issue_id
int64 2.03k
426k
| title
stringlengths 9
251
| body
stringlengths 1
32.8k
⌀ | status
stringclasses 6
values | after_fix_sha
stringlengths 7
7
| project_name
stringclasses 6
values | repo_url
stringclasses 6
values | repo_name
stringclasses 6
values | language
stringclasses 1
value | issue_url
null | before_fix_sha
null | pull_url
null | commit_datetime
timestamp[us, tz=UTC] | report_datetime
timestamp[us, tz=UTC] | updated_file
stringlengths 2
187
| file_content
stringlengths 0
368k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
41,443 |
Bug 41443 overview ruler not working
|
smoke test for 20030812 The overview ruler in the Java editor does not work when starting with a fresh workspace as described in the smoke test scenario.
|
resolved fixed
|
dd1da3a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-13T08:28:54Z | 2003-08-12T17:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/JavaEditor.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.javaeditor;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ResourceBundle;
import java.util.StringTokenizer;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Preferences;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BidiSegmentEvent;
import org.eclipse.swt.custom.BidiSegmentListener;
import org.eclipse.swt.custom.StyleRange;
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.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
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.Separator;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.IPostSelectionProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.text.BadLocationException;
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.ITextInputListener;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.ITextViewerExtension2;
import org.eclipse.jface.text.ITextViewerExtension3;
import org.eclipse.jface.text.ITextViewerExtension4;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.text.information.IInformationProvider;
import org.eclipse.jface.text.information.IInformationProviderExtension2;
import org.eclipse.jface.text.information.InformationPresenter;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.AnnotationRulerColumn;
import org.eclipse.jface.text.source.ChangeRulerColumn;
import org.eclipse.jface.text.source.CompositeRuler;
import org.eclipse.jface.text.source.IAnnotationAccess;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.IAnnotationModelExtension;
import org.eclipse.jface.text.source.IChangeRulerColumn;
import org.eclipse.jface.text.source.IOverviewRuler;
import org.eclipse.jface.text.source.ISharedTextColors;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.ISourceViewerExtension;
import org.eclipse.jface.text.source.IVerticalRuler;
import org.eclipse.jface.text.source.IVerticalRulerColumn;
import org.eclipse.jface.text.source.LineNumberChangeRulerColumn;
import org.eclipse.jface.text.source.LineNumberRulerColumn;
import org.eclipse.jface.text.source.OverviewRuler;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
import org.eclipse.ui.IEditorActionBarContributor;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPartService;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.editors.quickdiff.IQuickDiffProviderImplementation;
import org.eclipse.ui.editors.text.DefaultEncodingSupport;
import org.eclipse.ui.editors.text.IEncodingSupport;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.internal.editors.quickdiff.DocumentLineDiffer;
import org.eclipse.ui.internal.editors.quickdiff.ReferenceProviderDescriptor;
import org.eclipse.ui.internal.editors.text.EditorsPlugin;
import org.eclipse.ui.part.EditorActionBarContributor;
import org.eclipse.ui.part.IShowInTargetList;
import org.eclipse.ui.texteditor.AddTaskAction;
import org.eclipse.ui.texteditor.AnnotationPreference;
import org.eclipse.ui.texteditor.DefaultRangeIndicator;
import org.eclipse.ui.texteditor.IAbstractTextEditorHelpContextIds;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.ui.texteditor.IEditorStatusLine;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
import org.eclipse.ui.texteditor.MarkerAnnotation;
import org.eclipse.ui.texteditor.MarkerAnnotationPreferences;
import org.eclipse.ui.texteditor.ResourceAction;
import org.eclipse.ui.texteditor.SourceViewerDecorationSupport;
import org.eclipse.ui.texteditor.StatusTextEditor;
import org.eclipse.ui.texteditor.TextEditorAction;
import org.eclipse.ui.texteditor.TextOperationAction;
import org.eclipse.ui.views.contentoutline.ContentOutline;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
import org.eclipse.ui.views.tasklist.TaskList;
import org.eclipse.search.ui.SearchUI;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICodeAssist;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IImportContainer;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IPackageDeclaration;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.ISourceReference;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.actions.IJavaEditorActionDefinitionIds;
import org.eclipse.jdt.ui.actions.JavaSearchActionGroup;
import org.eclipse.jdt.ui.actions.OpenEditorActionGroup;
import org.eclipse.jdt.ui.actions.OpenViewActionGroup;
import org.eclipse.jdt.ui.actions.ShowActionGroup;
import org.eclipse.jdt.ui.text.IColorManager;
import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.GoToNextPreviousMemberAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.SelectionHistory;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectEnclosingAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectHistoryAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectNextAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectPreviousAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectionAction;
import org.eclipse.jdt.internal.ui.text.HTMLTextPresenter;
import org.eclipse.jdt.internal.ui.text.IJavaPartitions;
import org.eclipse.jdt.internal.ui.text.JavaChangeHover;
import org.eclipse.jdt.internal.ui.text.JavaPairMatcher;
import org.eclipse.jdt.internal.ui.util.JavaUIHelp;
import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider;
/**
* Java specific text editor.
*/
public abstract class JavaEditor extends StatusTextEditor implements IViewPartInputProvider {
/**
* Internal implementation class for a change listener.
* @since 3.0
*/
protected abstract class AbstractSelectionChangedListener implements ISelectionChangedListener {
/**
* Installs this selection changed listener with the given selection provider. If
* the selection provider is a post selection provider, post selection changed
* events are the preferred choice, otherwise normal selection changed events
* are requested.
*
* @param selectionProvider
*/
public void install(ISelectionProvider selectionProvider) {
if (selectionProvider == null)
return;
if (selectionProvider instanceof IPostSelectionProvider) {
IPostSelectionProvider provider= (IPostSelectionProvider) selectionProvider;
provider.addPostSelectionChangedListener(this);
} else {
selectionProvider.addSelectionChangedListener(this);
}
}
/**
* Removes this selection changed listener from the given selection provider.
*
* @param selectionProvider
*/
public void uninstall(ISelectionProvider selectionProvider) {
if (selectionProvider == null)
return;
if (selectionProvider instanceof IPostSelectionProvider) {
IPostSelectionProvider provider= (IPostSelectionProvider) selectionProvider;
provider.removePostSelectionChangedListener(this);
} else {
selectionProvider.removeSelectionChangedListener(this);
}
}
}
/**
* Updates the Java outline page selection and this editor's range indicator.
*
* @since 3.0
*/
private class EditorSelectionChangedListener extends AbstractSelectionChangedListener {
/*
* @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent)
*/
public void selectionChanged(SelectionChangedEvent event) {
selectionChanged();
}
public void selectionChanged() {
ISourceReference element= computeHighlightRangeSourceReference();
synchronizeOutlinePage(element);
setSelection(element, false);
}
}
/**
* Updates the selection in the editor's widget with the selection of the outline page.
*/
class OutlineSelectionChangedListener extends AbstractSelectionChangedListener {
public void selectionChanged(SelectionChangedEvent event) {
doSelectionChanged(event);
}
}
/*
* Link mode.
*/
class MouseClickListener implements KeyListener, MouseListener, MouseMoveListener,
FocusListener, PaintListener, IPropertyChangeListener, IDocumentListener, ITextInputListener {
/** The session is active. */
private boolean fActive;
/** The currently active style range. */
private IRegion fActiveRegion;
/** The currently active style range as position. */
private Position fRememberedPosition;
/** The hand cursor. */
private Cursor fCursor;
/** The link color. */
private Color fColor;
/** The key modifier mask. */
private int fKeyModifierMask;
public void deactivate() {
deactivate(false);
}
public void deactivate(boolean redrawAll) {
if (!fActive)
return;
repairRepresentation(redrawAll);
fActive= false;
}
public void install() {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
StyledText text= sourceViewer.getTextWidget();
if (text == null || text.isDisposed())
return;
updateColor(sourceViewer);
sourceViewer.addTextInputListener(this);
IDocument document= sourceViewer.getDocument();
if (document != null)
document.addDocumentListener(this);
text.addKeyListener(this);
text.addMouseListener(this);
text.addMouseMoveListener(this);
text.addFocusListener(this);
text.addPaintListener(this);
updateKeyModifierMask();
IPreferenceStore preferenceStore= getPreferenceStore();
preferenceStore.addPropertyChangeListener(this);
}
private void updateKeyModifierMask() {
String modifiers= getPreferenceStore().getString(BROWSER_LIKE_LINKS_KEY_MODIFIER);
fKeyModifierMask= computeStateMask(modifiers);
if (fKeyModifierMask == -1) {
// Fallback to stored state mask
fKeyModifierMask= getPreferenceStore().getInt(BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK);
}
}
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;
}
public void uninstall() {
if (fColor != null) {
fColor.dispose();
fColor= null;
}
if (fCursor != null) {
fCursor.dispose();
fCursor= null;
}
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
sourceViewer.removeTextInputListener(this);
IDocument document= sourceViewer.getDocument();
if (document != null)
document.removeDocumentListener(this);
IPreferenceStore preferenceStore= getPreferenceStore();
if (preferenceStore != null)
preferenceStore.removePropertyChangeListener(this);
StyledText text= sourceViewer.getTextWidget();
if (text == null || text.isDisposed())
return;
text.removeKeyListener(this);
text.removeMouseListener(this);
text.removeMouseMoveListener(this);
text.removeFocusListener(this);
text.removePaintListener(this);
}
/*
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
if (event.getProperty().equals(JavaEditor.LINK_COLOR)) {
ISourceViewer viewer= getSourceViewer();
if (viewer != null)
updateColor(viewer);
} else if (event.getProperty().equals(BROWSER_LIKE_LINKS_KEY_MODIFIER)) {
updateKeyModifierMask();
}
}
private void updateColor(ISourceViewer viewer) {
if (fColor != null)
fColor.dispose();
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
Display display= text.getDisplay();
fColor= createColor(getPreferenceStore(), JavaEditor.LINK_COLOR, display);
}
/**
* 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);
if (rgb != null)
return new Color(display, rgb);
}
return null;
}
private void repairRepresentation() {
repairRepresentation(false);
}
private void repairRepresentation(boolean redrawAll) {
if (fActiveRegion == null)
return;
ISourceViewer viewer= getSourceViewer();
if (viewer != null) {
resetCursor(viewer);
int offset= fActiveRegion.getOffset();
int length= fActiveRegion.getLength();
// remove style
if (!redrawAll && viewer instanceof ITextViewerExtension2)
((ITextViewerExtension2) viewer).invalidateTextPresentation(offset, length);
else
viewer.invalidateTextPresentation();
// remove underline
if (viewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) viewer;
offset= extension.modelOffset2WidgetOffset(offset);
} else {
offset -= viewer.getVisibleRegion().getOffset();
}
StyledText text= viewer.getTextWidget();
try {
text.redrawRange(offset, length, true);
} catch (IllegalArgumentException x) {
JavaPlugin.log(x);
}
}
fActiveRegion= null;
}
// will eventually be replaced by a method provided by jdt.core
private IRegion selectWord(IDocument document, int anchor) {
try {
int offset= anchor;
char c;
while (offset >= 0) {
c= document.getChar(offset);
if (!Character.isJavaIdentifierPart(c))
break;
--offset;
}
int start= offset;
offset= anchor;
int length= document.getLength();
while (offset < length) {
c= document.getChar(offset);
if (!Character.isJavaIdentifierPart(c))
break;
++offset;
}
int end= offset;
if (start == end)
return new Region(start, 0);
else
return new Region(start + 1, end - start - 1);
} catch (BadLocationException x) {
return null;
}
}
IRegion getCurrentTextRegion(ISourceViewer viewer) {
int offset= getCurrentTextOffset(viewer);
if (offset == -1)
return null;
IJavaElement input= SelectionConverter.getInput(JavaEditor.this);
if (input == null)
return null;
try {
IJavaElement[] elements= null;
synchronized (input) {
elements= ((ICodeAssist) input).codeSelect(offset, 0);
}
if (elements == null || elements.length == 0)
return null;
return selectWord(viewer.getDocument(), offset);
} catch (JavaModelException e) {
return null;
}
}
private int getCurrentTextOffset(ISourceViewer viewer) {
try {
StyledText text= viewer.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 (viewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) viewer;
return extension.widgetOffset2ModelOffset(widgetOffset);
} else {
return widgetOffset + viewer.getVisibleRegion().getOffset();
}
} catch (IllegalArgumentException e) {
return -1;
}
}
private void highlightRegion(ISourceViewer viewer, IRegion region) {
if (region.equals(fActiveRegion))
return;
repairRepresentation();
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
// highlight region
int offset= 0;
int length= 0;
if (viewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) viewer;
IRegion widgetRange= extension.modelRange2WidgetRange(region);
if (widgetRange == null)
return;
offset= widgetRange.getOffset();
length= widgetRange.getLength();
} else {
offset= region.getOffset() - viewer.getVisibleRegion().getOffset();
length= region.getLength();
}
StyleRange oldStyleRange= text.getStyleRangeAtOffset(offset);
Color foregroundColor= fColor;
Color backgroundColor= oldStyleRange == null ? text.getBackground() : oldStyleRange.background;
StyleRange styleRange= new StyleRange(offset, length, foregroundColor, backgroundColor);
text.setStyleRange(styleRange);
// underline
text.redrawRange(offset, length, true);
fActiveRegion= region;
}
private void activateCursor(ISourceViewer 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 void resetCursor(ISourceViewer viewer) {
StyledText text= viewer.getTextWidget();
if (text != null && !text.isDisposed())
text.setCursor(null);
if (fCursor != null) {
fCursor.dispose();
fCursor= null;
}
}
/*
* @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.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;
deactivate();
if (wasActive) {
IAction action= getAction("OpenEditor"); //$NON-NLS-1$
if (action != null)
action.run();
}
}
/*
* @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;
}
ISourceViewer viewer= getSourceViewer();
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= getCurrentTextRegion(viewer);
if (region == null || region.getLength() == 0) {
repairRepresentation();
return;
}
highlightRegion(viewer, region);
activateCursor(viewer);
}
/*
* @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();
}
/*
* @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 && !fRememberedPosition.isDeleted()) {
event.getDocument().removePosition(fRememberedPosition);
fActiveRegion= new Region(fRememberedPosition.getOffset(), fRememberedPosition.getLength());
}
fRememberedPosition= null;
ISourceViewer viewer= getSourceViewer();
if (viewer != null) {
StyledText widget= viewer.getTextWidget();
if (widget != null && !widget.isDisposed()) {
widget.getDisplay().asyncExec(new Runnable() {
public void run() {
deactivate();
}
});
}
}
}
/*
* @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);
}
/*
* @see PaintListener#paintControl(PaintEvent)
*/
public void paintControl(PaintEvent event) {
if (fActiveRegion == null)
return;
ISourceViewer viewer= getSourceViewer();
if (viewer == null)
return;
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
int offset= 0;
int length= 0;
if (viewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) viewer;
IRegion widgetRange= extension.modelRange2WidgetRange(new Region(offset, length));
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);
}
private boolean includes(IRegion region, IRegion position) {
return
position.getOffset() >= region.getOffset() &&
position.getOffset() + position.getLength() <= region.getOffset() + region.getLength();
}
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 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;
}
}
/**
* This action dispatches into two behaviours: If there is no current text
* hover, the javadoc is displayed using information presenter. If there is
* a current text hover, it is converted into a information presenter in
* order to make it sticky.
*/
class InformationDispatchAction extends TextEditorAction {
/** The wrapped text operation action. */
private final TextOperationAction fTextOperationAction;
/**
* Creates a dispatch action.
*/
public InformationDispatchAction(ResourceBundle resourceBundle, String prefix, final TextOperationAction textOperationAction) {
super(resourceBundle, prefix, JavaEditor.this);
if (textOperationAction == null)
throw new IllegalArgumentException();
fTextOperationAction= textOperationAction;
}
/*
* @see org.eclipse.jface.action.IAction#run()
*/
public void run() {
/**
* Information provider used to present the information.
*
* @since 3.0
*/
class InformationProvider implements IInformationProvider, IInformationProviderExtension2 {
private IRegion fHoverRegion;
private String fHoverInfo;
private IInformationControlCreator fControlCreator;
InformationProvider(IRegion hoverRegion, String hoverInfo, IInformationControlCreator controlCreator) {
fHoverRegion= hoverRegion;
fHoverInfo= hoverInfo;
fControlCreator= controlCreator;
}
/*
* @see org.eclipse.jface.text.information.IInformationProvider#getSubject(org.eclipse.jface.text.ITextViewer, int)
*/
public IRegion getSubject(ITextViewer textViewer, int invocationOffset) {
return fHoverRegion;
}
/*
* @see org.eclipse.jface.text.information.IInformationProvider#getInformation(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion)
*/
public String getInformation(ITextViewer textViewer, IRegion subject) {
return fHoverInfo;
}
/*
* @see org.eclipse.jface.text.information.IInformationProviderExtension2#getInformationPresenterControlCreator()
* @since 3.0
*/
public IInformationControlCreator getInformationPresenterControlCreator() {
return fControlCreator;
}
}
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null) {
fTextOperationAction.run();
return;
}
if (sourceViewer instanceof ITextViewerExtension4) {
ITextViewerExtension4 extension4= (ITextViewerExtension4) sourceViewer;
extension4.moveFocusToWidgetToken();
}
if (! (sourceViewer instanceof ITextViewerExtension2)) {
fTextOperationAction.run();
return;
}
ITextViewerExtension2 textViewerExtension2= (ITextViewerExtension2) sourceViewer;
// does a text hover exist?
ITextHover textHover= textViewerExtension2.getCurrentTextHover();
if (textHover == null) {
fTextOperationAction.run();
return;
}
Point hoverEventLocation= textViewerExtension2.getHoverEventLocation();
int offset= computeOffsetAtLocation(sourceViewer, hoverEventLocation.x, hoverEventLocation.y);
if (offset == -1) {
fTextOperationAction.run();
return;
}
try {
// get the text hover content
IDocument document= sourceViewer.getDocument();
String contentType= document.getContentType(offset);
IRegion hoverRegion= textHover.getHoverRegion(sourceViewer, offset);
if (hoverRegion == null)
return;
String hoverInfo= textHover.getHoverInfo(sourceViewer, hoverRegion);
IInformationControlCreator controlCreator= null;
if (textHover instanceof IInformationProviderExtension2)
controlCreator= ((IInformationProviderExtension2)textHover).getInformationPresenterControlCreator();
IInformationProvider informationProvider= new InformationProvider(hoverRegion, hoverInfo, controlCreator);
fInformationPresenter.setOffset(offset);
fInformationPresenter.setInformationProvider(informationProvider, contentType);
fInformationPresenter.showInformation();
} catch (BadLocationException e) {
}
}
// modified version from TextViewer
private int computeOffsetAtLocation(ITextViewer textViewer, int x, int y) {
StyledText styledText= textViewer.getTextWidget();
IDocument document= textViewer.getDocument();
if (document == null)
return -1;
try {
int widgetLocation= styledText.getOffsetAtLocation(new Point(x, y));
if (textViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) textViewer;
return extension.widgetOffset2ModelOffset(widgetLocation);
} else {
IRegion visibleRegion= textViewer.getVisibleRegion();
return widgetLocation + visibleRegion.getOffset();
}
} catch (IllegalArgumentException e) {
return -1;
}
}
}
static protected class AnnotationAccess implements IAnnotationAccess {
/*
* @see org.eclipse.jface.text.source.IAnnotationAccess#getType(org.eclipse.jface.text.source.Annotation)
*/
public Object getType(Annotation annotation) {
if (annotation instanceof IJavaAnnotation) {
IJavaAnnotation javaAnnotation= (IJavaAnnotation) annotation;
if (javaAnnotation.isRelevant())
return javaAnnotation.getAnnotationType();
}
return null;
}
/*
* @see org.eclipse.jface.text.source.IAnnotationAccess#isMultiLine(org.eclipse.jface.text.source.Annotation)
*/
public boolean isMultiLine(Annotation annotation) {
return true;
}
/*
* @see org.eclipse.jface.text.source.IAnnotationAccess#isTemporary(org.eclipse.jface.text.source.Annotation)
*/
public boolean isTemporary(Annotation annotation) {
if (annotation instanceof IJavaAnnotation) {
IJavaAnnotation javaAnnotation= (IJavaAnnotation) annotation;
if (javaAnnotation.isRelevant())
return javaAnnotation.isTemporary();
}
return false;
}
}
private class PropertyChangeListener implements org.eclipse.core.runtime.Preferences.IPropertyChangeListener {
/*
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
handlePreferencePropertyChanged(event);
}
}
/** Preference key for showing the line number ruler */
protected final static String LINE_NUMBER_RULER= PreferenceConstants.EDITOR_LINE_NUMBER_RULER;
/** Preference key for the foreground color of the line numbers */
protected final static String LINE_NUMBER_COLOR= PreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR;
/** Preference key for the link color */
protected final static String LINK_COLOR= PreferenceConstants.EDITOR_LINK_COLOR;
/** Preference key for matching brackets */
protected final static String MATCHING_BRACKETS= PreferenceConstants.EDITOR_MATCHING_BRACKETS;
/** Preference key for matching brackets color */
protected final static String MATCHING_BRACKETS_COLOR= PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR;
/** Preference key for highlighting current line */
protected final static String CURRENT_LINE= PreferenceConstants.EDITOR_CURRENT_LINE;
/** Preference key for highlight color of current line */
protected final static String CURRENT_LINE_COLOR= PreferenceConstants.EDITOR_CURRENT_LINE_COLOR;
/** Preference key for showing print marging ruler */
protected final static String PRINT_MARGIN= PreferenceConstants.EDITOR_PRINT_MARGIN;
/** Preference key for print margin ruler color */
protected final static String PRINT_MARGIN_COLOR= PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR;
/** Preference key for print margin ruler column */
protected final static String PRINT_MARGIN_COLUMN= PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN;
/** Preference key for error indication */
protected final static String ERROR_INDICATION= PreferenceConstants.EDITOR_PROBLEM_INDICATION;
/** Preference key for error color */
protected final static String ERROR_INDICATION_COLOR= PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR;
/** Preference key for warning indication */
protected final static String WARNING_INDICATION= PreferenceConstants.EDITOR_WARNING_INDICATION;
/** Preference key for warning color */
protected final static String WARNING_INDICATION_COLOR= PreferenceConstants.EDITOR_WARNING_INDICATION_COLOR;
/** Preference key for task indication */
protected final static String TASK_INDICATION= PreferenceConstants.EDITOR_TASK_INDICATION;
/** Preference key for task color */
protected final static String TASK_INDICATION_COLOR= PreferenceConstants.EDITOR_TASK_INDICATION_COLOR;
/** Preference key for bookmark indication */
protected final static String BOOKMARK_INDICATION= PreferenceConstants.EDITOR_BOOKMARK_INDICATION;
/** Preference key for bookmark color */
protected final static String BOOKMARK_INDICATION_COLOR= PreferenceConstants.EDITOR_BOOKMARK_INDICATION_COLOR;
/** Preference key for search result indication */
protected final static String SEARCH_RESULT_INDICATION= PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION;
/** Preference key for search result color */
protected final static String SEARCH_RESULT_INDICATION_COLOR= PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_COLOR;
/** Preference key for unknown annotation indication */
protected final static String UNKNOWN_INDICATION= PreferenceConstants.EDITOR_UNKNOWN_INDICATION;
/** Preference key for unknown annotation color */
protected final static String UNKNOWN_INDICATION_COLOR= PreferenceConstants.EDITOR_UNKNOWN_INDICATION_COLOR;
/** Preference key for shwoing the overview ruler */
protected final static String OVERVIEW_RULER= PreferenceConstants.EDITOR_OVERVIEW_RULER;
/** Preference key for error indication in overview ruler */
protected final static String ERROR_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER;
/** Preference key for warning indication in overview ruler */
protected final static String WARNING_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER;
/** Preference key for task indication in overview ruler */
protected final static String TASK_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER;
/** Preference key for bookmark indication in overview ruler */
protected final static String BOOKMARK_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER;
/** Preference key for search result indication in overview ruler */
protected final static String SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER;
/** Preference key for unknown annotation indication in overview ruler */
protected final static String UNKNOWN_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER;
/** Preference key for compiler task tags */
private final static String COMPILER_TASK_TAGS= JavaCore.COMPILER_TASK_TAGS;
/** Preference key for browser like links */
private final static String BROWSER_LIKE_LINKS= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS;
/** Preference key for key modifier of browser like links */
private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER;
/**
* Preference key for key modifier mask of browser like links.
* The value is only used if the value of <code>EDITOR_BROWSER_LIKE_LINKS</code>
* cannot be resolved to valid SWT modifier bits.
*
* @since 2.1.1
*/
private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK;
protected final static char[] BRACKETS= { '{', '}', '(', ')', '[', ']' };
/** The outline page */
protected JavaOutlinePage fOutlinePage;
/** Outliner context menu Id */
protected String fOutlinerContextMenuId;
/**
* The editor selection changed listener.
*
* @since 3.0
*/
private EditorSelectionChangedListener fEditorSelectionChangedListener;
/** The selection changed listener */
protected AbstractSelectionChangedListener fOutlineSelectionChangedListener= new OutlineSelectionChangedListener();
/** The editor's bracket matcher */
protected JavaPairMatcher fBracketMatcher= new JavaPairMatcher(BRACKETS);
/** The line number ruler column */
private LineNumberRulerColumn fLineNumberRulerColumn;
/**
* The change ruler column.
* @since 3.0
*/
private IChangeRulerColumn fChangeRulerColumn;
/** This editor's encoding support */
private DefaultEncodingSupport fEncodingSupport;
/** The mouse listener */
private MouseClickListener fMouseListener;
/** The information presenter. */
private InformationPresenter fInformationPresenter;
/**
* The annotation preferences.
* @since 3.0
*/
private MarkerAnnotationPreferences fAnnotationPreferences;
/** The annotation access */
protected IAnnotationAccess fAnnotationAccess= new AnnotationAccess();
/** The source viewer decoration support */
protected SourceViewerDecorationSupport fSourceViewerDecorationSupport;
/** The overview ruler */
protected OverviewRuler fOverviewRuler;
/** History for structure select action */
private SelectionHistory fSelectionHistory;
/** The preference property change listener for java core. */
private org.eclipse.core.runtime.Preferences.IPropertyChangeListener fPropertyChangeListener= new PropertyChangeListener();
protected CompositeActionGroup fActionGroups;
private CompositeActionGroup fContextMenuGroup;
/**
* Whether quick diff information is displayed, either on a change ruler or the line number ruler.
* @since 3.0
*/
private boolean fIsChangeInformationShown;
/**
* Returns the most narrow java element including the given offset.
*
* @param offset the offset inside of the requested element
* @return the most narrow java element
*/
abstract protected IJavaElement getElementAt(int offset);
/**
* Returns the java element of this editor's input corresponding to the given IJavaElement
*/
abstract protected IJavaElement getCorrespondingElement(IJavaElement element);
/**
* Sets the input of the editor's outline page.
*/
abstract protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input);
/**
* Default constructor.
*/
public JavaEditor() {
super();
fAnnotationPreferences= new MarkerAnnotationPreferences();
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
setSourceViewerConfiguration(new JavaSourceViewerConfiguration(textTools, this));
setRangeIndicator(new DefaultRangeIndicator());
setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore());
setKeyBindingScopes(new String[] { "org.eclipse.jdt.ui.javaEditorScope" }); //$NON-NLS-1$
}
/*
* @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
*/
protected final ISourceViewer createSourceViewer(Composite parent, IVerticalRuler verticalRuler, int styles) {
ISharedTextColors sharedColors= JavaPlugin.getDefault().getJavaTextTools().getColorManager();
fOverviewRuler= new OverviewRuler(fAnnotationAccess, VERTICAL_RULER_WIDTH, sharedColors);
fOverviewRuler.addHeaderAnnotationType(AnnotationType.WARNING);
fOverviewRuler.addHeaderAnnotationType(AnnotationType.ERROR);
ISourceViewer viewer= createJavaSourceViewer(parent, verticalRuler, fOverviewRuler, isOverviewRulerVisible(), styles);
StyledText text= viewer.getTextWidget();
text.addBidiSegmentListener(new BidiSegmentListener() {
public void lineGetSegments(BidiSegmentEvent event) {
event.segments= getBidiLineSegments(event.lineOffset, event.lineText);
}
});
JavaUIHelp.setHelp(this, text, IJavaHelpContextIds.JAVA_EDITOR);
fSourceViewerDecorationSupport= new SourceViewerDecorationSupport(viewer, fOverviewRuler, fAnnotationAccess, sharedColors);
configureSourceViewerDecorationSupport();
return viewer;
}
public final ISourceViewer getViewer() {
return getSourceViewer();
}
/*
* @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
*/
protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean isOverviewRulerVisible, int styles) {
return new JavaSourceViewer(parent, verticalRuler, fOverviewRuler, isOverviewRulerVisible(), styles);
}
/*
* @see AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent)
*/
protected boolean affectsTextPresentation(PropertyChangeEvent event) {
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
return textTools.affectsBehavior(event);
}
/**
* Sets the outliner's context menu ID.
*/
protected void setOutlinerContextMenuId(String menuId) {
fOutlinerContextMenuId= menuId;
}
/**
* Returns the standard action group of this editor.
*/
protected ActionGroup getActionGroup() {
return fActionGroups;
}
/*
* @see AbstractTextEditor#editorContextMenuAboutToShow
*/
public void editorContextMenuAboutToShow(IMenuManager menu) {
super.editorContextMenuAboutToShow(menu);
menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, new Separator(IContextMenuConstants.GROUP_OPEN));
menu.insertAfter(IContextMenuConstants.GROUP_OPEN, new GroupMarker(IContextMenuConstants.GROUP_SHOW));
ActionContext context= new ActionContext(getSelectionProvider().getSelection());
fContextMenuGroup.setContext(context);
fContextMenuGroup.fillContextMenu(menu);
fContextMenuGroup.setContext(null);
}
/**
* Creates the outline page used with this editor.
*/
protected JavaOutlinePage createOutlinePage() {
JavaOutlinePage page= new JavaOutlinePage(fOutlinerContextMenuId, this);
fOutlineSelectionChangedListener.install(page);
setOutlinePageInput(page, getEditorInput());
return page;
}
/**
* Informs the editor that its outliner has been closed.
*/
public void outlinePageClosed() {
if (fOutlinePage != null) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage= null;
resetHighlightRange();
}
}
/**
* Synchronizes the outliner selection with the given element
* position in the editor.
*
* @param element the java element to select
*/
protected void synchronizeOutlinePage(ISourceReference element) {
if (fOutlinePage != null && element != null && !isJavaOutlinePageActive()) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage.select(element);
fOutlineSelectionChangedListener.install(fOutlinePage);
}
}
/**
* Synchronizes the outliner selection with the actual cursor
* position in the editor.
*/
public void synchronizeOutlinePageSelection() {
synchronizeOutlinePage(computeHighlightRangeSourceReference());
}
/*
* Get the desktop's StatusLineManager
*/
protected IStatusLineManager getStatusLineManager() {
IEditorActionBarContributor contributor= getEditorSite().getActionBarContributor();
if (contributor instanceof EditorActionBarContributor) {
return ((EditorActionBarContributor) contributor).getActionBars().getStatusLineManager();
}
return null;
}
/*
* @see AbstractTextEditor#getAdapter(Class)
*/
public Object getAdapter(Class required) {
if (IContentOutlinePage.class.equals(required)) {
if (fOutlinePage == null)
fOutlinePage= createOutlinePage();
return fOutlinePage;
}
if (IEncodingSupport.class.equals(required))
return fEncodingSupport;
if (required == IShowInTargetList.class) {
return new IShowInTargetList() {
public String[] getShowInTargetIds() {
return new String[] { JavaUI.ID_PACKAGES, IPageLayout.ID_OUTLINE, IPageLayout.ID_RES_NAV };
}
};
}
return super.getAdapter(required);
}
protected void setSelection(ISourceReference reference, boolean moveCursor) {
ISelection selection= getSelectionProvider().getSelection();
if (selection instanceof TextSelection) {
TextSelection textSelection= (TextSelection) selection;
if (textSelection.getOffset() != 0 || textSelection.getLength() != 0)
markInNavigationHistory();
}
if (reference != null) {
StyledText textWidget= null;
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer != null)
textWidget= sourceViewer.getTextWidget();
if (textWidget == null)
return;
try {
ISourceRange range= reference.getSourceRange();
if (range == null)
return;
int offset= range.getOffset();
int length= range.getLength();
if (offset < 0 || length < 0)
return;
setHighlightRange(offset, length, moveCursor);
if (!moveCursor)
return;
offset= -1;
length= -1;
if (reference instanceof IMember) {
range= ((IMember) reference).getNameRange();
if (range != null) {
offset= range.getOffset();
length= range.getLength();
}
} else if (reference instanceof IImportDeclaration) {
String name= ((IImportDeclaration) reference).getElementName();
if (name != null && name.length() > 0) {
String content= reference.getSource();
if (content != null) {
offset= range.getOffset() + content.indexOf(name);
length= name.length();
}
}
} else if (reference instanceof IPackageDeclaration) {
String name= ((IPackageDeclaration) reference).getElementName();
if (name != null && name.length() > 0) {
String content= reference.getSource();
if (content != null) {
offset= range.getOffset() + content.indexOf(name);
length= name.length();
}
}
}
if (offset > -1 && length > 0) {
try {
textWidget.setRedraw(false);
sourceViewer.revealRange(offset, length);
sourceViewer.setSelectedRange(offset, length);
} finally {
textWidget.setRedraw(true);
}
markInNavigationHistory();
}
} catch (JavaModelException x) {
} catch (IllegalArgumentException x) {
}
} else if (moveCursor) {
resetHighlightRange();
markInNavigationHistory();
}
}
public void setSelection(IJavaElement element) {
if (element == null || element instanceof ICompilationUnit || element instanceof IClassFile) {
/*
* If the element is an ICompilationUnit this unit is either the input
* of this editor or not being displayed. In both cases, nothing should
* happened. (http://dev.eclipse.org/bugs/show_bug.cgi?id=5128)
*/
return;
}
IJavaElement corresponding= getCorrespondingElement(element);
if (corresponding instanceof ISourceReference) {
ISourceReference reference= (ISourceReference) corresponding;
// set hightlight range
setSelection(reference, true);
// set outliner selection
if (fOutlinePage != null) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage.select(reference);
fOutlineSelectionChangedListener.install(fOutlinePage);
}
}
}
protected void doSelectionChanged(SelectionChangedEvent event) {
ISourceReference reference= null;
ISelection selection= event.getSelection();
Iterator iter= ((IStructuredSelection) selection).iterator();
while (iter.hasNext()) {
Object o= iter.next();
if (o instanceof ISourceReference) {
reference= (ISourceReference) o;
break;
}
}
if (!isActivePart() && JavaPlugin.getActivePage() != null)
JavaPlugin.getActivePage().bringToTop(this);
setSelection(reference, !isActivePart());
}
/*
* @see AbstractTextEditor#adjustHighlightRange(int, int)
*/
protected void adjustHighlightRange(int offset, int length) {
try {
IJavaElement element= getElementAt(offset);
while (element instanceof ISourceReference) {
ISourceRange range= ((ISourceReference) element).getSourceRange();
if (offset < range.getOffset() + range.getLength() && range.getOffset() < offset + length) {
setHighlightRange(range.getOffset(), range.getLength(), true);
if (fOutlinePage != null) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage.select((ISourceReference) element);
fOutlineSelectionChangedListener.install(fOutlinePage);
}
return;
}
element= element.getParent();
}
} catch (JavaModelException x) {
JavaPlugin.log(x.getStatus());
}
resetHighlightRange();
}
protected boolean isActivePart() {
IWorkbenchPart part= getActivePart();
return part != null && part.equals(this);
}
private boolean isJavaOutlinePageActive() {
IWorkbenchPart part= getActivePart();
return part instanceof ContentOutline && ((ContentOutline)part).getCurrentPage() == fOutlinePage;
}
private IWorkbenchPart getActivePart() {
IWorkbenchWindow window= getSite().getWorkbenchWindow();
IPartService service= window.getPartService();
IWorkbenchPart part= service.getActivePart();
return part;
}
/*
* @see StatusTextEditor#getStatusHeader(IStatus)
*/
protected String getStatusHeader(IStatus status) {
if (fEncodingSupport != null) {
String message= fEncodingSupport.getStatusHeader(status);
if (message != null)
return message;
}
return super.getStatusHeader(status);
}
/*
* @see StatusTextEditor#getStatusBanner(IStatus)
*/
protected String getStatusBanner(IStatus status) {
if (fEncodingSupport != null) {
String message= fEncodingSupport.getStatusBanner(status);
if (message != null)
return message;
}
return super.getStatusBanner(status);
}
/*
* @see StatusTextEditor#getStatusMessage(IStatus)
*/
protected String getStatusMessage(IStatus status) {
if (fEncodingSupport != null) {
String message= fEncodingSupport.getStatusMessage(status);
if (message != null)
return message;
}
return super.getStatusMessage(status);
}
/*
* @see AbstractTextEditor#doSetInput
*/
protected void doSetInput(IEditorInput input) throws CoreException {
super.doSetInput(input);
if (fEncodingSupport != null)
fEncodingSupport.reset();
setOutlinePageInput(fOutlinePage, input);
}
/*
* @see IWorkbenchPart#dispose()
*/
public void dispose() {
if (isBrowserLikeLinks())
disableBrowserLikeLinks();
if (fEncodingSupport != null) {
fEncodingSupport.dispose();
fEncodingSupport= null;
}
if (fPropertyChangeListener != null) {
Preferences preferences= JavaCore.getPlugin().getPluginPreferences();
preferences.removePropertyChangeListener(fPropertyChangeListener);
fPropertyChangeListener= null;
}
if (fSourceViewerDecorationSupport != null) {
fSourceViewerDecorationSupport.dispose();
fSourceViewerDecorationSupport= null;
}
if (fBracketMatcher != null) {
fBracketMatcher.dispose();
fBracketMatcher= null;
}
if (fSelectionHistory != null) {
fSelectionHistory.dispose();
fSelectionHistory= null;
}
if (fEditorSelectionChangedListener != null) {
fEditorSelectionChangedListener.uninstall(getSelectionProvider());
fEditorSelectionChangedListener= null;
}
super.dispose();
}
protected void createActions() {
super.createActions();
ResourceAction resAction= new AddTaskAction(JavaEditorMessages.getResourceBundle(), "AddTask.", this); //$NON-NLS-1$
resAction.setHelpContextId(IAbstractTextEditorHelpContextIds.ADD_TASK_ACTION);
resAction.setActionDefinitionId(ITextEditorActionDefinitionIds.ADD_TASK);
setAction(ITextEditorActionConstants.ADD_TASK, resAction);
ActionGroup oeg, ovg, jsg, sg;
fActionGroups= new CompositeActionGroup(new ActionGroup[] {
oeg= new OpenEditorActionGroup(this),
sg= new ShowActionGroup(this),
ovg= new OpenViewActionGroup(this),
jsg= new JavaSearchActionGroup(this)
});
fContextMenuGroup= new CompositeActionGroup(new ActionGroup[] {oeg, ovg, sg, jsg});
resAction= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc.", this, ISourceViewer.INFORMATION, true); //$NON-NLS-1$
resAction= new InformationDispatchAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc.", (TextOperationAction) resAction); //$NON-NLS-1$
resAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_JAVADOC);
setAction("ShowJavaDoc", resAction); //$NON-NLS-1$
WorkbenchHelp.setHelp(resAction, IJavaHelpContextIds.SHOW_JAVADOC_ACTION);
Action action= new GotoMatchingBracketAction(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_MATCHING_BRACKET);
setAction(GotoMatchingBracketAction.GOTO_MATCHING_BRACKET, action);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"ShowOutline.", this, JavaSourceViewer.SHOW_OUTLINE, true); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_OUTLINE);
setAction(IJavaEditorActionDefinitionIds.SHOW_OUTLINE, action);
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.SHOW_OUTLINE_ACTION);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"OpenStructure.", this, JavaSourceViewer.OPEN_STRUCTURE, true); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_STRUCTURE);
setAction(IJavaEditorActionDefinitionIds.OPEN_STRUCTURE, action);
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.OPEN_STRUCTURE_ACTION);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"OpenHierarchy.", this, JavaSourceViewer.SHOW_HIERARCHY, true); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_HIERARCHY);
setAction(IJavaEditorActionDefinitionIds.OPEN_HIERARCHY, action);
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.OPEN_HIERARCHY_ACTION);
fEncodingSupport= new DefaultEncodingSupport();
fEncodingSupport.initialize(this);
fSelectionHistory= new SelectionHistory(this);
action= new StructureSelectEnclosingAction(this, fSelectionHistory);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_ENCLOSING);
setAction(StructureSelectionAction.ENCLOSING, action);
action= new StructureSelectNextAction(this, fSelectionHistory);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_NEXT);
setAction(StructureSelectionAction.NEXT, action);
action= new StructureSelectPreviousAction(this, fSelectionHistory);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_PREVIOUS);
setAction(StructureSelectionAction.PREVIOUS, action);
StructureSelectHistoryAction historyAction= new StructureSelectHistoryAction(this, fSelectionHistory);
historyAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_LAST);
setAction(StructureSelectionAction.HISTORY, historyAction);
fSelectionHistory.setHistoryAction(historyAction);
action= GoToNextPreviousMemberAction.newGoToNextMemberAction(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_NEXT_MEMBER);
setAction(GoToNextPreviousMemberAction.NEXT_MEMBER, action);
action= GoToNextPreviousMemberAction.newGoToPreviousMemberAction(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_PREVIOUS_MEMBER);
setAction(GoToNextPreviousMemberAction.PREVIOUS_MEMBER, action);
}
public void updatedTitleImage(Image image) {
setTitleImage(image);
}
/*
* @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
*/
protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
try {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
String property= event.getProperty();
if (PreferenceConstants.EDITOR_TAB_WIDTH.equals(property)) {
Object value= event.getNewValue();
if (value instanceof Integer) {
sourceViewer.getTextWidget().setTabs(((Integer) value).intValue());
} else if (value instanceof String) {
sourceViewer.getTextWidget().setTabs(Integer.parseInt((String) value));
}
return;
}
if (OVERVIEW_RULER.equals(property)) {
if (isOverviewRulerVisible())
showOverviewRuler();
else
hideOverviewRuler();
return;
}
if (LINE_NUMBER_RULER.equals(property)) {
if (isLineNumberRulerVisible())
showLineNumberRuler();
else
hideLineNumberRuler();
return;
}
if (fLineNumberRulerColumn != null
&& (LINE_NUMBER_COLOR.equals(property)
|| PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT.equals(property)
|| PREFERENCE_COLOR_BACKGROUND.equals(property))) {
initializeLineNumberRulerColumn(fLineNumberRulerColumn);
}
if (PreferenceConstants.QUICK_DIFF_CHANGED_COLOR.equals(property)
|| PreferenceConstants.QUICK_DIFF_ADDED_COLOR.equals(property)
|| PreferenceConstants.QUICK_DIFF_DELETED_COLOR.equals(property)) {
if (fLineNumberRulerColumn instanceof IChangeRulerColumn)
initializeChangeRulerColumn((IChangeRulerColumn) fLineNumberRulerColumn);
else if (fChangeRulerColumn != null)
initializeChangeRulerColumn(fChangeRulerColumn);
}
if (isJavaEditorHoverProperty(property))
updateHoverBehavior();
if (BROWSER_LIKE_LINKS.equals(property)) {
if (isBrowserLikeLinks())
enableBrowserLikeLinks();
else
disableBrowserLikeLinks();
return;
}
if (PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE.equals(property)) {
if ((event.getNewValue() instanceof Boolean) && ((Boolean)event.getNewValue()).booleanValue()) {
fEditorSelectionChangedListener= new EditorSelectionChangedListener();
fEditorSelectionChangedListener.install(getSelectionProvider());
fEditorSelectionChangedListener.selectionChanged();
} else {
fEditorSelectionChangedListener.uninstall(getSelectionProvider());
fEditorSelectionChangedListener= null;
}
return;
}
if (PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE.equals(property)) {
if (event.getNewValue() instanceof Boolean) {
Boolean disable= (Boolean) event.getNewValue();
configureInsertMode(OVERWRITE, !disable.booleanValue());
}
}
} finally {
super.handlePreferenceStoreChanged(event);
}
}
private boolean isJavaEditorHoverProperty(String property) {
return PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS.equals(property);
}
/**
* Return whether the browser like links should be enabled
* according to the preference store settings.
* @return <code>true</code> if the browser like links should be enabled
*/
private boolean isBrowserLikeLinks() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(BROWSER_LIKE_LINKS);
}
/**
* Enables browser like links.
*/
private void enableBrowserLikeLinks() {
if (fMouseListener == null) {
fMouseListener= new MouseClickListener();
fMouseListener.install();
}
}
/**
* Disables browser like links.
*/
private void disableBrowserLikeLinks() {
if (fMouseListener != null) {
fMouseListener.uninstall();
fMouseListener= null;
}
}
/**
* Handles a property change event describing a change
* of the java core's preferences and updates the preference
* related editor properties.
*
* @param event the property change event
*/
protected void handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
if (COMPILER_TASK_TAGS.equals(event.getProperty())) {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer != null && affectsTextPresentation(new PropertyChangeEvent(event.getSource(), event.getProperty(), event.getOldValue(), event.getNewValue())))
sourceViewer.invalidateTextPresentation();
}
}
/*
* @see org.eclipse.ui.texteditor.ITextEditorExtension3#showChangeInformation(boolean)
*/
public void showChangeInformation(boolean show) {
if (show == fIsChangeInformationShown)
return;
if (fIsChangeInformationShown) {
uninstallChangeRulerModel();
showChangeRuler(false); // hide change ruler if its displayed - if the line number ruler is showing, only the colors get removed by deinstalling the model
} else {
ensureChangeInfoCanBeDisplayed(); // can be replaced w/ showChangeRuler(false) once the old line number ruler is gone
installChangeRulerModel();
}
fIsChangeInformationShown= show;
}
/**
* Installs the differ annotation model with the current quick diff display.
* @since R3.0
*/
private void installChangeRulerModel() {
IChangeRulerColumn column= getChangeColumn();
if (column != null)
column.setModel(getOrCreateDiffer());
}
/**
* Uninstalls the differ annotation model from the current quick diff display.
*
* @since R3.0
*/
private void uninstallChangeRulerModel() {
IChangeRulerColumn column= getChangeColumn();
if (column != null)
column.setModel(null);
}
/**
* Ensures that either the line number display is a <code>LineNumberChangeRuler</code> or
* a separate change ruler gets displayed.
*
* @since R3.0
*/
private void ensureChangeInfoCanBeDisplayed() {
if (isLineNumberRulerVisible()) {
if (!(fLineNumberRulerColumn instanceof IChangeRulerColumn)) {
hideLineNumberRuler();
// HACK: set state already so a change ruler is created. Not needed once always a change line number bar gets installed
fIsChangeInformationShown= true;
showLineNumberRuler();
}
} else
showChangeRuler(true);
}
/*
* @see org.eclipse.ui.texteditor.ITextEditorExtension3#isChangeInformationShowing()
*/
public boolean isChangeInformationShowing() {
return fIsChangeInformationShown;
}
/**
* Creates a new <code>DocumentLineDiffer</code> and installs it with <code>model</code>.
* The default reference provider is installed with the newly created differ.
*
* @param model the annotation model of the current document.
* @return a new <code>DocumentLineDiffer</code> instance.
* @since R3.0
*/
private DocumentLineDiffer createDiffer(IAnnotationModelExtension model) {
DocumentLineDiffer differ;
differ= new DocumentLineDiffer();
IQuickDiffProviderImplementation provider= getDefaultReferenceProvider();
if (provider != null)
differ.setReferenceProvider(provider);
model.addAnnotationModel(IChangeRulerColumn.QUICK_DIFF_MODEL_ID, differ);
return differ;
}
/**
* Returns the default quick diff reference provider. It is determined by first trying to
* enable the preferred provider as specified by the preferences; if this is unsuccessful, the
* default provider as specified by the extension point mechanism is installed. If that fails
* as well, <code>null</code> is returned.
*
* @return the default reference provider
* @since R3.0
*/
private IQuickDiffProviderImplementation getDefaultReferenceProvider() {
String defaultID= getPreferenceStore().getString(PreferenceConstants.QUICK_DIFF_DEFAULT_PROVIDER);
EditorsPlugin editorPlugin= EditorsPlugin.getDefault();
ReferenceProviderDescriptor[] descs= editorPlugin.getExtensions();
IQuickDiffProviderImplementation provider= null;
// try to fetch preferred provider; load if needed
for (int i= 0; i < descs.length; i++) {
if (descs[i].getId().equals(defaultID)) {
provider= descs[i].createProvider();
if (provider != null) {
provider.setActiveEditor(this);
if (provider.isEnabled())
break;
provider.dispose();
provider= null;
}
}
}
// if not found, get default provider as specified by the extension point
if (provider == null) {
ReferenceProviderDescriptor defaultDescriptor= editorPlugin.getDefaultProvider();
if (defaultDescriptor != null) {
provider= defaultDescriptor.createProvider();
if (provider != null) {
provider.setActiveEditor(this);
if (!provider.isEnabled()) {
provider.dispose();
provider= null;
}
}
}
}
return provider;
}
/**
* Returns the annotation model associated with the document displayed in the
* viewer if it is an <code>IAnnotationModelExtension</code>, or <code>null</code>.
*
* @return the displayed document's annotation model if it is an <code>IAnnotationModelExtension</code>, or <code>null</code>
* @since R3.0
*/
private IAnnotationModelExtension getModel() {
ISourceViewer viewer= getSourceViewer();
if (viewer == null)
return null;
IAnnotationModel m= viewer.getAnnotationModel();
if (m instanceof IAnnotationModelExtension)
return (IAnnotationModelExtension) m;
else
return null;
}
/**
* Extracts the line differ from the displayed document's annotation model. If none can be found,
* a new differ is created and attached to the annotation model.
*
* @return the linediffer, or <code>null</code> if none could be found or created.
* @since R3.0
*/
private DocumentLineDiffer getOrCreateDiffer() {
IAnnotationModelExtension model= getModel();
if (model == null)
return null;
DocumentLineDiffer differ= (DocumentLineDiffer)model.getAnnotationModel(IChangeRulerColumn.QUICK_DIFF_MODEL_ID);
if (differ == null)
differ= createDiffer(model);
return differ;
}
/**
* Returns the <code>IChangeRulerColumn</code> of this editor, or <code>null</code> if there is none. Either
* the line number bar or a separate change ruler column can be returned.
*
* @return an instance of <code>IChangeRulerColumn</code> or <code>null</code>.
* @since R3.0
*/
private IChangeRulerColumn getChangeColumn() {
if (fChangeRulerColumn != null)
return fChangeRulerColumn;
else if (fLineNumberRulerColumn instanceof IChangeRulerColumn)
return (IChangeRulerColumn) fLineNumberRulerColumn;
else
return null;
}
/**
* Sets the display state of the separate change ruler column (not the quick diff display on
* the line number ruler column) to <code>show</code>.
*
* @param show <code>true</code> if the change ruler column should be shown, <code>false</code> if it should be hidden
* @since R3.0
*/
private void showChangeRuler(boolean show) {
IVerticalRuler v= getVerticalRuler();
if (v instanceof CompositeRuler) {
CompositeRuler c= (CompositeRuler) v;
if (show && fChangeRulerColumn == null)
c.addDecorator(1, createChangeRulerColumn());
else if (!show && fChangeRulerColumn != null) {
c.removeDecorator(fChangeRulerColumn);
fChangeRulerColumn= null;
}
}
}
/**
* Shows the line number ruler column.
*/
private void showLineNumberRuler() {
showChangeRuler(false);
IVerticalRuler v= getVerticalRuler();
if (v instanceof CompositeRuler) {
CompositeRuler c= (CompositeRuler) v;
c.addDecorator(1, createLineNumberRulerColumn());
}
}
/**
* Hides the line number ruler column.
*/
private void hideLineNumberRuler() {
IVerticalRuler v= getVerticalRuler();
if (fLineNumberRulerColumn != null && v instanceof CompositeRuler) {
CompositeRuler c= (CompositeRuler) v;
c.removeDecorator(fLineNumberRulerColumn);
fLineNumberRulerColumn= null;
}
if (fIsChangeInformationShown)
showChangeRuler(true);
}
/**
* Return whether the line number ruler column should be
* visible according to the preference store settings.
*
* @return <code>true</code> if the line numbers should be visible
*/
private boolean isLineNumberRulerVisible() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(LINE_NUMBER_RULER);
}
/**
* Returns whether quick diff info should be visible upon opening an editor
* according to the preference store settings.
*
* @return <code>true</code> if the line numbers should be visible
* @since R3.0
*/
private boolean isQuickDiffAlwaysOn() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(PreferenceConstants.QUICK_DIFF_ALWAYS_ON);
}
/**
* Returns a segmentation of the line of the given document appropriate for bidi rendering.
* The default implementation returns only the string literals of a java code line as segments.
*
* @param document the document
* @param lineOffset the offset of the line
* @return the line's bidi segmentation
* @throws BadLocationException in case lineOffset is not valid in document
*/
public static int[] getBidiLineSegments(IDocument document, int lineOffset) throws BadLocationException {
IRegion line= document.getLineInformationOfOffset(lineOffset);
ITypedRegion[] linePartitioning= document.computePartitioning(lineOffset, line.getLength());
List segmentation= new ArrayList();
for (int i= 0; i < linePartitioning.length; i++) {
if (IJavaPartitions.JAVA_STRING.equals(linePartitioning[i].getType()))
segmentation.add(linePartitioning[i]);
}
if (segmentation.size() == 0)
return null;
int size= segmentation.size();
int[] segments= new int[size * 2 + 1];
int j= 0;
for (int i= 0; i < size; i++) {
ITypedRegion segment= (ITypedRegion) segmentation.get(i);
if (i == 0)
segments[j++]= 0;
int offset= segment.getOffset() - lineOffset;
if (offset > segments[j - 1])
segments[j++]= offset;
if (offset + segment.getLength() >= line.getLength())
break;
segments[j++]= offset + segment.getLength();
}
if (j < segments.length) {
int[] result= new int[j];
System.arraycopy(segments, 0, result, 0, j);
segments= result;
}
return segments;
}
/**
* Returns a segmentation of the given line appropriate for bidi rendering. The default
* implementation returns only the string literals of a java code line as segments.
*
* @param lineOffset the offset of the line
* @param line the content of the line
* @return the line's bidi segmentation
*/
protected int[] getBidiLineSegments(int widgetLineOffset, String line) {
IDocumentProvider provider= getDocumentProvider();
if (provider != null && line != null && line.length() > 0) {
IDocument document= provider.getDocument(getEditorInput());
if (document != null)
try {
int lineOffset;
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) sourceViewer;
lineOffset= extension.widgetOffset2ModelOffset(widgetLineOffset);
} else {
IRegion visible= sourceViewer.getVisibleRegion();
lineOffset= visible.getOffset() + widgetLineOffset;
}
return getBidiLineSegments(document, lineOffset);
} catch (BadLocationException x) {
// ignore
}
}
return null;
}
/**
* Initializes the given line number ruler column from the preference store.
*
* @param rulerColumn the ruler column to be initialized
*/
protected void initializeLineNumberRulerColumn(LineNumberRulerColumn rulerColumn) {
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
IColorManager manager= textTools.getColorManager();
IPreferenceStore store= getPreferenceStore();
if (store != null) {
RGB rgb= null;
// foreground color
if (store.contains(LINE_NUMBER_COLOR)) {
if (store.isDefault(LINE_NUMBER_COLOR))
rgb= PreferenceConverter.getDefaultColor(store, LINE_NUMBER_COLOR);
else
rgb= PreferenceConverter.getColor(store, LINE_NUMBER_COLOR);
}
rulerColumn.setForeground(manager.getColor(rgb));
rgb= null;
// background color
if (!store.getBoolean(PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT)) {
if (store.contains(PREFERENCE_COLOR_BACKGROUND)) {
if (store.isDefault(PREFERENCE_COLOR_BACKGROUND))
rgb= PreferenceConverter.getDefaultColor(store, PREFERENCE_COLOR_BACKGROUND);
else
rgb= PreferenceConverter.getColor(store, PREFERENCE_COLOR_BACKGROUND);
}
}
rulerColumn.setBackground(manager.getColor(rgb));
rulerColumn.redraw();
}
}
/**
* Creates a new line number ruler column that is appropriately initialized.
*
* @return a new line number ruler column
*/
protected IVerticalRulerColumn createLineNumberRulerColumn() {
if (isQuickDiffAlwaysOn() || isChangeInformationShowing()) {
LineNumberChangeRulerColumn column= new LineNumberChangeRulerColumn();
column.setHover(new JavaChangeHover());
initializeChangeRulerColumn(column);
fLineNumberRulerColumn= column;
} else {
fLineNumberRulerColumn= new LineNumberRulerColumn();
}
initializeLineNumberRulerColumn(fLineNumberRulerColumn);
return fLineNumberRulerColumn;
}
/**
* Initializes the given change ruler column from the preference store.
*
* @param changeColumn the ruler column to be initialized
* @since R3.0
*/
private void initializeChangeRulerColumn(IChangeRulerColumn changeColumn) {
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
IColorManager manager= textTools.getColorManager();
IPreferenceStore store= getPreferenceStore();
if (store != null) {
RGB rgb= null;
ISourceViewer v= getSourceViewer();
if (v != null && v.getAnnotationModel() != null) {
changeColumn.setModel(v.getAnnotationModel());
}
rgb= null;
// change color
if (!store.getBoolean(PreferenceConstants.QUICK_DIFF_CHANGED_COLOR)) {
if (store.contains(PreferenceConstants.QUICK_DIFF_CHANGED_COLOR)) {
if (store.isDefault(PreferenceConstants.QUICK_DIFF_CHANGED_COLOR))
rgb= PreferenceConverter.getDefaultColor(store, PreferenceConstants.QUICK_DIFF_CHANGED_COLOR);
else
rgb= PreferenceConverter.getColor(store, PreferenceConstants.QUICK_DIFF_CHANGED_COLOR);
}
}
changeColumn.setChangedColor(manager.getColor(rgb));
rgb= null;
// addition color
if (!store.getBoolean(PreferenceConstants.QUICK_DIFF_ADDED_COLOR)) {
if (store.contains(PreferenceConstants.QUICK_DIFF_ADDED_COLOR)) {
if (store.isDefault(PreferenceConstants.QUICK_DIFF_ADDED_COLOR))
rgb= PreferenceConverter.getDefaultColor(store, PreferenceConstants.QUICK_DIFF_ADDED_COLOR);
else
rgb= PreferenceConverter.getColor(store, PreferenceConstants.QUICK_DIFF_ADDED_COLOR);
}
}
changeColumn.setAddedColor(manager.getColor(rgb));
rgb= null;
// deletion indicator color
if (!store.getBoolean(PreferenceConstants.QUICK_DIFF_DELETED_COLOR)) {
if (store.contains(PreferenceConstants.QUICK_DIFF_DELETED_COLOR)) {
if (store.isDefault(PreferenceConstants.QUICK_DIFF_DELETED_COLOR))
rgb= PreferenceConverter.getDefaultColor(store, PreferenceConstants.QUICK_DIFF_DELETED_COLOR);
else
rgb= PreferenceConverter.getColor(store, PreferenceConstants.QUICK_DIFF_DELETED_COLOR);
}
}
changeColumn.setDeletedColor(manager.getColor(rgb));
}
changeColumn.redraw();
}
/**
* Creates a new change ruler column for quick diff display independent of the
* line number ruler column
*
* @return a new change ruler column
* @since R3.0
*/
protected IChangeRulerColumn createChangeRulerColumn() {
IChangeRulerColumn column= new ChangeRulerColumn();
column.setHover(new JavaChangeHover());
fChangeRulerColumn= column;
initializeChangeRulerColumn(fChangeRulerColumn);
return fChangeRulerColumn;
}
/*
* @see AbstractTextEditor#createVerticalRuler()
*/
protected IVerticalRuler createVerticalRuler() {
CompositeRuler ruler= new CompositeRuler();
ruler.addDecorator(0, new AnnotationRulerColumn(VERTICAL_RULER_WIDTH));
if (isLineNumberRulerVisible())
ruler.addDecorator(1, createLineNumberRulerColumn());
else if (isQuickDiffAlwaysOn())
ruler.addDecorator(1, createChangeRulerColumn());
return ruler;
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#updatePropertyDependentActions()
*/
protected void updatePropertyDependentActions() {
super.updatePropertyDependentActions();
if (fEncodingSupport != null)
fEncodingSupport.reset();
}
/*
* 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);
}
}
/*
* @see org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput()
*/
public Object getViewPartInput() {
return getEditorInput().getAdapter(IJavaElement.class);
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#doSetSelection(ISelection)
*/
protected void doSetSelection(ISelection selection) {
super.doSetSelection(selection);
synchronizeOutlinePageSelection();
}
/*
* @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite)
*/
public void createPartControl(Composite parent) {
super.createPartControl(parent);
fSourceViewerDecorationSupport.install(getPreferenceStore());
Preferences preferences= JavaCore.getPlugin().getPluginPreferences();
preferences.addPropertyChangeListener(fPropertyChangeListener);
IInformationControlCreator informationControlCreator= new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell shell) {
boolean cutDown= false;
int style= cutDown ? SWT.NONE : (SWT.V_SCROLL | SWT.H_SCROLL);
return new DefaultInformationControl(shell, SWT.RESIZE, style, new HTMLTextPresenter(cutDown));
}
};
fInformationPresenter= new InformationPresenter(informationControlCreator);
fInformationPresenter.setSizeConstraints(60, 10, true, true);
fInformationPresenter.install(getSourceViewer());
if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE)) {
fEditorSelectionChangedListener= new EditorSelectionChangedListener();
fEditorSelectionChangedListener.install(getSelectionProvider());
}
if (isBrowserLikeLinks())
enableBrowserLikeLinks();
if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE))
configureInsertMode(OVERWRITE, false);
if (isQuickDiffAlwaysOn())
showChangeInformation(true);
}
protected void showOverviewRuler() {
if (fOverviewRuler != null) {
if (getSourceViewer() instanceof ISourceViewerExtension) {
((ISourceViewerExtension) getSourceViewer()).showAnnotationsOverview(true);
fSourceViewerDecorationSupport.updateOverviewDecorations();
}
}
}
protected void hideOverviewRuler() {
if (getSourceViewer() instanceof ISourceViewerExtension) {
fSourceViewerDecorationSupport.hideAnnotationOverview();
((ISourceViewerExtension) getSourceViewer()).showAnnotationsOverview(false);
}
}
protected boolean isOverviewRulerVisible() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(OVERVIEW_RULER);
}
protected void configureSourceViewerDecorationSupport() {
fSourceViewerDecorationSupport.setCharacterPairMatcher(fBracketMatcher);
Iterator e= fAnnotationPreferences.getAnnotationPreferences().iterator();
while (e.hasNext())
fSourceViewerDecorationSupport.setAnnotationPreference((AnnotationPreference) e.next());
fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(AnnotationType.UNKNOWN, UNKNOWN_INDICATION_COLOR, UNKNOWN_INDICATION, UNKNOWN_INDICATION_IN_OVERVIEW_RULER, 0);
fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(AnnotationType.BOOKMARK, BOOKMARK_INDICATION_COLOR, BOOKMARK_INDICATION, BOOKMARK_INDICATION_IN_OVERVIEW_RULER, 1);
fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(AnnotationType.TASK, TASK_INDICATION_COLOR, TASK_INDICATION, TASK_INDICATION_IN_OVERVIEW_RULER, 2);
fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(AnnotationType.SEARCH, SEARCH_RESULT_INDICATION_COLOR, SEARCH_RESULT_INDICATION, SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER, 3);
fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(AnnotationType.WARNING, WARNING_INDICATION_COLOR, WARNING_INDICATION, WARNING_INDICATION_IN_OVERVIEW_RULER, 4);
fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(AnnotationType.ERROR, ERROR_INDICATION_COLOR, ERROR_INDICATION, ERROR_INDICATION_IN_OVERVIEW_RULER, 5);
fSourceViewerDecorationSupport.setCursorLinePainterPreferenceKeys(CURRENT_LINE, CURRENT_LINE_COLOR);
fSourceViewerDecorationSupport.setMarginPainterPreferenceKeys(PRINT_MARGIN, PRINT_MARGIN_COLOR, PRINT_MARGIN_COLUMN);
fSourceViewerDecorationSupport.setMatchingCharacterPainterPreferenceKeys(MATCHING_BRACKETS, MATCHING_BRACKETS_COLOR);
fSourceViewerDecorationSupport.setSymbolicFontName(getFontPropertyPreferenceKey());
}
/**
* Jumps to the matching bracket.
*/
public void gotoMatchingBracket() {
ISourceViewer sourceViewer= getSourceViewer();
IDocument document= sourceViewer.getDocument();
if (document == null)
return;
IRegion selection= getSignedSelection(sourceViewer);
int selectionLength= Math.abs(selection.getLength());
if (selectionLength > 1) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.invalidSelection")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
// #26314
int sourceCaretOffset= selection.getOffset() + selection.getLength();
if (isSurroundedByBrackets(document, sourceCaretOffset))
sourceCaretOffset -= selection.getLength();
IRegion region= fBracketMatcher.match(document, sourceCaretOffset);
if (region == null) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.noMatchingBracket")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
int offset= region.getOffset();
int length= region.getLength();
if (length < 1)
return;
int anchor= fBracketMatcher.getAnchor();
// http://dev.eclipse.org/bugs/show_bug.cgi?id=34195
int targetOffset= (JavaPairMatcher.RIGHT == anchor) ? offset + 1: offset + length;
boolean visible= false;
if (sourceViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) sourceViewer;
visible= (extension.modelOffset2WidgetOffset(targetOffset) > -1);
} else {
IRegion visibleRegion= sourceViewer.getVisibleRegion();
// http://dev.eclipse.org/bugs/show_bug.cgi?id=34195
visible= (targetOffset >= visibleRegion.getOffset() && targetOffset <= visibleRegion.getOffset() + visibleRegion.getLength());
}
if (!visible) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.bracketOutsideSelectedElement")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
if (selection.getLength() < 0)
targetOffset -= selection.getLength();
sourceViewer.setSelectedRange(targetOffset, selection.getLength());
sourceViewer.revealRange(targetOffset, selection.getLength());
}
/**
* Ses the given message as error message to this editor's status line.
* @param msg message to be set
*/
protected void setStatusLineErrorMessage(String msg) {
IEditorStatusLine statusLine= (IEditorStatusLine) getAdapter(IEditorStatusLine.class);
if (statusLine != null)
statusLine.setMessage(true, msg, null);
}
private static IRegion getSignedSelection(ITextViewer viewer) {
StyledText text= viewer.getTextWidget();
int caretOffset= text.getCaretOffset();
Point selection= text.getSelection();
// caret left
int offset, length;
if (caretOffset == selection.x) {
offset= selection.y;
length= selection.x - selection.y;
// caret right
} else {
offset= selection.x;
length= selection.y - selection.x;
}
return new Region(offset, length);
}
private static boolean isBracket(char character) {
for (int i= 0; i != BRACKETS.length; ++i)
if (character == BRACKETS[i])
return true;
return false;
}
private static boolean isSurroundedByBrackets(IDocument document, int offset) {
if (offset == 0 || offset == document.getLength())
return false;
try {
return
isBracket(document.getChar(offset - 1)) &&
isBracket(document.getChar(offset));
} catch (BadLocationException e) {
return false;
}
}
/**
* Jumps to the next enabled annotation according to the given direction.
* An annotation type is enabled if it is configured to be in the
* Next/Previous tool bar drop down menu and if it is checked.
*/
public void gotoAnnotation(boolean forward) {
ISelectionProvider provider= getSelectionProvider();
ITextSelection s= (ITextSelection) provider.getSelection();
Position annotationPosition= new Position(0, 0);
IJavaAnnotation nextAnnotation= getNextAnnotation(s.getOffset(), forward, annotationPosition);
setStatusLineErrorMessage(null);
if (nextAnnotation != null) {
IMarker marker= null;
if (nextAnnotation instanceof MarkerAnnotation)
marker= ((MarkerAnnotation) nextAnnotation).getMarker();
else {
Iterator e= nextAnnotation.getOverlaidIterator();
if (e != null) {
while (e.hasNext()) {
Object o= e.next();
if (o instanceof MarkerAnnotation) {
marker= ((MarkerAnnotation) o).getMarker();
break;
}
}
}
}
if (marker != null) {
IWorkbenchPage page= getSite().getPage();
IViewPart view= view= page.findView("org.eclipse.ui.views.TaskList"); //$NON-NLS-1$
if (view instanceof TaskList) {
StructuredSelection ss= new StructuredSelection(marker);
((TaskList) view).setSelection(ss, true);
}
}
selectAndReveal(annotationPosition.getOffset(), annotationPosition.getLength());
if (nextAnnotation.isProblem())
setStatusLineErrorMessage(nextAnnotation.getMessage());
}
}
private IJavaAnnotation getNextAnnotation(int offset, boolean forward, Position annotationPosition) {
IJavaAnnotation nextAnnotation= null;
Position nextAnnotationPosition= null;
IDocument document= getDocumentProvider().getDocument(getEditorInput());
int endOfDocument= document.getLength();
int distance= 0;
IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput());
Iterator e= new JavaAnnotationIterator(model, true);
while (e.hasNext()) {
IJavaAnnotation a= (IJavaAnnotation) e.next();
// Map Java AnnotationType to workbench texteditor's annotation type
// XXX: This can be removed once Java plug-in uses workbench texteditor's type
String type= null;
int severity= IMarker.SEVERITY_INFO;
if (a.getAnnotationType() == AnnotationType.BOOKMARK) {
type= IMarker.BOOKMARK;
} else if (a.getAnnotationType() == AnnotationType.SEARCH) {
type= SearchUI.SEARCH_MARKER;
} else if (a.getAnnotationType() == AnnotationType.TASK) {
type= IMarker.TASK;
} else if (a.getAnnotationType() == AnnotationType.WARNING) {
type= IMarker.PROBLEM;
severity= IMarker.SEVERITY_WARNING;
} else if (a.getAnnotationType() == AnnotationType.ERROR) {
type= IMarker.PROBLEM;
severity= IMarker.SEVERITY_ERROR;
}
Preferences workbenchTextEditorPrefStore= Platform.getPlugin("org.eclipse.ui.workbench.texteditor").getPluginPreferences(); //$NON-NLS-1$
Iterator iter= fAnnotationPreferences.getAnnotationPreferences().iterator();
boolean isNavigationTarget= false;
while (iter.hasNext()) {
AnnotationPreference annotationPref= (AnnotationPreference)iter.next();
if (annotationPref.getMarkerType().equals(type) && annotationPref.getSeverity() == severity) {
String key;
if (forward)
key= annotationPref.getIsGoToNextNavigationTargetKey();
else
key= annotationPref.getIsGoToPreviousNavigationTargetKey();
if (key != null)
isNavigationTarget= workbenchTextEditorPrefStore.getBoolean(key);
break;
}
annotationPref= null;
}
if (a.hasOverlay() || !isNavigationTarget)
continue;
Position p= model.getPosition((Annotation) a);
if (!(p.includes(offset) || (p.getLength() == 0 && offset == p.offset))) {
int currentDistance= 0;
if (forward) {
currentDistance= p.getOffset() - offset;
if (currentDistance < 0)
currentDistance= endOfDocument - offset + p.getOffset();
} else {
currentDistance= offset - p.getOffset();
if (currentDistance < 0)
currentDistance= offset + endOfDocument - p.getOffset();
}
if (nextAnnotation == null || currentDistance < distance) {
distance= currentDistance;
nextAnnotation= a;
nextAnnotationPosition= p;
}
}
}
if (nextAnnotationPosition != null) {
annotationPosition.setOffset(nextAnnotationPosition.getOffset());
annotationPosition.setLength(nextAnnotationPosition.getLength());
}
return nextAnnotation;
}
/**
* Computes and returns the source reference that includes the caret and
* serves as provider for the outline page selection and the editor range
* indication.
*
* @return the computed source reference
* @since 3.0
*/
protected ISourceReference computeHighlightRangeSourceReference() {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return null;
StyledText styledText= sourceViewer.getTextWidget();
if (styledText == null)
return null;
int caret= 0;
if (sourceViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3)sourceViewer;
caret= extension.widgetOffset2ModelOffset(styledText.getCaretOffset());
} else {
int offset= sourceViewer.getVisibleRegion().getOffset();
caret= offset + styledText.getCaretOffset();
}
IJavaElement element= getElementAt(caret, false);
if ( !(element instanceof ISourceReference))
return null;
if (element.getElementType() == IJavaElement.IMPORT_DECLARATION) {
IImportDeclaration declaration= (IImportDeclaration) element;
IImportContainer container= (IImportContainer) declaration.getParent();
ISourceRange srcRange= null;
try {
srcRange= container.getSourceRange();
} catch (JavaModelException e) {
}
if (srcRange != null && srcRange.getOffset() == caret)
return container;
}
return (ISourceReference) element;
}
/**
* Returns the most narrow java element including the given offset.
*
* @param offset the offset inside of the requested element
* @param reconcile <code>true</code> if editor input should be reconciled in advance
* @return the most narrow java element
* @since 3.0
*/
protected IJavaElement getElementAt(int offset, boolean reconcile) {
return getElementAt(offset);
}
}
|
40,120 |
Bug 40120 move instance method: cannot move to the same file [refactoring]
|
200307010 there's a limitation in move instance method refactoring that does not allow one to move a method to another class if that another class is in the same file as the source class we should remove this limitation
|
resolved fixed
|
8a852fe
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-13T10:25:24Z | 2003-07-15T14:40:00Z |
org.eclipse.jdt.ui.tests.refactoring/test
| |
40,120 |
Bug 40120 move instance method: cannot move to the same file [refactoring]
|
200307010 there's a limitation in move instance method refactoring that does not allow one to move a method to another class if that another class is in the same file as the source class we should remove this limitation
|
resolved fixed
|
8a852fe
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-13T10:25:24Z | 2003-07-15T14:40:00Z |
cases/org/eclipse/jdt/ui/tests/refactoring/MoveInstanceMethodTests.java
| |
40,120 |
Bug 40120 move instance method: cannot move to the same file [refactoring]
|
200307010 there's a limitation in move instance method refactoring that does not allow one to move a method to another class if that another class is in the same file as the source class we should remove this limitation
|
resolved fixed
|
8a852fe
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-13T10:25:24Z | 2003-07-15T14:40:00Z |
org.eclipse.jdt.ui/core
| |
40,120 |
Bug 40120 move instance method: cannot move to the same file [refactoring]
|
200307010 there's a limitation in move instance method refactoring that does not allow one to move a method to another class if that another class is in the same file as the source class we should remove this limitation
|
resolved fixed
|
8a852fe
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-13T10:25:24Z | 2003-07-15T14:40:00Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/InstanceMethodMover.java
| |
40,337 |
Bug 40337 Bad defaults for insertion point
|
In version 2.x using "Add settter/getter" will insert the methods at the end of the class, and using "Add constructor from superclass" will insert the constructors at the top of the class. In version 3.0 both of this generators allow to specify the insertion point. This makes this commands more flexible but it slows down their use, and it is contrary to what people got used to. Constructors by default should be inserted before the first method, setters/getters should be inserted after the last method. Best would be to allow the default insertion point to be specified in the options. At a minimum the default should be the same as in 2.x
|
resolved fixed
|
f9898dc
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-13T10:43:55Z | 2003-07-17T11:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/dialogs/SourceActionDialog.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.dialogs;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.viewers.CheckboxTreeViewer;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.ui.dialogs.CheckedTreeSelectionDialog;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility.GenStubSettings;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.ActionMessages;
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
/**
* An advanced version of CheckedTreeSelectionDialog with right-side button layout and
* extra buttons and composites.
*/
public class SourceActionDialog extends CheckedTreeSelectionDialog {
private int fInsertPosition;
private IDialogSettings fSettings;
private CompilationUnitEditor fEditor;
private ITreeContentProvider fContentProvider;
private boolean fGenerateComment;
private IType fType;
private int fWidth = 60;
private int fHeight = 18;
private String fCommentString;
private final String SETTINGS_SECTION= "SourceActionDialog"; //$NON-NLS-1$
public final String SETTINGS_INSERTPOSITION= "InsertPosition"; //$NON-NLS-1$
public SourceActionDialog(Shell parent, ILabelProvider labelProvider, ITreeContentProvider contentProvider, CompilationUnitEditor editor, IType type) {
super(parent, labelProvider, contentProvider);
fEditor= editor;
fContentProvider= contentProvider;
fType= type;
fCommentString= ActionMessages.getString("SourceActionDialog.createMethodComment"); //$NON-NLS-1$
// Take the default from the default for generating comments from the code gen prefs
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
GenStubSettings genStubSettings= new GenStubSettings(settings);
fGenerateComment= genStubSettings.createComments;
IDialogSettings dialogSettings= JavaPlugin.getDefault().getDialogSettings();
fSettings= dialogSettings.getSection(SETTINGS_SECTION);
if (fSettings == null) {
fSettings= dialogSettings.addNewSection(SETTINGS_SECTION);
fSettings.put(SETTINGS_INSERTPOSITION, 0); //$NON-NLS-1$
}
fInsertPosition= fSettings.getInt(SETTINGS_INSERTPOSITION);
}
/***
* Returns 0 for the first method, 1 for the last method, > 1 for all else.
*/
public int getInsertPosition() {
return fInsertPosition;
}
/***
* Set insert position valid input is 0 for the first position, 1 for the last position, > 1 for all else.
*/
public void setInsertPosition(int insert) {
if (fInsertPosition != insert) {
fInsertPosition= insert;
fSettings.put(SETTINGS_INSERTPOSITION, insert);
}
}
public void setCommentString(String string) {
fCommentString= string;
}
protected ITreeContentProvider getContentProvider() {
return fContentProvider;
}
public boolean getGenerateComment() {
return fGenerateComment;
}
private void setGenerateComment(boolean comment) {
fGenerateComment= comment;
}
/**
* Sets the size of the tree in unit of characters.
* @param width the width of the tree.
* @param height the height of the tree.
*/
public void setSize(int width, int height) {
fWidth = width;
fHeight = height;
}
protected Composite createSelectionButtons(Composite composite) {
Composite buttonComposite= super.createSelectionButtons(composite);
GridLayout layout = new GridLayout();
buttonComposite.setLayout(layout);
layout.marginHeight= 0;
layout.marginWidth= 0;
layout.numColumns= 1;
return buttonComposite;
}
protected void buttonPressed(int buttonId) {
switch (buttonId) {
case IDialogConstants.OK_ID: {
okPressed();
break;
}
case IDialogConstants.CANCEL_ID: {
cancelPressed();
break;
}
}
}
/**
* Returns a composite containing the label created at the top of the dialog. Returns null if there is the
* message for the label is null.
*/
protected Label createMessageArea(Composite composite) {
if (getMessage() != null) {
Label label = new Label(composite,SWT.NONE);
label.setText(getMessage());
label.setFont(composite.getFont());
return label;
}
return null;
}
/*
* @see Dialog#createDialogArea(Composite)
*/
protected Control createDialogArea(Composite parent) {
initializeDialogUnits(parent);
Composite composite = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout();
GridData gd= null;
layout.marginHeight= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
layout.marginWidth= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
layout.verticalSpacing= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
layout.horizontalSpacing= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
composite.setLayout(layout);
composite.setFont(parent.getFont());
Label messageLabel = createMessageArea(composite);
if (messageLabel != null) {
gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= 2;
messageLabel.setLayoutData(gd);
}
Composite inner= new Composite(composite, SWT.NONE);
GridLayout innerLayout = new GridLayout();
innerLayout.numColumns= 2;
innerLayout.marginHeight= 0;
innerLayout.marginWidth= 0;
inner.setLayout(innerLayout);
inner.setFont(parent.getFont());
CheckboxTreeViewer treeViewer= createTreeViewer(inner);
gd= new GridData(GridData.FILL_BOTH);
gd.widthHint = convertWidthInCharsToPixels(fWidth);
gd.heightHint = convertHeightInCharsToPixels(fHeight);
treeViewer.getControl().setLayoutData(gd);
Composite buttonComposite= createSelectionButtons(inner);
gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL);
buttonComposite.setLayoutData(gd);
gd= new GridData(GridData.FILL_BOTH);
inner.setLayoutData(gd);
Composite entryComposite= createEntryPtCombo(composite);
entryComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
Composite commentComposite= createCommentSelection(composite);
commentComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
gd= new GridData(GridData.FILL_BOTH);
composite.setLayoutData(gd);
return composite;
}
protected Composite createCommentSelection(Composite composite) {
Composite commentComposite = new Composite(composite, SWT.NONE);
GridLayout layout = new GridLayout();
layout.marginHeight= 0;
layout.marginWidth= 0;
commentComposite.setLayout(layout);
commentComposite.setFont(composite.getFont());
Button commentButton= new Button(commentComposite, SWT.CHECK);
commentButton.setText(fCommentString); //$NON-NLS-1$
commentButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
commentButton.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
boolean isSelected= (((Button) e.widget).getSelection());
setGenerateComment(isSelected);
}
public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
});
commentButton.setSelection(getGenerateComment());
GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= 2;
commentButton.setLayoutData(gd);
return commentComposite;
}
protected Composite createEntryPtCombo(Composite composite) {
Composite selectionComposite = new Composite(composite, SWT.NONE);
GridLayout layout = new GridLayout();
layout.marginHeight= 0;
layout.marginWidth= 0;
selectionComposite.setLayout(layout);
addOrderEntryChoices(selectionComposite);
return selectionComposite;
}
private Composite addOrderEntryChoices(Composite buttonComposite) {
Label enterLabel= new Label(buttonComposite, SWT.NONE);
enterLabel.setText(ActionMessages.getString("SourceActionDialog.enterAt_label")); //$NON-NLS-1$
GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
enterLabel.setLayoutData(gd);
final Combo enterCombo= new Combo(buttonComposite, SWT.READ_ONLY);
fillWithPossibleInsertPositions(enterCombo);
gd= new GridData(GridData.FILL_BOTH);
enterCombo.setLayoutData(gd);
enterCombo.addSelectionListener(new SelectionAdapter(){
public void widgetSelected(SelectionEvent e) {
int index= enterCombo.getSelectionIndex();
// Add persistence only if first or last method: http://bugs.eclipse.org/bugs/show_bug.cgi?id=38400
setInsertPosition(index);
}
});
return buttonComposite;
}
private void fillWithPossibleInsertPositions(Combo combo) {
try {
int position= 0;
int presetOffset= 0;
if (fEditor != null) {
presetOffset= ((TextSelection) fEditor.getSelectionProvider().getSelection()).getOffset();
}
else {
List preselected= getInitialElementSelections();
int size= preselected.size();
if ((size > 1) || (size == 0))
presetOffset= 0;
else {
IJavaElement element= (IJavaElement) preselected.get(0);
int type= element.getElementType();
if (type == IJavaElement.FIELD)
presetOffset= ((IField)element).getSourceRange().getOffset();
else if (type == IJavaElement.METHOD)
presetOffset= ((IMethod)element).getSourceRange().getOffset();
}
}
IMethod[] methods= fType.getMethods();
combo.add(ActionMessages.getString("SourceActionDialog.first_method")); //$NON-NLS-1$
combo.add(ActionMessages.getString("SourceActionDialog.last_method")); //$NON-NLS-1$
int bestDiff= Integer.MAX_VALUE;
for (int i= 0; i < methods.length; i++) {
int currDiff= 0;
IMethod curr= methods[i];
combo.add(JavaElementLabels.getElementLabel(methods[i], JavaElementLabels.M_PARAMETER_TYPES));
// calculate method to pre-select
currDiff= presetOffset - curr.getSourceRange().getOffset();
if (currDiff >= 0)
if(currDiff < bestDiff) {
bestDiff= currDiff;
position= i + 2; // first two entries are first/last
}
else
break;
}
// Add persistence only if first or last method: http://bugs.eclipse.org/bugs/show_bug.cgi?id=38400
int index= getInsertPosition();
if (index > 1)
combo.select(position);
else
combo.select(index);
setInsertPosition(combo.getSelectionIndex());
} catch (JavaModelException e) {
}
}
/*
* Determine where in the file to enter the newly created methods.
*/
public IJavaElement getElementPosition() {
int comboBoxIndex= getInsertPosition();
try {
if (comboBoxIndex == 0) // as first method
return asFirstMethod(fType);
else if (comboBoxIndex == 1) // as last method
return null;
else // method position
return atElementPosition(fType, comboBoxIndex);
} catch (JavaModelException e) {
return null;
}
}
private IMethod asFirstMethod(IType type) throws JavaModelException {
if (type != null) {
IMethod[] methods= type.getMethods();
if (methods.length > 0) {
return methods[0];
}
}
return null;
}
/* Returns the element directly following the method to insert after. Index should never
* always be > 2 since 0 means first method, and 1 means last method.
*/
private IJavaElement atElementPosition(IType type, int index) throws JavaModelException {
if (type != null) {
IMethod[] methods= type.getMethods();
IJavaElement[] elements= type.getChildren();
for (int i= 0; i < (elements.length-1); i++) {
if (methods[index-2] == elements[i]) // first two entries are first/last
return elements[i+1];
}
}
return null;
}
}
|
41,464 |
Bug 41464 "extract interface" could change more references
|
Given a class Foo public class Foo { public void foo() { } } and a class Bar which uses Foo public class Bar { private Foo foo; public Foo getFoo() { return foo; } public void setFoo(Foo foo) { this.foo = foo; } public void useFoo() { foo.foo(); } } if you extract an interface IFoo for Foo, containing the foo() method and checking "change references...", only the return type of getFoo() in Bar gets changed, though the type of the whole field could be changed to the interface. This severely limits the usefulness of the refactoring.
|
resolved fixed
|
e1173e9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-13T11:20:35Z | 2003-08-13T10:20:00Z |
org.eclipse.jdt.ui.tests.refactoring/test
| |
41,464 |
Bug 41464 "extract interface" could change more references
|
Given a class Foo public class Foo { public void foo() { } } and a class Bar which uses Foo public class Bar { private Foo foo; public Foo getFoo() { return foo; } public void setFoo(Foo foo) { this.foo = foo; } public void useFoo() { foo.foo(); } } if you extract an interface IFoo for Foo, containing the foo() method and checking "change references...", only the return type of getFoo() in Bar gets changed, though the type of the whole field could be changed to the interface. This severely limits the usefulness of the refactoring.
|
resolved fixed
|
e1173e9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-13T11:20:35Z | 2003-08-13T10:20:00Z |
cases/org/eclipse/jdt/ui/tests/refactoring/ExtractInterfaceTests.java
| |
40,401 |
Bug 40401 CPP: paste package in same source folder: name suggestion
|
M2 testing When copying a package in the same source folder a dialog pops up that asks for a different name: It suggests 'copy1of.junit.runner' which is, in my opinion, not really useful. Better would be junit.runner1 or junit.runner.copy1
|
resolved fixed
|
6fa43a0
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-13T16:20:15Z | 2003-07-17T16:40:00Z |
org.eclipse.jdt.ui/core
| |
40,401 |
Bug 40401 CPP: paste package in same source folder: name suggestion
|
M2 testing When copying a package in the same source folder a dialog pops up that asks for a different name: It suggests 'copy1of.junit.runner' which is, in my opinion, not really useful. Better would be junit.runner1 or junit.runner.copy1
|
resolved fixed
|
6fa43a0
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-13T16:20:15Z | 2003-07-17T16:40:00Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/reorg/ReorgPolicyFactory.java
| |
39,642 |
Bug 39642 TextChangeManager should not setKeepExecutedTextEdits(true) on all changes [refactoring]
|
I20030628 The default should be false since setting it to true doubles the memory consumption. Keeping executed edits should require some client action.
|
resolved fixed
|
a687901
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-13T18:19:37Z | 2003-07-04T14:46:40Z |
org.eclipse.jdt.ui/core
| |
39,642 |
Bug 39642 TextChangeManager should not setKeepExecutedTextEdits(true) on all changes [refactoring]
|
I20030628 The default should be false since setting it to true doubles the memory consumption. Keeping executed edits should require some client action.
|
resolved fixed
|
a687901
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-13T18:19:37Z | 2003-07-04T14:46:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/rename/RenameFieldProcessor.java
| |
39,642 |
Bug 39642 TextChangeManager should not setKeepExecutedTextEdits(true) on all changes [refactoring]
|
I20030628 The default should be false since setting it to true doubles the memory consumption. Keeping executed edits should require some client action.
|
resolved fixed
|
a687901
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-13T18:19:37Z | 2003-07-04T14:46:40Z |
org.eclipse.jdt.ui/core
| |
39,642 |
Bug 39642 TextChangeManager should not setKeepExecutedTextEdits(true) on all changes [refactoring]
|
I20030628 The default should be false since setting it to true doubles the memory consumption. Keeping executed edits should require some client action.
|
resolved fixed
|
a687901
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-13T18:19:37Z | 2003-07-04T14:46:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/rename/RenameMethodProcessor.java
| |
39,642 |
Bug 39642 TextChangeManager should not setKeepExecutedTextEdits(true) on all changes [refactoring]
|
I20030628 The default should be false since setting it to true doubles the memory consumption. Keeping executed edits should require some client action.
|
resolved fixed
|
a687901
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-13T18:19:37Z | 2003-07-04T14:46:40Z |
org.eclipse.jdt.ui/core
| |
39,642 |
Bug 39642 TextChangeManager should not setKeepExecutedTextEdits(true) on all changes [refactoring]
|
I20030628 The default should be false since setting it to true doubles the memory consumption. Keeping executed edits should require some client action.
|
resolved fixed
|
a687901
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-13T18:19:37Z | 2003-07-04T14:46:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ExtractInterfaceRefactoring.java
| |
39,642 |
Bug 39642 TextChangeManager should not setKeepExecutedTextEdits(true) on all changes [refactoring]
|
I20030628 The default should be false since setting it to true doubles the memory consumption. Keeping executed edits should require some client action.
|
resolved fixed
|
a687901
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-13T18:19:37Z | 2003-07-04T14:46:40Z |
org.eclipse.jdt.ui/core
| |
39,642 |
Bug 39642 TextChangeManager should not setKeepExecutedTextEdits(true) on all changes [refactoring]
|
I20030628 The default should be false since setting it to true doubles the memory consumption. Keeping executed edits should require some client action.
|
resolved fixed
|
a687901
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-13T18:19:37Z | 2003-07-04T14:46:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/util/TextChangeManager.java
| |
40,399 |
Bug 40399 Move on type does not accept a move target
|
M2 testing 1. In the package explorer select type AssertTest (not the CU) 2. Refactor->Move 3. Select another type (e.g. ClassLoaderTest) The error message says: Element inside compilation units can not be used as targets for files, folders or comp. units This is a type and should be able to be moved into an enclosing type. Note that it might be good to have the name/signature of the element currently koved in the dialog title: E.g. Move 'org.junit.AssertTest' (or as a description)
|
resolved fixed
|
d76fb54
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-14T13:38:44Z | 2003-07-17T16:40:00Z |
org.eclipse.jdt.ui/core
| |
40,399 |
Bug 40399 Move on type does not accept a move target
|
M2 testing 1. In the package explorer select type AssertTest (not the CU) 2. Refactor->Move 3. Select another type (e.g. ClassLoaderTest) The error message says: Element inside compilation units can not be used as targets for files, folders or comp. units This is a type and should be able to be moved into an enclosing type. Note that it might be good to have the name/signature of the element currently koved in the dialog title: E.g. Move 'org.junit.AssertTest' (or as a description)
|
resolved fixed
|
d76fb54
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-14T13:38:44Z | 2003-07-17T16:40:00Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/reorg/ReorgPolicyFactory.java
| |
31,249 |
Bug 31249 Bad default modifier for Hyperlink style navigation on MacOS X
|
M5 The default modifier for hyperlink style navigation is "Control" which doesn't work well on MacOS X because here the Control modifier is used to simulate a right-click (opening the context menu). The consequence of this is that if control is pressed the users gets the underlined text style when hovering, but he cannot follow the link because a click results in opening the context menu. The default on MacOS should be 'Command'
|
resolved fixed
|
e574c2d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-14T14:26:00Z | 2003-02-07T12:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/PreferenceConstants.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.ui;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.ui.texteditor.AbstractTextEditor;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.ui.text.IJavaColorConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.preferences.NewJavaProjectPreferencePage;
import org.eclipse.jdt.internal.ui.preferences.WorkInProgressPreferencePage;
/**
* Preference constants used in the JDT-UI preference store. Clients should only read the
* JDT-UI preference store using these values. Clients are not allowed to modify the
* preference store programmatically.
*
* @since 2.0
*/
public class PreferenceConstants {
private PreferenceConstants() {
}
/**
* A named preference that controls return type rendering of methods in the UI.
* <p>
* Value is of type <code>Boolean</code>: if <code>true</code> return types
* are rendered
* </p>
*/
public static final String APPEARANCE_METHOD_RETURNTYPE= "org.eclipse.jdt.ui.methodreturntype";//$NON-NLS-1$
/**
* A named preference that controls if override indicators are rendered in the UI.
* <p>
* Value is of type <code>Boolean</code>: if <code>true</code> override
* indicators are rendered
* </p>
*/
public static final String APPEARANCE_OVERRIDE_INDICATOR= "org.eclipse.jdt.ui.overrideindicator";//$NON-NLS-1$
/**
* A named preference that controls if quick assist light bulbs are shown.
* <p>
* Value is of type <code>Boolean</code>: if <code>true</code> light bulbs are shown
* for quick assists.
* </p>
*/
public static final String APPEARANCE_QUICKASSIST_LIGHTBULB="org.eclipse.jdt.quickassist.lightbulb"; //$NON-NLS-1$
/**
* A named preference that defines the pattern used for package name compression.
* <p>
* Value is of type <code>String</code>. For example foe the given package name 'org.eclipse.jdt' pattern
* '.' will compress it to '..jdt', '1~' to 'o~.e~.jdt'.
* </p>
*/
public static final String APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW= "PackagesView.pkgNamePatternForPackagesView";//$NON-NLS-1$
/**
* A named preference that controls if package name compression is turned on or off.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*
* @see #APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW
*/
public static final String APPEARANCE_COMPRESS_PACKAGE_NAMES= "org.eclipse.jdt.ui.compresspackagenames";//$NON-NLS-1$
/**
* A named preference that controls if empty inner packages are folded in
* the hierarchical mode of the package explorer.
* <p>
* Value is of type <code>Boolean</code>: if <code>true</code> empty
* inner packages are folded.
* </p>
* @since 2.1
*/
public static final String APPEARANCE_FOLD_PACKAGES_IN_PACKAGE_EXPLORER= "org.eclipse.jdt.ui.flatPackagesInPackageExplorer";//$NON-NLS-1$
/**
* A named preference that defines how member elements are ordered by the
* Java views using the <code>JavaElementSorter</code>.
* <p>
* Value is of type <code>String</code>: A comma separated list of the
* following entries. Each entry must be in the list, no duplication. List
* order defines the sort order.
* <ul>
* <li><b>T</b>: Types</li>
* <li><b>C</b>: Constructors</li>
* <li><b>I</b>: Initializers</li>
* <li><b>M</b>: Methods</li>
* <li><b>F</b>: Fields</li>
* <li><b>SI</b>: Static Initializers</li>
* <li><b>SM</b>: Static Methods</li>
* <li><b>SF</b>: Static Fields</li>
* </ul>
* </p>
* @since 2.1
*/
public static final String APPEARANCE_MEMBER_SORT_ORDER= "outlinesortoption"; //$NON-NLS-1$
/**
* A named preference that controls if prefix removal during setter/getter generation is turned on or off.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @deprecated Use JavaCore preference store (key JavaCore.
* CODEASSIST_FIELD_PREFIXES and CODEASSIST_STATIC_FIELD_PREFIXES)
*/
public static final String CODEGEN_USE_GETTERSETTER_PREFIX= "org.eclipse.jdt.ui.gettersetter.prefix.enable";//$NON-NLS-1$
/**
* A named preference that holds a list of prefixes to be removed from a local variable to compute setter
* and gettter names.
* <p>
* Value is of type <code>String</code>: comma separated list of prefixed
* </p>
*
* @deprecated Use JavaCore preference store (key JavaCore.
* CODEASSIST_FIELD_PREFIXES and CODEASSIST_STATIC_FIELD_PREFIXES)
*/
public static final String CODEGEN_GETTERSETTER_PREFIX= "org.eclipse.jdt.ui.gettersetter.prefix.list";//$NON-NLS-1$
/**
* A named preference that controls if suffix removal during setter/getter generation is turned on or off.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @deprecated Use JavaCore preference store (key JavaCore.
* CODEASSIST_FIELD_PREFIXES and CODEASSIST_STATIC_FIELD_PREFIXES)
*/
public static final String CODEGEN_USE_GETTERSETTER_SUFFIX= "org.eclipse.jdt.ui.gettersetter.suffix.enable";//$NON-NLS-1$
/**
* A named preference that holds a list of suffixes to be removed from a local variable to compute setter
* and getter names.
* <p>
* Value is of type <code>String</code>: comma separated list of suffixes
* </p>
* @deprecated Use setting from JavaCore preference store (key JavaCore.
* CODEASSIST_FIELD_SUFFIXES and CODEASSIST_STATIC_FIELD_SUFFIXES)
*/
public static final String CODEGEN_GETTERSETTER_SUFFIX= "org.eclipse.jdt.ui.gettersetter.suffix.list"; //$NON-NLS-1$
/**
* A named preference that controls whether the keyword "this" will be added
* automatically to field accesses in autogenerated methods.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 3.0
*/
public static final String CODEGEN_KEYWORD_THIS= "org.eclipse.jdt.ui.keywordthis"; //$NON-NLS-1$
/**
* A named preference that controls whether to use the prefix "is" or the prefix "get" for
* automatically created getters which return a boolean field.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 3.0
*/
public static final String CODEGEN_IS_FOR_GETTERS= "org.eclipse.jdt.ui.gettersetter.use.is"; //$NON-NLS-1$
/**
* A named preference that controls if comment stubs will be added
* automatically to newly created types and methods.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public static final String CODEGEN_ADD_COMMENTS= "org.eclipse.jdt.ui.javadoc"; //$NON-NLS-1$
/**
* A named preference that controls if a comment stubs will be added
* automatocally to newly created types and methods.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @deprecated Use CODEGEN_ADD_COMMENTS instead (Name is more precice).
*/
public static final String CODEGEN__JAVADOC_STUBS= CODEGEN_ADD_COMMENTS;
/**
* A named preference that controls if a non-javadoc comment gets added to methods generated via the
* "Override Methods" operation.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @deprecated New code template story: user can
* specify the overriding method comment.
*/
public static final String CODEGEN__NON_JAVADOC_COMMENTS= "org.eclipse.jdt.ui.seecomments"; //$NON-NLS-1$
/**
* A named preference that controls if a file comment gets added to newly created files.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @deprecated New code template story: user can
* specify the new type code template.
*/
public static final String CODEGEN__FILE_COMMENTS= "org.eclipse.jdt.ui.filecomments"; //$NON-NLS-1$
/**
* A named preference that holds a list of comma separated package names. The list specifies the import order used by
* the "Organize Imports" opeation.
* <p>
* Value is of type <code>String</code>: semicolon separated list of package
* names
* </p>
*/
public static final String ORGIMPORTS_IMPORTORDER= "org.eclipse.jdt.ui.importorder"; //$NON-NLS-1$
/**
* A named preference that specifies the number of imports added before a star-import declaration is used.
* <p>
* Value is of type <code>Int</code>: positive value specifing the number of non star-import is used
* </p>
*/
public static final String ORGIMPORTS_ONDEMANDTHRESHOLD= "org.eclipse.jdt.ui.ondemandthreshold"; //$NON-NLS-1$
/**
* A named preferences that controls if types that start with a lower case letters get added by the
* "Organize Import" operation.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public static final String ORGIMPORTS_IGNORELOWERCASE= "org.eclipse.jdt.ui.ignorelowercasenames"; //$NON-NLS-1$
/**
* A named preference that speficies whether children of a compilation unit are shown in the package explorer.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public static final String SHOW_CU_CHILDREN= "org.eclipse.jdt.ui.packages.cuchildren"; //$NON-NLS-1$
/**
* A named preference that controls whether the package explorer's selection is linked to the active editor.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public static final String LINK_PACKAGES_TO_EDITOR= "org.eclipse.jdt.ui.packages.linktoeditor"; //$NON-NLS-1$
/**
* A named preference that controls whether the hierarchy view's selection is linked to the active editor.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public static final String LINK_TYPEHIERARCHY_TO_EDITOR= "org.eclipse.jdt.ui.packages.linktypehierarchytoeditor"; //$NON-NLS-1$
/**
* A named preference that controls whether the projects view's selection is
* linked to the active editor.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public static final String LINK_BROWSING_PROJECTS_TO_EDITOR= "org.eclipse.jdt.ui.browsing.projectstoeditor"; //$NON-NLS-1$
/**
* A named preference that controls whether the packages view's selection is
* linked to the active editor.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public static final String LINK_BROWSING_PACKAGES_TO_EDITOR= "org.eclipse.jdt.ui.browsing.packagestoeditor"; //$NON-NLS-1$
/**
* A named preference that controls whether the types view's selection is
* linked to the active editor.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public static final String LINK_BROWSING_TYPES_TO_EDITOR= "org.eclipse.jdt.ui.browsing.typestoeditor"; //$NON-NLS-1$
/**
* A named preference that controls whether the members view's selection is
* linked to the active editor.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public static final String LINK_BROWSING_MEMBERS_TO_EDITOR= "org.eclipse.jdt.ui.browsing.memberstoeditor"; //$NON-NLS-1$
/**
* A named preference that controls whether new projects are generated using source and output folder.
* <p>
* Value is of type <code>Boolean</code>. if <code>true</code> new projects are created with a source and
* output folder. If <code>false</code> source and output folder equals to the project.
* </p>
*/
public static final String SRCBIN_FOLDERS_IN_NEWPROJ= "org.eclipse.jdt.ui.wizards.srcBinFoldersInNewProjects"; //$NON-NLS-1$
/**
* A named preference that specifies the source folder name used when creating a new Java project. Value is inactive
* if <code>SRCBIN_FOLDERS_IN_NEWPROJ</code> is set to <code>false</code>.
* <p>
* Value is of type <code>String</code>.
* </p>
*
* @see #SRCBIN_FOLDERS_IN_NEWPROJ
*/
public static final String SRCBIN_SRCNAME= "org.eclipse.jdt.ui.wizards.srcBinFoldersSrcName"; //$NON-NLS-1$
/**
* A named preference that specifies the output folder name used when creating a new Java project. Value is inactive
* if <code>SRCBIN_FOLDERS_IN_NEWPROJ</code> is set to <code>false</code>.
* <p>
* Value is of type <code>String</code>.
* </p>
*
* @see #SRCBIN_FOLDERS_IN_NEWPROJ
*/
public static final String SRCBIN_BINNAME= "org.eclipse.jdt.ui.wizards.srcBinFoldersBinName"; //$NON-NLS-1$
/**
* A named preference that holds a list of possible JRE libraries used by the New Java Project wizard. An library
* consists of a description and an arbitrary number of <code>IClasspathEntry</code>s, that will represent the
* JRE on the new project's classpath.
* <p>
* Value is of type <code>String</code>: a semicolon separated list of encoded JRE libraries.
* <code>NEWPROJECT_JRELIBRARY_INDEX</code> defines the currently used library. Clients
* should use the method <code>encodeJRELibrary</code> to encode a JRE library into a string
* and the methods <code>decodeJRELibraryDescription(String)</code> and <code>
* decodeJRELibraryClasspathEntries(String)</code> to decode the description and the array
* of classpath entries from an encoded string.
* </p>
*
* @see #NEWPROJECT_JRELIBRARY_INDEX
* @see #encodeJRELibrary(String, IClasspathEntry[])
* @see #decodeJRELibraryDescription(String)
* @see #decodeJRELibraryClasspathEntries(String)
*/
public static final String NEWPROJECT_JRELIBRARY_LIST= "org.eclipse.jdt.ui.wizards.jre.list"; //$NON-NLS-1$
/**
* A named preferences that specifies the current active JRE library.
* <p>
* Value is of type <code>Int</code>: an index into the list of possible JRE libraries.
* </p>
*
* @see #NEWPROJECT_JRELIBRARY_LIST
*/
public static final String NEWPROJECT_JRELIBRARY_INDEX= "org.eclipse.jdt.ui.wizards.jre.index"; //$NON-NLS-1$
/**
* A named preference that controls if a new type hierarchy gets opened in a
* new type hierarchy perspective or inside the type hierarchy view part.
* <p>
* Value is of type <code>String</code>: possible values are <code>
* OPEN_TYPE_HIERARCHY_IN_PERSPECTIVE</code> or <code>
* OPEN_TYPE_HIERARCHY_IN_VIEW_PART</code>.
* </p>
*
* @see #OPEN_TYPE_HIERARCHY_IN_PERSPECTIVE
* @see #OPEN_TYPE_HIERARCHY_IN_VIEW_PART
*/
public static final String OPEN_TYPE_HIERARCHY= "org.eclipse.jdt.ui.openTypeHierarchy"; //$NON-NLS-1$
/**
* A string value used by the named preference <code>OPEN_TYPE_HIERARCHY</code>.
*
* @see #OPEN_TYPE_HIERARCHY
*/
public static final String OPEN_TYPE_HIERARCHY_IN_PERSPECTIVE= "perspective"; //$NON-NLS-1$
/**
* A string value used by the named preference <code>OPEN_TYPE_HIERARCHY</code>.
*
* @see #OPEN_TYPE_HIERARCHY
*/
public static final String OPEN_TYPE_HIERARCHY_IN_VIEW_PART= "viewPart"; //$NON-NLS-1$
/**
* A named preference that controls the behaviour when double clicking on a container in the packages view.
* <p>
* Value is of type <code>String</code>: possible values are <code>
* DOUBLE_CLICK_GOES_INTO</code> or <code>
* DOUBLE_CLICK_EXPANDS</code>.
* </p>
*
* @see #DOUBLE_CLICK_EXPANDS
* @see #DOUBLE_CLICK_GOES_INTO
*/
public static final String DOUBLE_CLICK= "packageview.doubleclick"; //$NON-NLS-1$
/**
* A string value used by the named preference <code>DOUBLE_CLICK</code>.
*
* @see #DOUBLE_CLICK
*/
public static final String DOUBLE_CLICK_GOES_INTO= "packageview.gointo"; //$NON-NLS-1$
/**
* A string value used by the named preference <code>DOUBLE_CLICK</code>.
*
* @see #DOUBLE_CLICK
*/
public static final String DOUBLE_CLICK_EXPANDS= "packageview.doubleclick.expands"; //$NON-NLS-1$
/**
* A named preference that controls whether Java views update their presentation while editing or when saving the
* content of an editor.
* <p>
* Value is of type <code>String</code>: possible values are <code>
* UPDATE_ON_SAVE</code> or <code>
* UPDATE_WHILE_EDITING</code>.
* </p>
*
* @see #UPDATE_ON_SAVE
* @see #UPDATE_WHILE_EDITING
*/
public static final String UPDATE_JAVA_VIEWS= "JavaUI.update"; //$NON-NLS-1$
/**
* A string value used by the named preference <code>UPDATE_JAVA_VIEWS</code>
*
* @see #UPDATE_JAVA_VIEWS
*/
public static final String UPDATE_ON_SAVE= "JavaUI.update.onSave"; //$NON-NLS-1$
/**
* A string value used by the named preference <code>UPDATE_JAVA_VIEWS</code>
*
* @see #UPDATE_JAVA_VIEWS
*/
public static final String UPDATE_WHILE_EDITING= "JavaUI.update.whileEditing"; //$NON-NLS-1$
/**
* A named preference that holds the path of the Javadoc command used by the Javadoc creation wizard.
* <p>
* Value is of type <code>String</code>.
* </p>
*/
public static final String JAVADOC_COMMAND= "command"; //$NON-NLS-1$
/**
* A named preference that defines whether hint to make hover sticky should be shown.
*
* @see JavaUI
* @since 3.0
*/
public static String EDITOR_SHOW_TEXT_HOVER_AFFORDANCE= "PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE"; //$NON-NLS-1$
/**
* A named preference that defines the key for the hover modifiers.
*
* @see JavaUI
* @since 2.1
*/
public static final String EDITOR_TEXT_HOVER_MODIFIERS= "hoverModifiers"; //$NON-NLS-1$
/**
* A named preference that defines the key for the hover modifier state masks.
* The value is only used if the value of <code>EDITOR_TEXT_HOVER_MODIFIERS</code>
* cannot be resolved to valid SWT modifier bits.
*
* @see JavaUI
* @see #EDITOR_TEXT_HOVER_MODIFIERS
* @since 2.1.1
*/
public static final String EDITOR_TEXT_HOVER_MODIFIER_MASKS= "hoverModifierMasks"; //$NON-NLS-1$
/**
* The id of the best match hover contributed for extension point
* <code>javaEditorTextHovers</code>.
*
* @since 2.1
*/
public static String ID_BESTMATCH_HOVER= "org.eclipse.jdt.ui.BestMatchHover"; //$NON-NLS-1$
/**
* The id of the source code hover contributed for extension point
* <code>javaEditorTextHovers</code>.
*
* @since 2.1
*/
public static String ID_SOURCE_HOVER= "org.eclipse.jdt.ui.JavaSourceHover"; //$NON-NLS-1$
/**
* The id of the javadoc hover contributed for extension point
* <code>javaEditorTextHovers</code>.
*
* @since 2.1
*/
public static String ID_JAVADOC_HOVER= "org.eclipse.jdt.ui.JavadocHover"; //$NON-NLS-1$
/**
* The id of the problem hover contributed for extension point
* <code>javaEditorTextHovers</code>.
*
* @since 2.1
*/
public static String ID_PROBLEM_HOVER= "org.eclipse.jdt.ui.ProblemHover"; //$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 EDITOR_MATCHING_BRACKETS= "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>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String EDITOR_MATCHING_BRACKETS_COLOR= "matchingBracketsColor"; //$NON-NLS-1$
/**
* A named preference that controls whether the current line highlighting is turned on or off.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_CURRENT_LINE= "currentLine"; //$NON-NLS-1$
/**
* A named preference that holds the color used to highlight the current line.
* <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 EDITOR_CURRENT_LINE_COLOR= "currentLineColor"; //$NON-NLS-1$
/**
* A named preference that controls whether the print margin is turned on or off.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_PRINT_MARGIN= "printMargin"; //$NON-NLS-1$
/**
* A named preference that holds the color used to render the print margin.
* <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 EDITOR_PRINT_MARGIN_COLOR= "printMarginColor"; //$NON-NLS-1$
/**
* Print margin column. Int value.
*/
public final static String EDITOR_PRINT_MARGIN_COLUMN= "printMarginColumn"; //$NON-NLS-1$
/**
* A named preference that holds the color used for the find/replace scope.
* <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 EDITOR_FIND_SCOPE_COLOR= AbstractTextEditor.PREFERENCE_COLOR_FIND_SCOPE;
/**
* A named preference that specifies if the editor uses spaces for tabs.
* <p>
* Value is of type <code>Boolean</code>. If <code>true</code>spaces instead of tabs are used
* in the editor. If <code>false</code> the editor inserts a tab character when pressing the tab
* key.
* </p>
*/
public final static String EDITOR_SPACES_FOR_TABS= "spacesForTabs"; //$NON-NLS-1$
/**
* A named preference that holds the number of spaces used per tab in the editor.
* <p>
* Value is of type <code>Int</code>: positive int value specifying the number of
* spaces per tab.
* </p>
*/
public final static String EDITOR_TAB_WIDTH= "org.eclipse.jdt.ui.editor.tab.width"; //$NON-NLS-1$
/**
* A named preference that controls whether the outline view selection
* should stay in sync with with the element at the current cursor position.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE= "JavaEditor.SyncOutlineOnCursorMove"; //$NON-NLS-1$
/**
* A named preference that controls if correction indicators are shown in the UI.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_CORRECTION_INDICATION= "JavaEditor.ShowTemporaryProblem"; //$NON-NLS-1$
/**
* A named preference that controls whether the editor shows problem indicators in text (squiggly lines).
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*
* @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences}
*/
public final static String EDITOR_PROBLEM_INDICATION= "problemIndication"; //$NON-NLS-1$
/**
* A named preference that holds the color used to render problem indicators.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see #EDITOR_PROBLEM_INDICATION
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
* @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences}
*/
public final static String EDITOR_PROBLEM_INDICATION_COLOR= "problemIndicationColor"; //$NON-NLS-1$
/**
* A named preference that controls whether the editor shows warning indicators in text (squiggly lines).
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
* @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences}
*/
public final static String EDITOR_WARNING_INDICATION= "warningIndication"; //$NON-NLS-1$
/**
* A named preference that holds the color used to render warning indicators.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see #EDITOR_WARNING_INDICATION
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
* @since 2.1
* @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences}
*/
public final static String EDITOR_WARNING_INDICATION_COLOR= "warningIndicationColor"; //$NON-NLS-1$
/**
* A named preference that controls whether the editor shows task indicators in text (squiggly lines).
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
* @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences}
*/
public final static String EDITOR_TASK_INDICATION= "taskIndication"; //$NON-NLS-1$
/**
* A named preference that holds the color used to render task indicators.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see #EDITOR_TASK_INDICATION
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
* @since 2.1
* @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences}
*/
public final static String EDITOR_TASK_INDICATION_COLOR= "taskIndicationColor"; //$NON-NLS-1$
/**
* A named preference that controls whether the editor shows bookmark
* indicators in text (squiggly lines).
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
* @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences}
*/
public final static String EDITOR_BOOKMARK_INDICATION= "bookmarkIndication"; //$NON-NLS-1$
/**
* A named preference that holds the color used to render bookmark indicators.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see #EDITOR_BOOKMARK_INDICATION
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
* @since 2.1
* @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences}
*/
public final static String EDITOR_BOOKMARK_INDICATION_COLOR= "bookmarkIndicationColor"; //$NON-NLS-1$
/**
* A named preference that controls whether the editor shows search
* indicators in text (squiggly lines).
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
* @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences}
*/
public final static String EDITOR_SEARCH_RESULT_INDICATION= "searchResultIndication"; //$NON-NLS-1$
/**
* A named preference that holds the color used to render search indicators.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see #EDITOR_SEARCH_RESULT_INDICATION
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
* @since 2.1
* @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences}
*/
public final static String EDITOR_SEARCH_RESULT_INDICATION_COLOR= "searchResultIndicationColor"; //$NON-NLS-1$
/**
* A named preference that controls whether the editor shows unknown
* indicators in text (squiggly lines).
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
* @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences}
*/
public final static String EDITOR_UNKNOWN_INDICATION= "othersIndication"; //$NON-NLS-1$
/**
* A named preference that holds the color used to render unknown
* indicators.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see #EDITOR_UNKNOWN_INDICATION
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
* @since 2.1
* @deprecated
* @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences}
*/
public final static String EDITOR_UNKNOWN_INDICATION_COLOR= "othersIndicationColor"; //$NON-NLS-1$
/**
* A named preference that controls whether the overview ruler shows error
* indicators.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
* @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences}
*/
public final static String EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER= "errorIndicationInOverviewRuler"; //$NON-NLS-1$
/**
* A named preference that controls whether the overview ruler shows warning
* indicators.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
* @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences}
*/
public final static String EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER= "warningIndicationInOverviewRuler"; //$NON-NLS-1$
/**
* A named preference that controls whether the overview ruler shows task
* indicators.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
* @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences}
*/
public final static String EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER= "taskIndicationInOverviewRuler"; //$NON-NLS-1$
/**
* A named preference that controls whether the overview ruler shows
* bookmark indicators.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
* @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences}
*/
public final static String EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER= "bookmarkIndicationInOverviewRuler"; //$NON-NLS-1$
/**
* A named preference that controls whether the overview ruler shows
* search result indicators.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
* @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences}
*/
public final static String EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER= "searchResultIndicationInOverviewRuler"; //$NON-NLS-1$
/**
* A named preference that controls whether the overview ruler shows
* unknown indicators.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
* @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences}
*/
public final static String EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER= "othersIndicationInOverviewRuler"; //$NON-NLS-1$
/**
* A named preference that controls whether the 'close strings' feature
* is enabled.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_CLOSE_STRINGS= "closeStrings"; //$NON-NLS-1$
/**
* A named preference that controls whether the 'wrap strings' feature is
* enabled.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_WRAP_STRINGS= "wrapStrings"; //$NON-NLS-1$
/**
* A named preference that controls whether the 'close brackets' feature is
* enabled.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_CLOSE_BRACKETS= "closeBrackets"; //$NON-NLS-1$
/**
* A named preference that controls whether the 'close braces' feature is
* enabled.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_CLOSE_BRACES= "closeBraces"; //$NON-NLS-1$
/**
* A named preference that controls whether the 'close java docs' feature is
* enabled.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_CLOSE_JAVADOCS= "closeJavaDocs"; //$NON-NLS-1$
/**
* A named preference that controls whether the 'add JavaDoc tags' feature
* is enabled.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_ADD_JAVADOC_TAGS= "addJavaDocTags"; //$NON-NLS-1$
/**
* A named preference that controls whether the 'format Javadoc tags'
* feature is enabled.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_FORMAT_JAVADOCS= "autoFormatJavaDocs"; //$NON-NLS-1$
/**
* A named preference that controls whether the 'smart paste' feature is
* enabled.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_SMART_PASTE= "smartPaste"; //$NON-NLS-1$
/**
* A named preference that controls whether the 'smart home-end' feature is
* enabled.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_SMART_HOME_END= AbstractTextEditor.PREFERENCE_NAVIGATION_SMART_HOME_END;
/**
* A named preference that controls if temporary problems are evaluated and shown in the UI.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_EVALUTE_TEMPORARY_PROBLEMS= "handleTemporaryProblems"; //$NON-NLS-1$
/**
* A named preference that controls if the overview ruler is shown in the UI.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_OVERVIEW_RULER= "overviewRuler"; //$NON-NLS-1$
/**
* A named preference that controls if the line number ruler is shown in the UI.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_LINE_NUMBER_RULER= "lineNumberRuler"; //$NON-NLS-1$
/**
* A named preference that holds the color used to render line numbers inside the line number ruler.
* <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
* @see #EDITOR_LINE_NUMBER_RULER
*/
public final static String EDITOR_LINE_NUMBER_RULER_COLOR= "lineNumberColor"; //$NON-NLS-1$
/**
* A named preference that holds the color used to render linked positions inside code templates.
* <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 EDITOR_LINKED_POSITION_COLOR= "linkedPositionColor"; //$NON-NLS-1$
/**
* A named preference that holds the color used as the text foreground.
* This value has not effect if the system default color is used.
* <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 EDITOR_FOREGROUND_COLOR= AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND;
/**
* A named preference that describes if the system default foreground color
* is used as the text foreground.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_FOREGROUND_DEFAULT_COLOR= AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND_SYSTEM_DEFAULT;
/**
* A named preference that holds the color used as the text background.
* This value has not effect if the system default color is used.
* <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 EDITOR_BACKGROUND_COLOR= AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND;
/**
* A named preference that describes if the system default background color
* is used as the text background.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_BACKGROUND_DEFAULT_COLOR= AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT;
/**
* Preference key suffix for bold text style preference keys.
*
* @since 2.1
*/
public static final String EDITOR_BOLD_SUFFIX= "_bold"; //$NON-NLS-1$
/**
* A named preference that holds the color used to render multi line comments.
* <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 EDITOR_MULTI_LINE_COMMENT_COLOR= IJavaColorConstants.JAVA_MULTI_LINE_COMMENT;
/**
* The symbolic font name for the Java editor text font
* (value <code>"org.eclipse.jdt.ui.editors.textfont"</code>).
*
* @since 2.1
*/
public final static String EDITOR_TEXT_FONT= "org.eclipse.jdt.ui.editors.textfont"; //$NON-NLS-1$
/**
* A named preference that controls whether multi line comments are rendered in bold.
* <p>
* Value is of type <code>Boolean</code>. If <code>true</code> multi line comments are rendered
* in bold. If <code>false</code> the are rendered using no font style attribute.
* </p>
*/
public final static String EDITOR_MULTI_LINE_COMMENT_BOLD= IJavaColorConstants.JAVA_MULTI_LINE_COMMENT + EDITOR_BOLD_SUFFIX;
/**
* A named preference that holds the color used to render single line comments.
* <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 EDITOR_SINGLE_LINE_COMMENT_COLOR= IJavaColorConstants.JAVA_SINGLE_LINE_COMMENT;
/**
* A named preference that controls whether sinle line comments are rendered in bold.
* <p>
* Value is of type <code>Boolean</code>. If <code>true</code> single line comments are rendered
* in bold. If <code>false</code> the are rendered using no font style attribute.
* </p>
*/
public final static String EDITOR_SINGLE_LINE_COMMENT_BOLD= IJavaColorConstants.JAVA_SINGLE_LINE_COMMENT + EDITOR_BOLD_SUFFIX;
/**
* A named preference that holds the color used to render java keywords.
* <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 EDITOR_JAVA_KEYWORD_COLOR= IJavaColorConstants.JAVA_KEYWORD;
/**
* A named preference that controls whether keywords are rendered in bold.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_JAVA_KEYWORD_BOLD= IJavaColorConstants.JAVA_KEYWORD + EDITOR_BOLD_SUFFIX;
/**
* A named preference that holds the color used to render string constants.
* <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 EDITOR_STRING_COLOR= IJavaColorConstants.JAVA_STRING;
/**
* A named preference that controls whether string constants are rendered in bold.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_STRING_BOLD= IJavaColorConstants.JAVA_STRING + EDITOR_BOLD_SUFFIX;
/**
* A named preference that holds the color used to render method names.
* <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
* @since 3.0
*/
public final static String EDITOR_JAVA_METHOD_NAME_COLOR= IJavaColorConstants.JAVA_METHOD_NAME;
/**
* A named preference that controls whether method names are rendered in bold.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*
* @since 3.0
*/
public final static String EDITOR_JAVA_METHOD_NAME_BOLD= IJavaColorConstants.JAVA_METHOD_NAME + EDITOR_BOLD_SUFFIX;
/**
* A named preference that holds the color used to render operators and brackets.
* <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
* @since 3.0
*/
public final static String EDITOR_JAVA_OPERATOR_COLOR= IJavaColorConstants.JAVA_OPERATOR;
/**
* A named preference that controls whether operators and brackets are rendered in bold.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*
* @since 3.0
*/
public final static String EDITOR_JAVA_OPERATOR_BOLD= IJavaColorConstants.JAVA_OPERATOR + EDITOR_BOLD_SUFFIX;
/**
* A named preference that holds the color used to render java default text.
* <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 EDITOR_JAVA_DEFAULT_COLOR= IJavaColorConstants.JAVA_DEFAULT;
/**
* A named preference that controls whether Java default text is rendered in bold.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_JAVA_DEFAULT_BOLD= IJavaColorConstants.JAVA_DEFAULT + EDITOR_BOLD_SUFFIX;
/**
* A named preference that holds the color used to render task tags.
* <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
* @since 2.1
*/
public final static String EDITOR_TASK_TAG_COLOR= IJavaColorConstants.TASK_TAG;
/**
* A named preference that controls whether task tags are rendered in bold.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String EDITOR_TASK_TAG_BOLD= IJavaColorConstants.TASK_TAG + EDITOR_BOLD_SUFFIX;
/**
* A named preference that holds the color used to render javadoc keywords.
* <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 EDITOR_JAVADOC_KEYWORD_COLOR= IJavaColorConstants.JAVADOC_KEYWORD;
/**
* A named preference that controls whether javadoc keywords are rendered in bold.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_JAVADOC_KEYWORD_BOLD= IJavaColorConstants.JAVADOC_KEYWORD + EDITOR_BOLD_SUFFIX;
/**
* A named preference that holds the color used to render javadoc tags.
* <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 EDITOR_JAVADOC_TAG_COLOR= IJavaColorConstants.JAVADOC_TAG;
/**
* A named preference that controls whether javadoc tags are rendered in bold.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_JAVADOC_TAG_BOLD= IJavaColorConstants.JAVADOC_TAG + EDITOR_BOLD_SUFFIX;
/**
* A named preference that holds the color used to render javadoc links.
* <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 EDITOR_JAVADOC_LINKS_COLOR= IJavaColorConstants.JAVADOC_LINK;
/**
* A named preference that controls whether javadoc links are rendered in bold.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_JAVADOC_LINKS_BOLD= IJavaColorConstants.JAVADOC_LINK + EDITOR_BOLD_SUFFIX;
/**
* A named preference that holds the color used to render javadoc default text.
* <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 EDITOR_JAVADOC_DEFAULT_COLOR= IJavaColorConstants.JAVADOC_DEFAULT;
/**
* A named preference that controls whether javadoc default text is rendered in bold.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String EDITOR_JAVADOC_DEFAULT_BOLD= IJavaColorConstants.JAVADOC_DEFAULT + EDITOR_BOLD_SUFFIX;
/**
* A named preference that holds the color used for 'linked-mode' underline.
* <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
* @since 2.1
*/
public final static String EDITOR_LINK_COLOR= "linkColor"; //$NON-NLS-1$
/**
* A named preference that controls whether hover tooltips in the editor are turned on or off.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public static final String EDITOR_SHOW_HOVER= "org.eclipse.jdt.ui.editor.showHover"; //$NON-NLS-1$
/**
* A named preference that defines the hover shown when no control key is
* pressed.
* <p>Value is of type <code>String</code>: possible values are <code>
* EDITOR_NO_HOVER_CONFIGURED_ID</code> or
* <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a hover
* contributed as <code>javaEditorTextHovers</code>.
* </p>
* @see #EDITOR_NO_HOVER_CONFIGURED_ID
* @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID
* @see JavaUI
* @since 2.1
* @deprecated Will soon be removed - replaced by {@link #EDITOR_TEXT_HOVER_MODIFIERS}
*/
public static final String EDITOR_NONE_HOVER= "noneHover"; //$NON-NLS-1$
/**
* A named preference that defines the hover shown when the
* <code>CTRL</code> modifier key is pressed.
* <p>Value is of type <code>String</code>: possible values are <code>
* EDITOR_NO_HOVER_CONFIGURED_ID</code> or
* <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a
* hover contributed as <code>javaEditorTextHovers</code>.
* </p>
* @see #EDITOR_NO_HOVER_CONFIGURED_ID
* @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID
* @see JavaUI
* @since 2.1
* @deprecated Will soon be removed - replaced by {@link #EDITOR_TEXT_HOVER_MODIFIERS}
*/
public static final String EDITOR_CTRL_HOVER= "ctrlHover"; //$NON-NLS-1$
/**
* A named preference that defines the hover shown when the
* <code>SHIFT</code> modifier key is pressed.
* <p>Value is of type <code>String</code>: possible values are <code>
* EDITOR_NO_HOVER_CONFIGURED_ID</code> or
* <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a
* hover contributed as <code>javaEditorTextHovers</code>.
* </p>
* @see #EDITOR_NO_HOVER_CONFIGURED_ID
* @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID
* @see JavaUI ID_*_HOVER
* @since 2.1
* @deprecated Will soon be removed - replaced by {@link #EDITOR_TEXT_HOVER_MODIFIERS}
*/
public static final String EDITOR_SHIFT_HOVER= "shiftHover"; //$NON-NLS-1$
/**
* A named preference that defines the hover shown when the
* <code>CTRL + ALT</code> modifier keys is pressed.
* <p>Value is of type <code>String</code>: possible values are <code>
* EDITOR_NO_HOVER_CONFIGURED_ID</code> or
* <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a
* hover contributed as <code>javaEditorTextHovers</code>.
* </p>
* @see #EDITOR_NO_HOVER_CONFIGURED_ID
* @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID
* @see JavaUI ID_*_HOVER
* @since 2.1
*/
public static final String EDITOR_CTRL_ALT_HOVER= "ctrlAltHover"; //$NON-NLS-1$
/**
* A named preference that defines the hover shown when the
* <code>CTRL + ALT + SHIFT</code> modifier keys is pressed.
* <p>Value is of type <code>String</code>: possible values are <code>
* EDITOR_NO_HOVER_CONFIGURED_ID</code> or
* <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a
* hover contributed as <code>javaEditorTextHovers</code>.
* </p>
* @see #EDITOR_NO_HOVER_CONFIGURED_ID
* @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID
* @see JavaUI ID_*_HOVER
* @since 2.1
*/
public static final String EDITOR_CTRL_ALT_SHIFT_HOVER= "ctrlAltShiftHover"; //$NON-NLS-1$
/**
* A named preference that defines the hover shown when the
* <code>CTRL + SHIFT</code> modifier keys is pressed.
* <p>Value is of type <code>String</code>: possible values are <code>
* EDITOR_NO_HOVER_CONFIGURED_ID</code> or
* <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a
* hover contributed as <code>javaEditorTextHovers</code>.
* </p>
* @see #EDITOR_NO_HOVER_CONFIGURED_ID
* @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID
* @see JavaUI ID_*_HOVER
* @since 2.1
* @deprecated Will be removed in one of the next builds.
*/
public static final String EDITOR_CTRL_SHIFT_HOVER= "ctrlShiftHover"; //$NON-NLS-1$
/**
* A named preference that defines the hover shown when the
* <code>ALT</code> modifier key is pressed.
* <p>Value is of type <code>String</code>: possible values are <code>
* EDITOR_NO_HOVER_CONFIGURED_ID</code>,
* <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a
* hover contributed as <code>javaEditorTextHovers</code>.
* </p>
* @see #EDITOR_NO_HOVER_CONFIGURED_ID
* @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID
* @see JavaUI ID_*_HOVER
* @deprecated Will soon be removed - replaced by {@link #EDITOR_TEXT_HOVER_MODIFIERS}
* @since 2.1
*/
public static final String EDITOR_ALT_SHIFT_HOVER= "altShiftHover"; //$NON-NLS-1$
/**
* A string value used by the named preferences for hover configuration to
* descibe that no hover should be shown for the given key modifiers.
* @deprecated Will soon be removed - replaced by {@link #EDITOR_TEXT_HOVER_MODIFIERS}
* @since 2.1
*/
public static final String EDITOR_NO_HOVER_CONFIGURED_ID= "noHoverConfiguredId"; //$NON-NLS-1$
/**
* A string value used by the named preferences for hover configuration to
* descibe that the default hover should be shown for the given key
* modifiers. The default hover is described by the
* <code>EDITOR_DEFAULT_HOVER</code> property.
* @since 2.1
* @deprecated Will soon be removed - replaced by {@link #EDITOR_TEXT_HOVER_MODIFIERS}
*/
public static final String EDITOR_DEFAULT_HOVER_CONFIGURED_ID= "defaultHoverConfiguredId"; //$NON-NLS-1$
/**
* A named preference that defines the hover named the 'default hover'.
* Value is of type <code>String</code>: possible values are <code>
* EDITOR_NO_HOVER_CONFIGURED_ID</code> or <code> the hover id of a hover
* contributed as <code>javaEditorTextHovers</code>.
* </p>
* @since 2.1
* @deprecated Will soon be removed - replaced by {@link #EDITOR_TEXT_HOVER_MODIFIERS}
*/
public static final String EDITOR_DEFAULT_HOVER= "defaultHover"; //$NON-NLS-1$
/**
* A named preference that controls if segmented view (show selected element only) is turned on or off.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public static final String EDITOR_SHOW_SEGMENTS= "org.eclipse.jdt.ui.editor.showSegments"; //$NON-NLS-1$
/**
* A named preference that controls if browser like links are turned on or off.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*
* @since 2.1
*/
public static final String EDITOR_BROWSER_LIKE_LINKS= "browserLikeLinks"; //$NON-NLS-1$
/**
* A named preference that controls the key modifier for browser like links.
* <p>
* Value is of type <code>String</code>.
* </p>
*
* @since 2.1
*/
public static final String EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER= "browserLikeLinksKeyModifier"; //$NON-NLS-1$
/**
* A named preference that controls the key modifier mask for browser like links.
* The value is only used if the value of <code>EDITOR_BROWSER_LIKE_LINKS</code>
* cannot be resolved to valid SWT modifier bits.
* <p>
* Value is of type <code>String</code>.
* </p>
*
* @see #EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER
* @since 2.1.1
*/
public static final String EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK= "browserLikeLinksKeyModifierMask"; //$NON-NLS-1$
/**
* A named preference that controls disabling of the overwrite mode.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*
* @since 3.0
*/
public static final String EDITOR_DISABLE_OVERWRITE_MODE= "disable_overwrite_mode"; //$NON-NLS-1$
/**
* A named preference that controls the "smart semicolon" smart typing handler
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*
* @since 3.0
*/
public static final String EDITOR_SMART_SEMICOLON= "smart_semicolon"; //$NON-NLS-1$
/**
* A named preference that controls the "smart opening brace" smart typing handler
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*
* @since 3.0
*/
public static final String EDITOR_SMART_OPENING_BRACE= "smart_opening_brace"; //$NON-NLS-1$
/**
* A named preference that controls if the Java code assist gets auto activated.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String CODEASSIST_AUTOACTIVATION= "content_assist_autoactivation"; //$NON-NLS-1$
/**
* A name preference that holds the auto activation delay time in milli seconds.
* <p>
* Value is of type <code>Int</code>.
* </p>
*/
public final static String CODEASSIST_AUTOACTIVATION_DELAY= "content_assist_autoactivation_delay"; //$NON-NLS-1$
/**
* A named preference that controls if code assist contains only visible proposals.
* <p>
* Value is of type <code>Boolean</code>. if <code>true<code> code assist only contains visible members. If
* <code>false</code> all members are included.
* </p>
*/
public final static String CODEASSIST_SHOW_VISIBLE_PROPOSALS= "content_assist_show_visible_proposals"; //$NON-NLS-1$
/**
* A named preference that controls if the Java code assist inserts a
* proposal automatically if only one proposal is available.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String CODEASSIST_AUTOINSERT= "content_assist_autoinsert"; //$NON-NLS-1$
/**
* A named preference that controls if the Java code assist adds import
* statements.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String CODEASSIST_ADDIMPORT= "content_assist_add_import"; //$NON-NLS-1$
/**
* A named preference that controls if the Java code assist only inserts
* completions. If set to false the proposals can also _replace_ code.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String CODEASSIST_INSERT_COMPLETION= "content_assist_insert_completion"; //$NON-NLS-1$
/**
* A named preference that controls whether code assist proposals filtering is case sensitive or not.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String CODEASSIST_CASE_SENSITIVITY= "content_assist_case_sensitivity"; //$NON-NLS-1$
/**
* A named preference that defines if code assist proposals are sorted in alphabetical order.
* <p>
* Value is of type <code>Boolean</code>. If <code>true</code> that are sorted in alphabetical
* order. If <code>false</code> that are unsorted.
* </p>
*/
public final static String CODEASSIST_ORDER_PROPOSALS= "content_assist_order_proposals"; //$NON-NLS-1$
/**
* A named preference that controls if argument names are filled in when a method is selected from as list
* of code assist proposal.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public final static String CODEASSIST_FILL_ARGUMENT_NAMES= "content_assist_fill_method_arguments"; //$NON-NLS-1$
/**
* A named preference that controls if method arguments are guessed when a
* method is selected from as list of code assist proposal.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
* @since 2.1
*/
public final static String CODEASSIST_GUESS_METHOD_ARGUMENTS= "content_assist_guess_method_arguments"; //$NON-NLS-1$
/**
* A named preference that holds the characters that auto activate code assist in Java code.
* <p>
* Value is of type <code>Sring</code>. All characters that trigger auto code assist in Java code.
* </p>
*/
public final static String CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA= "content_assist_autoactivation_triggers_java"; //$NON-NLS-1$
/**
* A named preference that holds the characters that auto activate code assist in Javadoc.
* <p>
* Value is of type <code>Sring</code>. All characters that trigger auto code assist in Javadoc.
* </p>
*/
public final static String CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC= "content_assist_autoactivation_triggers_javadoc"; //$NON-NLS-1$
/**
* A named preference that holds the background color used in the code assist selection dialog.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String CODEASSIST_PROPOSALS_BACKGROUND= "content_assist_proposals_background"; //$NON-NLS-1$
/**
* A named preference that holds the foreground color used in the code assist selection dialog.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String CODEASSIST_PROPOSALS_FOREGROUND= "content_assist_proposals_foreground"; //$NON-NLS-1$
/**
* A named preference that holds the background color used for parameter hints.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String CODEASSIST_PARAMETERS_BACKGROUND= "content_assist_parameters_background"; //$NON-NLS-1$
/**
* A named preference that holds the foreground color used in the code assist selection dialog.
* <p>
* Value is of type <code>String</code>. A RGB color value encoded as a string
* using class <code>PreferenceConverter</code>
* </p>
*
* @see org.eclipse.jface.resource.StringConverter
* @see org.eclipse.jface.preference.PreferenceConverter
*/
public final static String CODEASSIST_PARAMETERS_FOREGROUND= "content_assist_parameters_foreground"; //$NON-NLS-1$
/**
* A named preference that holds the background color used in the code
* assist selection dialog to mark replaced code.
* <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
* @since 2.1
*/
public final static String CODEASSIST_REPLACEMENT_BACKGROUND= "content_assist_completion_replacement_background"; //$NON-NLS-1$
/**
* A named preference that holds the foreground color used in the code
* assist selection dialog to mark replaced code.
* <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
* @since 2.1
*/
public final static String CODEASSIST_REPLACEMENT_FOREGROUND= "content_assist_completion_replacement_foreground"; //$NON-NLS-1$
/**
* A named preference that controls the behaviour of the refactoring wizard for showing the error page.
* <p>
* Value is of type <code>String</code>. Valid values are:
* <code>REFACTOR_FATAL_SEVERITY</code>,
* <code>REFACTOR_ERROR_SEVERITY</code>,
* <code>REFACTOR_WARNING_SEVERITY</code>
* <code>REFACTOR_INFO_SEVERITY</code>,
* <code>REFACTOR_OK_SEVERITY</code>.
* </p>
*
* @see #REFACTOR_FATAL_SEVERITY
* @see #REFACTOR_ERROR_SEVERITY
* @see #REFACTOR_WARNING_SEVERITY
* @see #REFACTOR_INFO_SEVERITY
* @see #REFACTOR_OK_SEVERITY
*/
public static final String REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD= "Refactoring.ErrorPage.severityThreshold"; //$NON-NLS-1$
/**
* A string value used by the named preference <code>REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD</code>.
*
* @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD
*/
public static final String REFACTOR_FATAL_SEVERITY= "4"; //$NON-NLS-1$
/**
* A string value used by the named preference <code>REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD</code>.
*
* @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD
*/
public static final String REFACTOR_ERROR_SEVERITY= "3"; //$NON-NLS-1$
/**
* A string value used by the named preference <code>REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD</code>.
*
* @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD
*/
public static final String REFACTOR_WARNING_SEVERITY= "2"; //$NON-NLS-1$
/**
* A string value used by the named preference <code>REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD</code>.
*
* @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD
*/
public static final String REFACTOR_INFO_SEVERITY= "1"; //$NON-NLS-1$
/**
* A string value used by the named preference <code>REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD</code>.
*
* @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD
*/
public static final String REFACTOR_OK_SEVERITY= "0"; //$NON-NLS-1$
/**
* A named preference thet controls whether all dirty editors are automatically saved before a refactoring is
* executed.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*/
public static final String REFACTOR_SAVE_ALL_EDITORS= "Refactoring.savealleditors"; //$NON-NLS-1$
/**
* A named preference that controls if the Java Browsing views are linked to the active editor.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*
* @see #LINK_PACKAGES_TO_EDITOR
*/
public static final String BROWSING_LINK_VIEW_TO_EDITOR= "org.eclipse.jdt.ui.browsing.linktoeditor"; //$NON-NLS-1$
/**
* A named preference that controls the layout of the Java Browsing views vertically. Boolean value.
* <p>
* Value is of type <code>Boolean</code>. If <code>true<code> the views are stacked vertical.
* If <code>false</code> they are stacked horizontal.
* </p>
*/
public static final String BROWSING_STACK_VERTICALLY= "org.eclipse.jdt.ui.browsing.stackVertically"; //$NON-NLS-1$
/**
* A named preference that controls if templates are formatted when applied.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*
* @since 2.1
*/
public static final String TEMPLATES_USE_CODEFORMATTER= "org.eclipse.jdt.ui.template.format"; //$NON-NLS-1$
/**
* A named preference that controls the background color for changed lines in the line number bar.
* <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
* @since 3.0
*/
public static final String QUICK_DIFF_CHANGED_COLOR= "lineNumberBar.colors.changed"; //$NON-NLS-1$
/**
* A named preference that controls the background color for added lines in the line number bar.
* <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
* @since 3.0
*/
public static final String QUICK_DIFF_ADDED_COLOR= "lineNumberBar.colors.added"; //$NON-NLS-1$
/**
* A named preference that controls the color for the deleted lines indicator in the line number bar.
* <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
* @since 3.0
*/
public static final String QUICK_DIFF_DELETED_COLOR= "lineNumberBar.colors.deleted"; //$NON-NLS-1$
/**
* A named preference that controls whether quick diff information is shown on a newly opened editor.
* <p>
* Value is of type <code>Boolean</code>.
* </p>
*
* @since 3.0
*/
public static String QUICK_DIFF_ALWAYS_ON= "quickdiff.alwaysOn"; //$NON-NLS-1$
/**
* A named preference that controls the preferred provider to be used for quick diff reference.
* <p>
* Value is of type <code>String</code>.
* </p>
*
* @since 3.0
*/
public static String QUICK_DIFF_DEFAULT_PROVIDER= "quickdiff.preferredProvider"; //$NON-NLS-1$
/**
* Initializes the given preference store with the default values.
*
* @param store the preference store to be initialized
*
* @since 2.1
*/
public static void initializeDefaultValues(IPreferenceStore store) {
store.setDefault(PreferenceConstants.EDITOR_SHOW_SEGMENTS, false);
// JavaBasePreferencePage
store.setDefault(PreferenceConstants.LINK_PACKAGES_TO_EDITOR, false);
store.setDefault(PreferenceConstants.LINK_TYPEHIERARCHY_TO_EDITOR, false);
store.setDefault(PreferenceConstants.OPEN_TYPE_HIERARCHY, PreferenceConstants.OPEN_TYPE_HIERARCHY_IN_VIEW_PART);
store.setDefault(PreferenceConstants.DOUBLE_CLICK, PreferenceConstants.DOUBLE_CLICK_EXPANDS);
store.setDefault(PreferenceConstants.UPDATE_JAVA_VIEWS, PreferenceConstants.UPDATE_WHILE_EDITING);
store.setDefault(PreferenceConstants.LINK_BROWSING_PROJECTS_TO_EDITOR, true);
store.setDefault(PreferenceConstants.LINK_BROWSING_PACKAGES_TO_EDITOR, true);
store.setDefault(PreferenceConstants.LINK_BROWSING_TYPES_TO_EDITOR, true);
store.setDefault(PreferenceConstants.LINK_BROWSING_MEMBERS_TO_EDITOR, true);
// AppearancePreferencePage
store.setDefault(PreferenceConstants.APPEARANCE_COMPRESS_PACKAGE_NAMES, false);
store.setDefault(PreferenceConstants.APPEARANCE_METHOD_RETURNTYPE, false);
store.setDefault(PreferenceConstants.SHOW_CU_CHILDREN, true);
store.setDefault(PreferenceConstants.APPEARANCE_OVERRIDE_INDICATOR, true);
store.setDefault(PreferenceConstants.BROWSING_STACK_VERTICALLY, false);
store.setDefault(PreferenceConstants.APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW, ""); //$NON-NLS-1$
store.setDefault(PreferenceConstants.APPEARANCE_FOLD_PACKAGES_IN_PACKAGE_EXPLORER, true);
// ImportOrganizePreferencePage
store.setDefault(PreferenceConstants.ORGIMPORTS_IMPORTORDER, "java;javax;org;com"); //$NON-NLS-1$
store.setDefault(PreferenceConstants.ORGIMPORTS_ONDEMANDTHRESHOLD, 99);
store.setDefault(PreferenceConstants.ORGIMPORTS_IGNORELOWERCASE, true);
// ClasspathVariablesPreferencePage
// CodeFormatterPreferencePage
// CompilerPreferencePage
// no initialization needed
// RefactoringPreferencePage
store.setDefault(PreferenceConstants.REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD, PreferenceConstants.REFACTOR_ERROR_SEVERITY);
store.setDefault(PreferenceConstants.REFACTOR_SAVE_ALL_EDITORS, false);
// TemplatePreferencePage
store.setDefault(PreferenceConstants.TEMPLATES_USE_CODEFORMATTER, true);
// CodeGenerationPreferencePage
// compatibility code
if (store.getBoolean(PreferenceConstants.CODEGEN_USE_GETTERSETTER_PREFIX)) {
String prefix= store.getString(PreferenceConstants.CODEGEN_GETTERSETTER_PREFIX);
if (prefix.length() > 0) {
JavaCore.getPlugin().getPluginPreferences().setValue(JavaCore.CODEASSIST_FIELD_PREFIXES, prefix);
store.setToDefault(PreferenceConstants.CODEGEN_USE_GETTERSETTER_PREFIX);
store.setToDefault(PreferenceConstants.CODEGEN_GETTERSETTER_PREFIX);
}
}
if (store.getBoolean(PreferenceConstants.CODEGEN_USE_GETTERSETTER_SUFFIX)) {
String suffix= store.getString(PreferenceConstants.CODEGEN_GETTERSETTER_SUFFIX);
if (suffix.length() > 0) {
JavaCore.getPlugin().getPluginPreferences().setValue(JavaCore.CODEASSIST_FIELD_SUFFIXES, suffix);
store.setToDefault(PreferenceConstants.CODEGEN_USE_GETTERSETTER_SUFFIX);
store.setToDefault(PreferenceConstants.CODEGEN_GETTERSETTER_SUFFIX);
}
}
store.setDefault(PreferenceConstants.CODEGEN_KEYWORD_THIS, false);
store.setDefault(PreferenceConstants.CODEGEN_IS_FOR_GETTERS, true);
store.setDefault(PreferenceConstants.CODEGEN_ADD_COMMENTS, true);
// MembersOrderPreferencePage
store.setDefault(PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER, "T,SI,SF,SM,I,F,C,M"); //$NON-NLS-1$
// must add here to guarantee that it is the first in the listener list
store.addPropertyChangeListener(JavaPlugin.getDefault().getMemberOrderPreferenceCache());
// JavaEditorPreferencePage
store.setDefault(PreferenceConstants.EDITOR_MATCHING_BRACKETS, true);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR, new RGB(192, 192,192));
store.setDefault(PreferenceConstants.EDITOR_CURRENT_LINE, true);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_CURRENT_LINE_COLOR, new RGB(225, 235, 224));
store.setDefault(PreferenceConstants.EDITOR_PRINT_MARGIN, false);
store.setDefault(PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN, 80);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR, new RGB(176, 180 , 185));
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_FIND_SCOPE_COLOR, new RGB(185, 176 , 180));
store.setDefault(PreferenceConstants.EDITOR_CORRECTION_INDICATION, true);
store.setDefault(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE, true);
store.setDefault(PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS, true);
store.setDefault(PreferenceConstants.EDITOR_OVERVIEW_RULER, true);
store.setDefault(PreferenceConstants.EDITOR_LINE_NUMBER_RULER, false);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR, new RGB(0, 0, 0));
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_LINKED_POSITION_COLOR, new RGB(0, 200 , 100));
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_LINK_COLOR, new RGB(0, 0, 255));
store.setDefault(PreferenceConstants.EDITOR_FOREGROUND_DEFAULT_COLOR, true);
store.setDefault(PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR, true);
store.setDefault(PreferenceConstants.EDITOR_TAB_WIDTH, 4);
store.setDefault(PreferenceConstants.EDITOR_SPACES_FOR_TABS, false);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_COLOR, new RGB(63, 127, 95));
store.setDefault(PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_BOLD, false);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_COLOR, new RGB(63, 127, 95));
store.setDefault(PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_BOLD, false);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVA_KEYWORD_COLOR, new RGB(127, 0, 85));
store.setDefault(PreferenceConstants.EDITOR_JAVA_KEYWORD_BOLD, true);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_STRING_COLOR, new RGB(42, 0, 255));
store.setDefault(PreferenceConstants.EDITOR_STRING_BOLD, false);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVA_DEFAULT_COLOR, new RGB(0, 0, 0));
store.setDefault(PreferenceConstants.EDITOR_JAVA_DEFAULT_BOLD, false);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVA_METHOD_NAME_COLOR, new RGB(0, 0, 0));
store.setDefault(PreferenceConstants.EDITOR_JAVA_METHOD_NAME_BOLD, false);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVA_OPERATOR_COLOR, new RGB(0, 0, 0));
store.setDefault(PreferenceConstants.EDITOR_JAVA_OPERATOR_BOLD, false);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_TASK_TAG_COLOR, new RGB(127, 159, 191));
store.setDefault(PreferenceConstants.EDITOR_TASK_TAG_BOLD, true);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVADOC_KEYWORD_COLOR, new RGB(127, 159, 191));
store.setDefault(PreferenceConstants.EDITOR_JAVADOC_KEYWORD_BOLD, true);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVADOC_TAG_COLOR, new RGB(127, 127, 159));
store.setDefault(PreferenceConstants.EDITOR_JAVADOC_TAG_BOLD, false);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVADOC_LINKS_COLOR, new RGB(63, 63, 191));
store.setDefault(PreferenceConstants.EDITOR_JAVADOC_LINKS_BOLD, false);
PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVADOC_DEFAULT_COLOR, new RGB(63, 95, 191));
store.setDefault(PreferenceConstants.EDITOR_JAVADOC_DEFAULT_BOLD, false);
store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION, true);
store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION_DELAY, 500);
store.setDefault(PreferenceConstants.CODEASSIST_AUTOINSERT, true);
PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND, new RGB(254, 241, 233));
PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND, new RGB(0, 0, 0));
PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_PARAMETERS_BACKGROUND, new RGB(254, 241, 233));
PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_PARAMETERS_FOREGROUND, new RGB(0, 0, 0));
PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_REPLACEMENT_BACKGROUND, new RGB(255, 255, 0));
PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_REPLACEMENT_FOREGROUND, new RGB(255, 0, 0));
store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA, "."); //$NON-NLS-1$
store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC, "@"); //$NON-NLS-1$
store.setDefault(PreferenceConstants.CODEASSIST_SHOW_VISIBLE_PROPOSALS, true);
store.setDefault(PreferenceConstants.CODEASSIST_CASE_SENSITIVITY, false);
store.setDefault(PreferenceConstants.CODEASSIST_ORDER_PROPOSALS, false);
store.setDefault(PreferenceConstants.CODEASSIST_ADDIMPORT, true);
store.setDefault(PreferenceConstants.CODEASSIST_INSERT_COMPLETION, true);
store.setDefault(PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES, false);
store.setDefault(PreferenceConstants.CODEASSIST_GUESS_METHOD_ARGUMENTS, true);
store.setDefault(PreferenceConstants.EDITOR_SMART_HOME_END, true);
store.setDefault(PreferenceConstants.EDITOR_SMART_PASTE, true);
store.setDefault(PreferenceConstants.EDITOR_CLOSE_STRINGS, true);
store.setDefault(PreferenceConstants.EDITOR_CLOSE_BRACKETS, true);
store.setDefault(PreferenceConstants.EDITOR_CLOSE_BRACES, true);
store.setDefault(PreferenceConstants.EDITOR_CLOSE_JAVADOCS, true);
store.setDefault(PreferenceConstants.EDITOR_WRAP_STRINGS, true);
store.setDefault(PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS, true);
store.setDefault(PreferenceConstants.EDITOR_FORMAT_JAVADOCS, false);
String ctrl= Action.findModifierString(SWT.CTRL);
store.setDefault(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS, "org.eclipse.jdt.ui.BestMatchHover;0;org.eclipse.jdt.ui.JavaSourceHover;" + ctrl); //$NON-NLS-1$
store.setDefault(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIER_MASKS, "org.eclipse.jdt.ui.BestMatchHover;0;org.eclipse.jdt.ui.JavaSourceHover;" + SWT.CTRL); //$NON-NLS-1$
store.setDefault(PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE, true);
store.setDefault(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS, true);
store.setDefault(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER, ctrl);
store.setDefault(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK, SWT.CTRL);
PreferenceConverter.setDefault(store, PreferenceConstants.QUICK_DIFF_CHANGED_COLOR, new RGB(255, 230, 230));
PreferenceConverter.setDefault(store, PreferenceConstants.QUICK_DIFF_ADDED_COLOR, new RGB(230, 230, 255));
PreferenceConverter.setDefault(store, PreferenceConstants.QUICK_DIFF_DELETED_COLOR, new RGB(0, 0, 0));
store.setDefault(PreferenceConstants.QUICK_DIFF_ALWAYS_ON, true);
store.setDefault(PreferenceConstants.QUICK_DIFF_DEFAULT_PROVIDER, "org.eclipse.ui.internal.editors.quickdiff.LastSaveReferenceProvider"); //$NON-NLS-1$
// work in progress
WorkInProgressPreferencePage.initDefaults(store);
// do more complicated stuff
NewJavaProjectPreferencePage.initDefaults(store);
}
/**
* Returns the JDT-UI preference store.
*
* @return the JDT-UI preference store
*/
public static IPreferenceStore getPreferenceStore() {
return JavaPlugin.getDefault().getPreferenceStore();
}
/**
* Encodes a JRE library to be used in the named preference <code>NEWPROJECT_JRELIBRARY_LIST</code>.
*
* @param description a string value describing the JRE library. The description is used
* to indentify the JDR library in the UI
* @param entries an array of classpath entries to be encoded
*
* @return the encoded string.
*/
public static String encodeJRELibrary(String description, IClasspathEntry[] entries) {
return NewJavaProjectPreferencePage.encodeJRELibrary(description, entries);
}
/**
* Decodes an encoded JRE library and returns its description string.
*
* @return the description of an encoded JRE library
*
* @see #encodeJRELibrary(String, IClasspathEntry[])
*/
public static String decodeJRELibraryDescription(String encodedLibrary) {
return NewJavaProjectPreferencePage.decodeJRELibraryDescription(encodedLibrary);
}
/**
* Decodes an encoded JRE library and returns its classpath entries.
*
* @return the array of classpath entries of an encoded JRE library.
*
* @see #encodeJRELibrary(String, IClasspathEntry[])
*/
public static IClasspathEntry[] decodeJRELibraryClasspathEntries(String encodedLibrary) {
return NewJavaProjectPreferencePage.decodeJRELibraryClasspathEntries(encodedLibrary);
}
/**
* Returns the current configuration for the JRE to be used as default in new Java projects.
* This is a convenience method to access the named preference <code>NEWPROJECT_JRELIBRARY_LIST
* </code> with the index defined by <code> NEWPROJECT_JRELIBRARY_INDEX</code>.
*
* @return the current default set of classpath entries
*
* @see #NEWPROJECT_JRELIBRARY_LIST
* @see #NEWPROJECT_JRELIBRARY_INDEX
*/
public static IClasspathEntry[] getDefaultJRELibrary() {
return NewJavaProjectPreferencePage.getDefaultJRELibrary();
}
}
|
41,491 |
Bug 41491 Add constructors from fields issues
|
200300813 a. add visibility buttons like 'Add constructor from super class'
|
resolved fixed
|
a9559b7
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-14T16:12:33Z | 2003-08-13T15:53:20Z |
org.eclipse.jdt.ui/core
| |
41,491 |
Bug 41491 Add constructors from fields issues
|
200300813 a. add visibility buttons like 'Add constructor from super class'
|
resolved fixed
|
a9559b7
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-14T16:12:33Z | 2003-08-13T15:53:20Z |
extension/org/eclipse/jdt/internal/corext/codemanipulation/AddCustomConstructorOperation.java
| |
41,491 |
Bug 41491 Add constructors from fields issues
|
200300813 a. add visibility buttons like 'Add constructor from super class'
|
resolved fixed
|
a9559b7
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-14T16:12:33Z | 2003-08-13T15:53:20Z |
org.eclipse.jdt.ui/core
| |
41,491 |
Bug 41491 Add constructors from fields issues
|
200300813 a. add visibility buttons like 'Add constructor from super class'
|
resolved fixed
|
a9559b7
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-14T16:12:33Z | 2003-08-13T15:53:20Z |
extension/org/eclipse/jdt/internal/corext/codemanipulation/AddUnimplementedConstructorsOperation.java
| |
41,491 |
Bug 41491 Add constructors from fields issues
|
200300813 a. add visibility buttons like 'Add constructor from super class'
|
resolved fixed
|
a9559b7
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-14T16:12:33Z | 2003-08-13T15:53:20Z |
org.eclipse.jdt.ui/core
| |
41,491 |
Bug 41491 Add constructors from fields issues
|
200300813 a. add visibility buttons like 'Add constructor from super class'
|
resolved fixed
|
a9559b7
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-14T16:12:33Z | 2003-08-13T15:53:20Z |
extension/org/eclipse/jdt/internal/corext/codemanipulation/StubUtility.java
| |
41,491 |
Bug 41491 Add constructors from fields issues
|
200300813 a. add visibility buttons like 'Add constructor from super class'
|
resolved fixed
|
a9559b7
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-14T16:12:33Z | 2003-08-13T15:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/AddUnimplementedConstructorsAction.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.ui.actions;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableContext;
import org.eclipse.jface.text.IRewriteTarget;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.CheckboxTreeViewer;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.window.Window;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.dialogs.ISelectionStatusValidator;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.ui.JavaElementSorter;
import org.eclipse.jdt.internal.corext.codemanipulation.AddUnimplementedConstructorsOperation;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.ActionMessages;
import org.eclipse.jdt.internal.ui.actions.ActionUtil;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter;
import org.eclipse.jdt.internal.ui.dialogs.SourceActionDialog;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.refactoring.IVisibilityChangeListener;
import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext;
import org.eclipse.jdt.internal.ui.util.ElementValidator;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
/**
* Creates unimplemented constructors for a type.
* <p>
* Will open the parent compilation unit in a Java editor. Opens a dialog
* with a list of constructors from the super class which can be generated.
* User is able to check or uncheck items before constructors are generated.
* The result is unsaved, so the user can decide if the changes are acceptable.
* <p>
* The action is applicable to structured selections containing elements
* of type <code>IType</code>.
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 2.0
*/
public class AddUnimplementedConstructorsAction extends SelectionDispatchAction {
private CompilationUnitEditor fEditor;
private static final String dialogTitle= ActionMessages.getString("AddUnimplementedConstructorsAction.error.title"); //$NON-NLS-1$
/**
* Creates a new <code>AddUnimplementedConstructorsAction</code>. The action requires
* that the selection provided by the site's selection provider is of type <code>
* org.eclipse.jface.viewers.IStructuredSelection</code>.
*
* @param site the site providing context information for this action
*/
public AddUnimplementedConstructorsAction(IWorkbenchSite site) {
super(site);
setText(ActionMessages.getString("AddUnimplementedConstructorsAction.label")); //$NON-NLS-1$
setDescription(ActionMessages.getString("AddUnimplementedConstructorsAction.description")); //$NON-NLS-1$
setToolTipText(ActionMessages.getString("AddUnimplementedConstructorsAction.tooltip")); //$NON-NLS-1$
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.ADD_UNIMPLEMENTED_CONSTRUCTORS_ACTION);
}
/**
* Note: This constructor is for internal use only. Clients should not call this constructor.
*/
public AddUnimplementedConstructorsAction(CompilationUnitEditor editor) {
this(editor.getEditorSite());
fEditor= editor;
setEnabled(checkEnabledEditor());
}
//---- Structured Viewer -----------------------------------------------------------
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
public void selectionChanged(IStructuredSelection selection) {
try {
setEnabled(canEnable(selection));
} catch (JavaModelException e) {
// http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253
if (JavaModelUtil.filterNotPresentException(e))
JavaPlugin.log(e);
setEnabled(false);
}
}
private boolean canEnable(IStructuredSelection selection) throws JavaModelException {
if ((selection.size() == 1) && (selection.getFirstElement() instanceof IType)) {
IType type= (IType) selection.getFirstElement();
return type.getCompilationUnit() != null && type.isClass(); // look if class: not cheap but done by all source generation actions
}
if ((selection.size() == 1) && (selection.getFirstElement() instanceof ICompilationUnit))
return true;
return false;
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
public void run(IStructuredSelection selection) {
Shell shell= getShell();
try {
IType type= getSelectedType(selection);
if (type == null) {
MessageDialog.openInformation(getShell(), getDialogTitle(), ActionMessages.getString("AddUnimplementedConstructorsAction.not_applicable")); //$NON-NLS-1$
return;
}
// open an editor and work on a working copy
IEditorPart editor= EditorUtility.openInEditor(type);
type= (IType)EditorUtility.getWorkingCopy(type);
if (type == null) {
MessageDialog.openError(shell, getDialogTitle(), ActionMessages.getString("AddUnimplementedConstructorsAction.error.type_removed_in_editor")); //$NON-NLS-1$
return;
}
run(shell, type, editor, false);
} catch (CoreException e) {
ExceptionHandler.handle(e, shell, getDialogTitle(), null);
}
}
//---- Java Editior --------------------------------------------------------------
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void selectionChanged(ITextSelection selection) {
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
public void run(ITextSelection selection) {
Shell shell= getShell();
try {
IType type= SelectionConverter.getTypeAtOffset(fEditor);
if (type != null)
run(shell, type, fEditor, true);
else
MessageDialog.openInformation(shell, getDialogTitle(), ActionMessages.getString("AddUnimplementedConstructorsAction.not_applicable")); //$NON-NLS-1$
} catch (JavaModelException e) {
ExceptionHandler.handle(e, getShell(), getDialogTitle(), null);
} catch (CoreException e) {
ExceptionHandler.handle(e, getShell(), getDialogTitle(), null);
}
}
private boolean checkEnabledEditor() {
return fEditor != null && SelectionConverter.canOperateOn(fEditor);
}
//---- Helpers -------------------------------------------------------------------
private void run(Shell shell, IType type, IEditorPart editor, boolean activatedFromEditor) throws CoreException {
if (!ElementValidator.check(type, getShell(), getDialogTitle(), activatedFromEditor)) {
return;
}
if (!ActionUtil.isProcessable(getShell(), type)) {
return;
}
IMethod[] constructorMethods= StubUtility.getOverridableConstructors(type);
if (constructorMethods.length == 0) {
MessageDialog.openInformation(getShell(), getDialogTitle(), ActionMessages.getString("AddUnimplementedConstructorsAction.error.nothing_found")); //$NON-NLS-1$
return;
}
JavaElementLabelProvider labelProvider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT);
AddUnimplementedConstructorsContentProvider contentProvider = new AddUnimplementedConstructorsContentProvider(constructorMethods);
AddUnimplementedConstructorsDialog dialog= new AddUnimplementedConstructorsDialog(shell, labelProvider, contentProvider, fEditor, type);
dialog.setCommentString(ActionMessages.getString("SourceActionDialog.createConstructorComment")); //$NON-NLS-1$
dialog.setTitle(getDialogTitle());
dialog.setInitialSelections(constructorMethods);
dialog.setContainerMode(true);
dialog.setSorter(new JavaElementSorter());
dialog.setSize(60, 18);
dialog.setInput(new Object());
dialog.setMessage(ActionMessages.getString("AddUnimplementedConstructorsAction.dialog.label")); //$NON-NLS-1$
dialog.setValidator(createValidator(constructorMethods.length));
IMethod[] selected= null;
int dialogResult = dialog.open();
if (dialogResult == Window.OK) {
Object[] checkedElements = dialog.getResult();
if (checkedElements == null)
return;
ArrayList result= new ArrayList(checkedElements.length);
for (int i= 0; i < checkedElements.length; i++) {
Object curr= checkedElements[i];
if (curr instanceof IMethod) {
result.add(curr);
}
}
selected= (IMethod[]) result.toArray(new IMethod[result.size()]);
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
settings.createComments= dialog.getGenerateComment();
IJavaElement elementPosition= dialog.getElementPosition();
AddUnimplementedConstructorsOperation op= new AddUnimplementedConstructorsOperation(type, settings, selected, false, elementPosition);
op.setVisbility(dialog.getVisibilityModifier());
op.setOmitSuper(dialog.isOmitSuper());
IRewriteTarget target= editor != null ? (IRewriteTarget) editor.getAdapter(IRewriteTarget.class) : null;
if (target != null) {
target.beginCompoundChange();
}
try {
IRunnableContext context= JavaPlugin.getActiveWorkbenchWindow();
if (context == null) {
context= new BusyIndicatorRunnableContext();
}
context.run(false, true, new WorkbenchRunnableAdapter(op));
IMethod[] res= op.getCreatedMethods();
if (res == null || res.length == 0) {
MessageDialog.openInformation(shell, getDialogTitle(), ActionMessages.getString("AddUnimplementedConstructorsAction.error.nothing_found")); //$NON-NLS-1$
} else if (editor != null) {
if (res[0].getCompilationUnit().isWorkingCopy()) {
synchronized(res[0].getCompilationUnit()) {
res[0].getCompilationUnit().reconcile();
}
}
EditorUtility.revealInEditor(editor, res[0]);
}
} catch (InvocationTargetException e) {
ExceptionHandler.handle(e, shell, getDialogTitle(), null);
} catch (InterruptedException e) {
// Do nothing. Operation has been canceled by user.
} finally {
if (target != null) {
target.endCompoundChange();
}
}
}
}
private static ISelectionStatusValidator createValidator(int entries) {
AddUnimplementedConstructorsValidator validator= new AddUnimplementedConstructorsValidator(entries);
return validator;
}
private IType getSelectedType(IStructuredSelection selection) throws JavaModelException {
Object[] elements= selection.toArray();
if (elements.length == 1 && (elements[0] instanceof IType)) {
IType type= (IType) elements[0];
if (type.getCompilationUnit() != null && type.isClass()) {
return type;
}
}
else if (elements[0] instanceof ICompilationUnit) {
ICompilationUnit cu= (ICompilationUnit) elements[0];
IType type= cu.findPrimaryType();
if (type != null && !type.isInterface())
return type;
}
return null;
}
private String getDialogTitle() {
return dialogTitle;
}
private static class AddUnimplementedConstructorsContentProvider implements ITreeContentProvider {
private IMethod[] fMethodsList;
private static final Object[] EMPTY= new Object[0];
public AddUnimplementedConstructorsContentProvider(IMethod[] methodList) {
fMethodsList= methodList;
}
/*
* @see ITreeContentProvider#getChildren(Object)
*/
public Object[] getChildren(Object parentElement) {
return EMPTY;
}
/*
* @see ITreeContentProvider#getParent(Object)
*/
public Object getParent(Object element) {
return null;
}
/*
* @see ITreeContentProvider#hasChildren(Object)
*/
public boolean hasChildren(Object element) {
return getChildren(element).length > 0;
}
/*
* @see IStructuredContentProvider#getElements(Object)
*/
public Object[] getElements(Object inputElement) {
return fMethodsList;
}
/*
* @see IContentProvider#dispose()
*/
public void dispose() {
}
/*
* @see IContentProvider#inputChanged(Viewer, Object, Object)
*/
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
}
private static class AddUnimplementedConstructorsValidator implements ISelectionStatusValidator {
private static int fEntries;
AddUnimplementedConstructorsValidator(int entries) {
super();
fEntries= entries;
}
public IStatus validate(Object[] selection) {
int count= countSelectedMethods(selection);
if (count == 0)
return new StatusInfo(IStatus.ERROR, ""); //$NON-NLS-1$
String message= ActionMessages.getFormattedString("AddUnimplementedConstructorsAction.methods_selected", //$NON-NLS-1$
new Object[] { String.valueOf(count), String.valueOf(fEntries)} );
return new StatusInfo(IStatus.INFO, message);
}
private int countSelectedMethods(Object[] selection){
int count= 0;
for (int i = 0; i < selection.length; i++) {
if (selection[i] instanceof IMethod)
count++;
}
return count;
}
}
private static class AddUnimplementedConstructorsDialog extends SourceActionDialog {
private boolean fOmitSuper;
private int fWidth= 60;
private int fHeight= 18;
private IDialogSettings fAddConstructorsSettings;
private final String SETTINGS_SECTION= "AddUnimplementedConstructorsDialog"; //$NON-NLS-1$
private final String OMIT_SUPER="OmitCallToSuper"; //$NON-NLS-1$
public AddUnimplementedConstructorsDialog(Shell parent, ILabelProvider labelProvider, ITreeContentProvider contentProvider, CompilationUnitEditor editor, IType type) {
super(parent, labelProvider, contentProvider, editor, type);
IDialogSettings dialogSettings= JavaPlugin.getDefault().getDialogSettings();
fAddConstructorsSettings= dialogSettings.getSection(SETTINGS_SECTION);
if (fAddConstructorsSettings == null) {
fAddConstructorsSettings= dialogSettings.addNewSection(SETTINGS_SECTION);
fAddConstructorsSettings.put(OMIT_SUPER, false); //$NON-NLS-1$
}
fOmitSuper= fAddConstructorsSettings.getBoolean(OMIT_SUPER);
}
protected Composite createEntryPtCombo(Composite composite) {
Composite entryComposite= super.createEntryPtCombo(composite);
addVisibilityAndModifiersChoices(entryComposite);
return entryComposite;
}
protected Composite createVisibilityControlAndModifiers(Composite parent, final IVisibilityChangeListener visibilityChangeListener, int[] availableVisibilities, int correctVisibility) {
Composite visibilityComposite= createVisibilityControl(parent, visibilityChangeListener, availableVisibilities, correctVisibility);
return visibilityComposite;
}
public boolean isOmitSuper() {
return fOmitSuper;
}
public void setOmitSuper(boolean omitSuper) {
if (fOmitSuper != omitSuper) {
fOmitSuper= omitSuper;
fAddConstructorsSettings.put(OMIT_SUPER, omitSuper);
}
}
protected Composite createOmitSuper(Composite composite) {
Composite omitSuperComposite= new Composite(composite, SWT.NONE);
GridLayout layout= new GridLayout();
layout.marginHeight= 0;
layout.marginWidth= 0;
omitSuperComposite.setLayout(layout);
omitSuperComposite.setFont(composite.getFont());
Button omitSuperButton= new Button(omitSuperComposite, SWT.CHECK);
omitSuperButton.setText(ActionMessages.getString("AddUnimplementedConstructorsDialog.omit.super")); //$NON-NLS-1$
omitSuperButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
omitSuperButton.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
boolean isSelected= (((Button) e.widget).getSelection());
setOmitSuper(isSelected);
}
public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
});
omitSuperButton.setSelection(isOmitSuper());
GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= 2;
omitSuperButton.setLayoutData(gd);
return omitSuperComposite;
}
protected Control createDialogArea(Composite parent) {
initializeDialogUnits(parent);
Composite composite= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
GridData gd= null;
layout.marginHeight= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
layout.marginWidth= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
layout.verticalSpacing= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
layout.horizontalSpacing= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
composite.setLayout(layout);
composite.setFont(parent.getFont());
Label messageLabel = createMessageArea(composite);
if (messageLabel != null) {
gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= 2;
messageLabel.setLayoutData(gd);
}
Composite inner= new Composite(composite, SWT.NONE);
GridLayout innerLayout = new GridLayout();
innerLayout.numColumns= 2;
innerLayout.marginHeight= 0;
innerLayout.marginWidth= 0;
inner.setLayout(innerLayout);
inner.setFont(parent.getFont());
CheckboxTreeViewer treeViewer= createTreeViewer(inner);
gd= new GridData(GridData.FILL_BOTH);
gd.widthHint = convertWidthInCharsToPixels(fWidth);
gd.heightHint = convertHeightInCharsToPixels(fHeight);
treeViewer.getControl().setLayoutData(gd);
Composite buttonComposite= createSelectionButtons(inner);
gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL);
buttonComposite.setLayoutData(gd);
gd= new GridData(GridData.FILL_BOTH);
inner.setLayoutData(gd);
Composite entryComposite= createEntryPtCombo(composite);
entryComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
Composite commentComposite= createCommentSelection(composite);
commentComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
Composite overrideSuperComposite= createOmitSuper(composite);
overrideSuperComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
gd= new GridData(GridData.FILL_BOTH);
composite.setLayoutData(gd);
return composite;
}
}
}
|
41,491 |
Bug 41491 Add constructors from fields issues
|
200300813 a. add visibility buttons like 'Add constructor from super class'
|
resolved fixed
|
a9559b7
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-14T16:12:33Z | 2003-08-13T15:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/GenerateNewConstructorUsingFieldsAction.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.ui.actions;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableContext;
import org.eclipse.jface.text.IRewriteTarget;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.CheckboxTreeViewer;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.window.Window;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.dialogs.ISelectionStatusValidator;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.ToolFactory;
import org.eclipse.jdt.core.compiler.IScanner;
import org.eclipse.jdt.core.compiler.ITerminalSymbols;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.internal.corext.codemanipulation.AddCustomConstructorOperation;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility;
import org.eclipse.jdt.internal.corext.dom.TokenScanner;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.ActionMessages;
import org.eclipse.jdt.internal.ui.actions.ActionUtil;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter;
import org.eclipse.jdt.internal.ui.dialogs.SourceActionDialog;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext;
import org.eclipse.jdt.internal.ui.util.ElementValidator;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
public class GenerateNewConstructorUsingFieldsAction extends SelectionDispatchAction {
private CompilationUnitEditor fEditor;
private static final String fDialogTitle= ActionMessages.getString("GenerateConstructorUsingFieldsAction.error.title"); //$NON-NLS-1$
private static final int UP_INDEX= 0;
private static final int DOWN_INDEX= 1;
/**
* Creates a new <code>GenerateConstructorUsingFieldsAction</code>. The action requires
* that the selection provided by the site's selection provider is of type <code>
* org.eclipse.jface.viewers.IStructuredSelection</code>.
*
* @param site the site providing context information for this action
*/
public GenerateNewConstructorUsingFieldsAction(IWorkbenchSite site) {
super(site);
setText(ActionMessages.getString("GenerateConstructorUsingFieldsAction.label")); //$NON-NLS-1$
setDescription(ActionMessages.getString("GenerateConstructorUsingFieldsAction.description")); //$NON-NLS-1$
setToolTipText(ActionMessages.getString("GenerateConstructorUsingFieldsAction.tooltip")); //$NON-NLS-1$
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.CREATE_NEW_CONSTRUCTOR_ACTION);
}
/**
* Note: This constructor is for internal use only. Clients should not call this constructor.
*/
public GenerateNewConstructorUsingFieldsAction(CompilationUnitEditor editor) {
this(editor.getEditorSite());
fEditor= editor;
setEnabled(checkEnabledEditor());
}
//---- Structured Viewer -----------------------------------------------------------
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
public void selectionChanged(IStructuredSelection selection) {
try {
setEnabled(canEnable(selection));
} catch (JavaModelException e) {
// http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253
if (JavaModelUtil.filterNotPresentException(e))
JavaPlugin.log(e);
setEnabled(false);
}
}
private boolean canEnable(IStructuredSelection selection) throws JavaModelException {
if (getSelectedFields(selection) != null)
return true;
if ((selection.size() == 1) && (selection.getFirstElement() instanceof IType)) {
IType type= (IType) selection.getFirstElement();
return type.getCompilationUnit() != null && type.isClass();
// look if class: not cheap but done by all source generation actions
}
if ((selection.size() == 1) && (selection.getFirstElement() instanceof ICompilationUnit))
return true;
return false;
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
public void run(IStructuredSelection selection) {
try {
IType selectionType= getSelectedType(selection);
if (selectionType == null) {
MessageDialog.openInformation(getShell(), getDialogTitle(), ActionMessages.getString("GenerateConstructorUsingFieldsAction.not_applicable")); //$NON-NLS-1$
return;
}
IField[] selectedFields= getSelectedFields(selection);
// open an editor and work on a working copy
IEditorPart editor= null;
if (selectedFields != null)
editor= EditorUtility.openInEditor(selectedFields[0]);
else
editor= EditorUtility.openInEditor(getSelectedType(selection).getCompilationUnit());
if (canRunOn(selectedFields)) {
run((IType) EditorUtility.getWorkingCopy(selectedFields[0].getDeclaringType()), selectedFields, editor, false);
return;
}
Object firstElement= selection.getFirstElement();
if (firstElement instanceof IType)
run((IType) EditorUtility.getWorkingCopy((IType) firstElement), new IField[0], editor, false);
else if (firstElement instanceof ICompilationUnit) {
IType type= ((ICompilationUnit) firstElement).findPrimaryType();
if (type.isInterface()) {
MessageDialog.openInformation(getShell(), fDialogTitle, ActionMessages.getString("GenerateConstructorUsingFieldsAction.interface_not_applicable")); //$NON-NLS-1$
return;
} else
run((IType) EditorUtility.getWorkingCopy(((ICompilationUnit) firstElement).findPrimaryType()), new IField[0], editor, false);
}
} catch (CoreException e) {
ExceptionHandler.handle(e, getShell(), fDialogTitle, ActionMessages.getString("GenerateConstructorUsingFieldsAction.error.actionfailed")); //$NON-NLS-1$
}
}
private IType getSelectedType(IStructuredSelection selection) throws JavaModelException {
Object[] elements= selection.toArray();
if (elements.length == 1 && (elements[0] instanceof IType)) {
IType type= (IType) elements[0];
if (type.getCompilationUnit() != null && type.isClass()) {
return type;
}
} else if (elements[0] instanceof ICompilationUnit) {
ICompilationUnit cu= (ICompilationUnit) elements[0];
IType type= cu.findPrimaryType();
if (type != null && !type.isInterface())
return type;
} else if (elements[0] instanceof IField) {
return ((IField) elements[0]).getCompilationUnit().findPrimaryType();
}
return null;
}
private static boolean canRunOn(IField[] fields) throws JavaModelException {
return fields != null && fields.length > 0;
}
/*
* Returns fields in the selection or <code>null</code> if the selection is
* empty or not valid.
*/
private IField[] getSelectedFields(IStructuredSelection selection) {
List elements= selection.toList();
int nElements= elements.size();
if (nElements > 0) {
IField[] res= new IField[nElements];
ICompilationUnit cu= null;
for (int i= 0; i < nElements; i++) {
Object curr= elements.get(i);
if (curr instanceof IField) {
IField fld= (IField) curr;
if (i == 0) {
// remember the cu of the first element
cu= fld.getCompilationUnit();
if (cu == null) {
return null;
}
} else if (!cu.equals(fld.getCompilationUnit())) {
// all fields must be in the same CU
return null;
}
try {
if (fld.getDeclaringType().isInterface()) {
// no constructors for interfaces
return null;
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
return null;
}
res[i]= fld;
} else {
return null;
}
}
return res;
}
return null;
}
//---- Java Editior --------------------------------------------------------------
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
public void selectionChanged(ITextSelection selection) {
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
public void run(ITextSelection selection) {
try {
IJavaElement[] elements= SelectionConverter.codeResolve(fEditor);
if (elements.length == 1 && (elements[0] instanceof IField)) {
IField field= (IField) elements[0];
run(field.getDeclaringType(), new IField[] { field }, fEditor, false);
return;
}
IJavaElement element= SelectionConverter.getElementAtOffset(fEditor);
if (element != null) {
IType type= (IType) element.getAncestor(IJavaElement.TYPE);
if (type != null) {
if (type.getFields().length > 0) {
run(type, new IField[0], fEditor, true);
return;
}
}
}
MessageDialog.openInformation(getShell(), fDialogTitle, ActionMessages.getString("GenerateConstructorUsingFieldsAction.not_applicable")); //$NON-NLS-1$
} catch (CoreException e) {
ExceptionHandler.handle(e, getShell(), getDialogTitle(), null);
}
}
private boolean checkEnabledEditor() {
return fEditor != null && SelectionConverter.canOperateOn(fEditor);
}
//---- Helpers -------------------------------------------------------------------
private void run(IType type, IField[] preselected, IEditorPart editor, boolean activatedFromEditor) throws CoreException {
if (!ElementValidator.check(type, getShell(), getDialogTitle(), activatedFromEditor)) {
return;
}
if (!ActionUtil.isProcessable(getShell(), type)) {
return;
}
IField[] constructorFields= type.getFields();
ArrayList constructorFieldsList= new ArrayList();
for (int i= 0; i < constructorFields.length; i++) {
boolean isStatic= Flags.isStatic(constructorFields[i].getFlags());
boolean isFinal= Flags.isFinal(constructorFields[i].getFlags());
if (!isStatic) {
if (isFinal) {
try {
// Do not add final fields which have been set in the <clinit>
IScanner scanner= ToolFactory.createScanner(true, false, false, false);
scanner.setSource(constructorFields[i].getSource().toCharArray());
TokenScanner tokenScanner= new TokenScanner(scanner);
tokenScanner.getTokenStartOffset(ITerminalSymbols.TokenNameEQUAL, 0);
} catch (JavaModelException e) {
} catch (CoreException e) {
constructorFieldsList.add(constructorFields[i]);
}
} else
constructorFieldsList.add(constructorFields[i]);
}
}
if (constructorFieldsList.isEmpty()) {
MessageDialog.openInformation(getShell(), fDialogTitle, ActionMessages.getString("GenerateConstructorUsingFieldsAction.typeContainsNoFields.message")); //$NON-NLS-1$
return;
}
JavaElementLabelProvider labelProvider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT);
GenerateConstructorUsingFieldsContentProvider contentProvider= new GenerateConstructorUsingFieldsContentProvider(constructorFieldsList);
GenerateConstructorUsingFieldsSelectionDialog dialog= new GenerateConstructorUsingFieldsSelectionDialog(getShell(), labelProvider, contentProvider, fEditor, type);
dialog.setCommentString(ActionMessages.getString("SourceActionDialog.createConstructorComment")); //$NON-NLS-1$
dialog.setTitle(getDialogTitle());
dialog.setInitialSelections(preselected);
dialog.setContainerMode(true);
dialog.setSize(60, 18);
dialog.setInput(new Object());
dialog.setMessage(ActionMessages.getString("GenerateConstructorUsingFieldsAction.dialog.label")); //$NON-NLS-1$
dialog.setValidator(createValidator(constructorFieldsList.size(), dialog, type));
if (dialog.getSuperConstructors().length == 0) {
MessageDialog.openInformation(getShell(), getDialogTitle(), ActionMessages.getString("GenerateConstructorUsingFieldsAction.error.nothing_found")); //$NON-NLS-1$
return;
}
IField[] selected= null;
int dialogResult= dialog.open();
if (dialogResult == Window.OK) {
Object[] checkedElements= dialog.getResult();
if (checkedElements == null)
return;
ArrayList result= new ArrayList(checkedElements.length);
for (int i= 0; i < checkedElements.length; i++) {
Object curr= checkedElements[i];
if (curr instanceof IField) {
result.add(curr);
}
}
selected= (IField[]) result.toArray(new IField[result.size()]);
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
settings.createComments= dialog.getGenerateComment();
IJavaElement elementPosition= dialog.getElementPosition();
int superIndex= dialog.getSuperIndex();
AddCustomConstructorOperation op= new AddCustomConstructorOperation(type, settings, selected, false, elementPosition, dialog.getSuperConstructors()[superIndex]);
// Ignore the omit super() checkbox if the default constructor is not chosen
if (dialog.getSuperConstructors()[dialog.getSuperIndex()].getParameterNames().length == 0)
op.setOmitSuper(dialog.isOmitSuper());
IRewriteTarget target= editor != null ? (IRewriteTarget) editor.getAdapter(IRewriteTarget.class) : null;
if (target != null) {
target.beginCompoundChange();
}
try {
IRunnableContext context= JavaPlugin.getActiveWorkbenchWindow();
if (context == null) {
context= new BusyIndicatorRunnableContext();
}
context.run(false, true, new WorkbenchRunnableAdapter(op));
IMethod res= op.getCreatedConstructor();
if (res.getCompilationUnit().isWorkingCopy()) {
synchronized (res.getCompilationUnit()) {
res.getCompilationUnit().reconcile();
}
}
EditorUtility.revealInEditor(editor, res);
} catch (InvocationTargetException e) {
ExceptionHandler.handle(e, getShell(), getDialogTitle(), null);
} catch (InterruptedException e) {
// Do nothing. Operation has been canceled by user.
} finally {
if (target != null) {
target.endCompoundChange();
}
}
}
}
private static ISelectionStatusValidator createValidator(int entries, GenerateConstructorUsingFieldsSelectionDialog dialog, IType type) {
GenerateConstructorUsingFieldsValidator validator= new GenerateConstructorUsingFieldsValidator(entries, dialog, type);
return validator;
}
private String getDialogTitle() {
return fDialogTitle;
}
private static class GenerateConstructorUsingFieldsValidator implements ISelectionStatusValidator {
private static int fEntries;
private IType fType;
private GenerateConstructorUsingFieldsSelectionDialog fDialog;
List fExistingSigs;
GenerateConstructorUsingFieldsValidator(int entries) {
super();
fEntries= entries;
fType= null;
}
GenerateConstructorUsingFieldsValidator(int entries, GenerateConstructorUsingFieldsSelectionDialog dialog, IType type) {
super();
fEntries= entries;
fDialog= dialog;
fType= type;
// Create the potential signature and compare it to the existing ones
fExistingSigs= getExistingConstructorSignatures();
}
public IStatus validate(Object[] selection) {
StringBuffer buffer= new StringBuffer();
buffer.append("("); //$NON-NLS-1$
// first form the part of the signature corresponding to the super constructor combo choice
IMethod chosenSuper= fDialog.getSuperConstructorChoice();
try {
String superParamTypes[]= chosenSuper.getParameterTypes();
for (int i= 0; i < superParamTypes.length; i++) {
buffer.append(superParamTypes[i]);
}
// second form the part of the signature corresponding to the fields selected
for (int i= 0; i < selection.length; i++) {
if (selection[i] instanceof IField) {
buffer.append(((IField) selection[i]).getTypeSignature());
}
}
} catch (JavaModelException e) {
}
buffer.append(")V"); //$NON-NLS-1$
if (fExistingSigs.contains(buffer.toString())) {
return new StatusInfo(IStatus.WARNING, ActionMessages.getString("GenerateConstructorUsingFieldsAction.error.duplicate_constructor")); //$NON-NLS-1$
}
int fieldCount= countSelectedFields(selection);
String message= ActionMessages.getFormattedString("GenerateConstructorUsingFieldsAction.fields_selected", //$NON-NLS-1$
new Object[] { String.valueOf(fieldCount), String.valueOf(fEntries)});
return new StatusInfo(IStatus.INFO, message);
}
private int countSelectedFields(Object[] selection) {
int count= 0;
for (int i= 0; i < selection.length; i++) {
if (selection[i] instanceof IField)
count++;
}
return count;
}
private List getExistingConstructorSignatures() {
List constructorMethods= new ArrayList();
try {
IMethod[] methods= fType.getMethods();
for (int i= 0; i < methods.length; i++) {
IMethod curr= methods[i];
if (curr.isConstructor()) {
constructorMethods.add(curr.getSignature());
}
}
} catch (JavaModelException e) {
}
return constructorMethods;
}
}
private static class GenerateConstructorUsingFieldsSelectionDialog extends SourceActionDialog {
private GenerateConstructorUsingFieldsContentProvider fContentProvider;
private IType fType;
private int fSuperIndex;
private int fWidth= 60;
private int fHeight= 18;
protected Button[] fButtonControls;
private boolean[] fButtonsEnabled;
private boolean fOmitSuper;
private IMethod[] fSuperConstructors;
private IDialogSettings fGenConstructorSettings;
protected CheckboxTreeViewer fTreeViewer;
private GenerateConstructorUsingFieldsTreeViewerAdapter fTreeViewerAdapter;
private static final int UP_BUTTON= IDialogConstants.CLIENT_ID + 1;
private static final int DOWN_BUTTON= IDialogConstants.CLIENT_ID + 2;
private final String SETTINGS_SECTION= "GenerateConstructorUsingFieldsSelectionDialog"; //$NON-NLS-1$
private final String OMIT_SUPER="OmitCallToSuper"; //$NON-NLS-1$
public GenerateConstructorUsingFieldsSelectionDialog(Shell parent, ILabelProvider labelProvider, GenerateConstructorUsingFieldsContentProvider contentProvider, CompilationUnitEditor editor, IType type) {
super(parent, labelProvider, contentProvider, editor, type);
fContentProvider= contentProvider;
fType= type;
fTreeViewerAdapter= new GenerateConstructorUsingFieldsTreeViewerAdapter();
try {
fSuperConstructors= StubUtility.getOverridableConstructors(fType);
} catch (CoreException e) {
ExceptionHandler.handle(e, getShell(), fDialogTitle, ActionMessages.getString("GenerateConstructorUsingFieldsSelectionDialog.error.create.failed")); //$NON-NLS-1$
}
IDialogSettings dialogSettings= JavaPlugin.getDefault().getDialogSettings();
fGenConstructorSettings= dialogSettings.getSection(SETTINGS_SECTION);
if (fGenConstructorSettings == null) {
fGenConstructorSettings= dialogSettings.addNewSection(SETTINGS_SECTION);
fGenConstructorSettings.put(OMIT_SUPER, false); //$NON-NLS-1$
}
fOmitSuper= fGenConstructorSettings.getBoolean(OMIT_SUPER);
}
protected Control createDialogArea(Composite parent) {
initializeDialogUnits(parent);
Composite composite= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
GridData gd= null;
layout.marginHeight= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
layout.marginWidth= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_MARGIN);
layout.verticalSpacing= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_SPACING);
layout.horizontalSpacing= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
composite.setLayout(layout);
composite.setFont(parent.getFont());
Composite classConstructorComposite= addSuperClassConstructorChoices(composite);
gd= new GridData(GridData.FILL_BOTH);
classConstructorComposite.setLayoutData(gd);
Composite inner= new Composite(composite, SWT.NONE);
GridLayout innerLayout= new GridLayout();
innerLayout.numColumns= 2;
innerLayout.marginHeight= 0;
innerLayout.marginWidth= 0;
inner.setLayout(innerLayout);
inner.setFont(parent.getFont());
Label messageLabel= createMessageArea(inner);
if (messageLabel != null) {
gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= 2;
messageLabel.setLayoutData(gd);
}
fTreeViewer= createTreeViewer(inner);
gd= new GridData(GridData.FILL_BOTH);
gd.widthHint= convertWidthInCharsToPixels(fWidth);
gd.heightHint= convertHeightInCharsToPixels(fHeight);
fTreeViewer.getControl().setLayoutData(gd);
fTreeViewer.setContentProvider(fContentProvider);
fTreeViewer.addSelectionChangedListener(fTreeViewerAdapter);
Composite buttonComposite= createSelectionButtons(inner);
gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL);
buttonComposite.setLayoutData(gd);
gd= new GridData(GridData.FILL_BOTH);
inner.setLayoutData(gd);
Composite entryComposite= createEntryPtCombo(composite);
entryComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
Composite commentComposite= createCommentSelection(composite);
commentComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
Composite overrideSuperComposite= createOmitSuper(composite);
overrideSuperComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
gd= new GridData(GridData.FILL_BOTH);
composite.setLayoutData(gd);
return composite;
}
protected Composite createOmitSuper(Composite composite) {
Composite omitSuperComposite= new Composite(composite, SWT.NONE);
GridLayout layout= new GridLayout();
layout.marginHeight= 0;
layout.marginWidth= 0;
omitSuperComposite.setLayout(layout);
omitSuperComposite.setFont(composite.getFont());
Button omitSuperButton= new Button(omitSuperComposite, SWT.CHECK);
omitSuperButton.setText(ActionMessages.getString("GenerateConstructorUsingFieldsSelectionDialog.omit.super")); //$NON-NLS-1$
omitSuperButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
omitSuperButton.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
boolean isSelected= (((Button) e.widget).getSelection());
setOmitSuper(isSelected);
}
public void widgetDefaultSelected(SelectionEvent e) {
widgetSelected(e);
}
});
omitSuperButton.setSelection(isOmitSuper());
GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= 2;
omitSuperButton.setLayoutData(gd);
return omitSuperComposite;
}
protected Composite createSelectionButtons(Composite composite) {
Composite buttonComposite= super.createSelectionButtons(composite);
GridLayout layout= new GridLayout();
buttonComposite.setLayout(layout);
createUpDownButtons(buttonComposite);
layout.marginHeight= 0;
layout.marginWidth= 0;
layout.numColumns= 1;
return buttonComposite;
}
protected void createUpDownButtons(Composite buttonComposite) {
int numButtons= 2; // up, down
fButtonControls= new Button[numButtons];
fButtonsEnabled= new boolean[numButtons];
fButtonControls[UP_INDEX]= createButton(buttonComposite, UP_BUTTON, ActionMessages.getString("GenerateConstructorUsingFieldsSelectionDialog.up_button"), false); //$NON-NLS-1$
fButtonControls[DOWN_INDEX]= createButton(buttonComposite, DOWN_BUTTON, ActionMessages.getString("GenerateConstructorUsingFieldsSelectionDialog.down_button"), false); //$NON-NLS-1$
boolean defaultState= false;
fButtonControls[UP_INDEX].setEnabled(defaultState);
fButtonControls[DOWN_INDEX].setEnabled(defaultState);
fButtonsEnabled[UP_INDEX]= defaultState;
fButtonsEnabled[DOWN_INDEX]= defaultState;
}
protected void buttonPressed(int buttonId) {
super.buttonPressed(buttonId);
switch (buttonId) {
case UP_BUTTON :
{
fContentProvider.up(getElementList(), getTreeViewer());
updateOKStatus();
break;
}
case DOWN_BUTTON :
{
fContentProvider.down(getElementList(), getTreeViewer());
updateOKStatus();
break;
}
}
}
private List getElementList() {
IStructuredSelection selection= (IStructuredSelection) getTreeViewer().getSelection();
List elements= selection.toList();
ArrayList elementList= new ArrayList();
for (int i= 0; i < elements.size(); i++) {
elementList.add(elements.get(i));
}
return elementList;
}
protected Composite createEntryPtCombo(Composite composite) {
Composite entryComposite= super.createEntryPtCombo(composite);
return entryComposite;
}
private Composite addSuperClassConstructorChoices(Composite composite) {
Label label= new Label(composite, SWT.NONE);
label.setText(ActionMessages.getString("GenerateConstructorUsingFieldsSelectionDialog.sort_constructor_choices.label")); //$NON-NLS-1$
GridData gd= new GridData(GridData.FILL_BOTH);
label.setLayoutData(gd);
final Combo combo= new Combo(composite, SWT.READ_ONLY);
for (int i= 0; i < fSuperConstructors.length; i++) {
combo.add(JavaElementLabels.getElementLabel(fSuperConstructors[i], JavaElementLabels.M_PARAMETER_TYPES));
}
// TODO: Can we be a little more intelligent about guessing the super() ?
combo.setText(combo.getItem(0));
combo.setLayoutData(new GridData(GridData.FILL_BOTH));
combo.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
fSuperIndex= combo.getSelectionIndex();
updateOKStatus();
}
});
return composite;
}
public int getSuperIndex() {
return fSuperIndex;
}
public CheckboxTreeViewer getTreeViewer() {
return fTreeViewer;
}
public IMethod getSuperConstructorChoice() {
return getSuperConstructors()[getSuperIndex()];
}
private class GenerateConstructorUsingFieldsTreeViewerAdapter implements ISelectionChangedListener, IDoubleClickListener {
public void selectionChanged(SelectionChangedEvent event) {
IStructuredSelection selection= (IStructuredSelection) fTreeViewer.getSelection();
List selectedList= selection.toList();
GenerateConstructorUsingFieldsContentProvider cp= (GenerateConstructorUsingFieldsContentProvider) getContentProvider();
fButtonControls[UP_INDEX].setEnabled(cp.canMoveUp(selectedList));
fButtonControls[DOWN_INDEX].setEnabled(cp.canMoveDown(selectedList));
}
public void doubleClick(DoubleClickEvent event) {
// Do nothing
}
}
public IMethod[] getSuperConstructors() {
return fSuperConstructors;
}
public void setOmitSuper(boolean omitSuper) {
if (fOmitSuper != omitSuper) {
fOmitSuper= omitSuper;
fGenConstructorSettings.put(OMIT_SUPER, omitSuper);
}
}
public boolean isOmitSuper() {
return fOmitSuper;
}
}
private static class GenerateConstructorUsingFieldsContentProvider implements ITreeContentProvider {
private List fFieldsList;
private static final Object[] EMPTY= new Object[0];
public GenerateConstructorUsingFieldsContentProvider(List fieldList) {
fFieldsList= fieldList;
}
/*
* @see ITreeContentProvider#getChildren(Object)
*/
public Object[] getChildren(Object parentElement) {
return EMPTY;
}
/*
* @see ITreeContentProvider#getParent(Object)
*/
public Object getParent(Object element) {
return null;
}
/*
* @see ITreeContentProvider#hasChildren(Object)
*/
public boolean hasChildren(Object element) {
return getChildren(element).length > 0;
}
/*
* @see IStructuredContentProvider#getElements(Object)
*/
public Object[] getElements(Object inputElement) {
return fFieldsList.toArray();
}
/*
* @see IContentProvider#dispose()
*/
public void dispose() {
}
/*
* @see IContentProvider#inputChanged(Viewer, Object, Object)
*/
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
private List moveUp(List elements, List move) {
int nElements= elements.size();
List res= new ArrayList(nElements);
Object floating= null;
for (int i= 0; i < nElements; i++) {
Object curr= elements.get(i);
if (move.contains(curr)) {
res.add(curr);
} else {
if (floating != null) {
res.add(floating);
}
floating= curr;
}
}
if (floating != null) {
res.add(floating);
}
return res;
}
private List reverse(List p) {
List reverse= new ArrayList(p.size());
for (int i= p.size() - 1; i >= 0; i--) {
reverse.add(p.get(i));
}
return reverse;
}
public void setElements(List elements, CheckboxTreeViewer tree) {
fFieldsList= new ArrayList(elements);
if (tree != null)
tree.refresh();
}
public void up(List checkedElements, CheckboxTreeViewer tree) {
if (checkedElements.size() > 0) {
setElements(moveUp(fFieldsList, checkedElements), tree);
tree.reveal(checkedElements.get(0));
}
tree.setSelection(new StructuredSelection(checkedElements));
}
public void down(List checkedElements, CheckboxTreeViewer tree) {
if (checkedElements.size() > 0) {
setElements(reverse(moveUp(reverse(fFieldsList), checkedElements)), tree);
tree.reveal(checkedElements.get(checkedElements.size() - 1));
}
tree.setSelection(new StructuredSelection(checkedElements));
}
public boolean canMoveUp(List selectedElements) {
int nSelected= selectedElements.size();
int nElements= fFieldsList.size();
for (int i= 0; i < nElements && nSelected > 0; i++) {
if (!selectedElements.contains(fFieldsList.get(i))) {
return true;
}
nSelected--;
}
return false;
}
public boolean canMoveDown(List selectedElements) {
int nSelected= selectedElements.size();
for (int i= fFieldsList.size() - 1; i >= 0 && nSelected > 0; i--) {
if (!selectedElements.contains(fFieldsList.get(i))) {
return true;
}
nSelected--;
}
return false;
}
public List getFieldsList() {
return fFieldsList;
}
}
}
|
41,601 |
Bug 41601 CCE on opening classfile editor
|
20030813+0815 export i tried to open editor for IPackageFragment java.lang.ClassCastException: org/eclipse/jdt/internal/ui/javaeditor/InternalClassFileEditorInput incompatible with org/eclipse/ui/part/FileEditorInput at java.lang.Throwable.<init>(Throwable.java) at java.lang.Throwable.<init>(Throwable.java) at java.lang.ClassCastException.<init>(ClassCastException.java:56) at org.eclipse.ui.editors.text.FileDocumentProvider.isSynchronized (FileDocumentProvider.java:719) at org.eclipse.ui.texteditor.AbstractTextEditor.sanityCheckState (AbstractTextEditor.java:3011) at org.eclipse.ui.texteditor.StatusTextEditor.sanityCheckState (StatusTextEditor.java:182) at org.eclipse.ui.texteditor.AbstractTextEditor.safelySanityCheckState (AbstractTextEditor.java:2990) at org.eclipse.ui.texteditor.AbstractTextEditor$ActivationListener.handleActivation (AbstractTextEditor.java) at org.eclipse.ui.texteditor.AbstractTextEditor$ActivationListener.partActivated (AbstractTextEditor.java:732) at org.eclipse.ui.internal.PartListenerList$1.run(PartListenerList.java) at org.eclipse.core.internal.runtime.InternalPlatform.run (InternalPlatform.java) at org.eclipse.core.runtime.Platform.run(Platform.java) at org.eclipse.ui.internal.PartListenerList.firePartActivated (PartListenerList.java:47) at org.eclipse.ui.internal.WWinPartService$1.partActivated (WWinPartService.java:27) at org.eclipse.ui.internal.PartListenerList2$1.run (PartListenerList2.java:45) at org.eclipse.core.internal.runtime.InternalPlatform.run (InternalPlatform.java) at org.eclipse.core.runtime.Platform.run(Platform.java) at org.eclipse.ui.internal.PartListenerList2.firePartActivated (PartListenerList2.java) at org.eclipse.ui.internal.WorkbenchPage.firePartActivated (WorkbenchPage.java) at org.eclipse.ui.internal.WorkbenchPage.setActivePart (WorkbenchPage.java) at org.eclipse.ui.internal.WorkbenchPage.requestActivation (WorkbenchPage.java:2232) at org.eclipse.ui.internal.PartPane.requestActivation(PartPane.java:334) at org.eclipse.ui.internal.EditorPane.requestActivation (EditorPane.java:136) at org.eclipse.ui.internal.PartPane.handleEvent(PartPane.java:314) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java) at org.eclipse.swt.widgets.Shell.setActiveControl(Shell.java) at org.eclipse.swt.widgets.Shell.WM_MOUSEACTIVATE(Shell.java:1336) at org.eclipse.swt.widgets.Control.windowProc(Control.java) at org.eclipse.swt.widgets.Decorations.windowProc(Decorations.java) at org.eclipse.swt.widgets.Display.windowProc(Display.java) at org.eclipse.swt.internal.win32.OS.DefWindowProcW(Native Method) at org.eclipse.swt.internal.win32.OS.DefWindowProc(OS.java) at org.eclipse.swt.widgets.Scrollable.callWindowProc(Scrollable.java) at org.eclipse.swt.widgets.Control.windowProc(Control.java) at org.eclipse.swt.widgets.Display.windowProc(Display.java) at org.eclipse.swt.internal.win32.OS.DefWindowProcW(Native Method) at org.eclipse.swt.internal.win32.OS.DefWindowProc(OS.java) at org.eclipse.swt.widgets.Scrollable.callWindowProc(Scrollable.java) at org.eclipse.swt.widgets.Control.windowProc(Control.java) at org.eclipse.swt.widgets.Display.windowProc(Display.java) at org.eclipse.swt.internal.win32.OS.DefWindowProcW(Native Method) at org.eclipse.swt.internal.win32.OS.DefWindowProc(OS.java) at org.eclipse.swt.widgets.Scrollable.callWindowProc(Scrollable.java) at org.eclipse.swt.widgets.Control.windowProc(Control.java) at org.eclipse.swt.widgets.Display.windowProc(Display.java) at org.eclipse.swt.internal.win32.OS.DefWindowProcW(Native Method) at org.eclipse.swt.internal.win32.OS.DefWindowProc(OS.java) at org.eclipse.swt.widgets.Scrollable.callWindowProc(Scrollable.java) at org.eclipse.swt.widgets.Control.windowProc(Control.java) at org.eclipse.swt.widgets.Display.windowProc(Display.java) at org.eclipse.swt.internal.win32.OS.DefWindowProcW(Native Method) at org.eclipse.swt.internal.win32.OS.DefWindowProc(OS.java) at org.eclipse.swt.widgets.Scrollable.callWindowProc(Scrollable.java) at org.eclipse.swt.widgets.Control.windowProc(Control.java) at org.eclipse.swt.widgets.Display.windowProc(Display.java) at org.eclipse.swt.internal.win32.OS.DefWindowProcW(Native Method) at org.eclipse.swt.internal.win32.OS.DefWindowProc(OS.java) at org.eclipse.swt.widgets.Scrollable.callWindowProc(Scrollable.java) at org.eclipse.swt.widgets.Control.windowProc(Control.java) at org.eclipse.swt.widgets.Display.windowProc(Display.java) at org.eclipse.swt.internal.win32.OS.DefWindowProcW(Native Method) at org.eclipse.swt.internal.win32.OS.DefWindowProc(OS.java) at org.eclipse.swt.widgets.Scrollable.callWindowProc(Scrollable.java) at org.eclipse.swt.widgets.Control.windowProc(Control.java) at org.eclipse.swt.widgets.Display.windowProc(Display.java) at org.eclipse.swt.internal.win32.OS.DefWindowProcW(Native Method) at org.eclipse.swt.internal.win32.OS.DefWindowProc(OS.java) at org.eclipse.swt.widgets.Scrollable.callWindowProc(Scrollable.java) at org.eclipse.swt.widgets.Control.windowProc(Control.java) at org.eclipse.swt.widgets.Display.windowProc(Display.java) at org.eclipse.swt.internal.win32.OS.DefWindowProcW(Native Method) at org.eclipse.swt.internal.win32.OS.DefWindowProc(OS.java) at org.eclipse.swt.widgets.Scrollable.callWindowProc(Scrollable.java) at org.eclipse.swt.widgets.Control.windowProc(Control.java) at org.eclipse.swt.widgets.Display.windowProc(Display.java) at org.eclipse.swt.internal.win32.OS.DefWindowProcW(Native Method) at org.eclipse.swt.internal.win32.OS.DefWindowProc(OS.java) at org.eclipse.swt.widgets.Scrollable.callWindowProc(Scrollable.java) at org.eclipse.swt.widgets.Control.windowProc(Control.java) at org.eclipse.swt.widgets.Display.windowProc(Display.java) at org.eclipse.swt.internal.win32.OS.DefWindowProcW(Native Method) at org.eclipse.swt.internal.win32.OS.DefWindowProc(OS.java) at org.eclipse.swt.widgets.Scrollable.callWindowProc(Scrollable.java) at org.eclipse.swt.widgets.Control.windowProc(Control.java) at org.eclipse.swt.widgets.Display.windowProc(Display.java) at org.eclipse.swt.internal.win32.OS.PeekMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.PeekMessage(OS.java) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1676) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1659) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at java.lang.reflect.AccessibleObject.invokeL(AccessibleObject.java:207) at java.lang.reflect.Method.invoke(Method.java:271) at org.eclipse.core.launcher.Main.basicRun(Main.java:291) at org.eclipse.core.launcher.Main.run(Main.java:747) at org.eclipse.core.launcher.Main.main(Main.java:583)
|
resolved fixed
|
1e27a1d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-15T12:17:15Z | 2003-08-15T09:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/ClassFileDocumentProvider.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.javaeditor;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.editors.text.FileDocumentProvider;
import org.eclipse.jdt.core.ElementChangedEvent;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.IElementChangedListener;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaElementDelta;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jdt.internal.ui.IResourceLocator;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.IJavaPartitions;
/**
* A document provider for class files. Class files can be either inside
*/
public class ClassFileDocumentProvider extends FileDocumentProvider {
/**
* An input change listener to request the editor to reread the input.
*/
public interface InputChangeListener {
void inputChanged(IClassFileEditorInput input);
}
/**
* Synchronizes the document with external resource changes.
*/
protected class ClassFileSynchronizer implements IElementChangedListener {
protected IClassFileEditorInput fInput;
protected IPackageFragmentRoot fPackageFragmentRoot;
/**
* Default constructor.
*/
public ClassFileSynchronizer(IClassFileEditorInput input) {
fInput= input;
IJavaElement parent= fInput.getClassFile().getParent();
while (parent != null && !(parent instanceof IPackageFragmentRoot)) {
parent= parent.getParent();
}
fPackageFragmentRoot= (IPackageFragmentRoot) parent;
}
/**
* Installs the synchronizer.
*/
public void install() {
JavaCore.addElementChangedListener(this);
}
/**
* Uninstalls the synchronizer.
*/
public void uninstall() {
JavaCore.removeElementChangedListener(this);
}
/*
* @see IElementChangedListener#elementChanged
*/
public void elementChanged(ElementChangedEvent e) {
check(fPackageFragmentRoot, e.getDelta());
}
/**
* Recursively check whether the class file has been deleted.
* Returns true if delta processing can be stopped.
*/
protected boolean check(IPackageFragmentRoot input, IJavaElementDelta delta) {
IJavaElement element= delta.getElement();
if ((delta.getKind() & IJavaElementDelta.REMOVED) != 0 || (delta.getFlags() & IJavaElementDelta.F_CLOSED) != 0) {
// http://dev.eclipse.org/bugs/show_bug.cgi?id=19023
if (element.equals(input.getJavaProject()) || element.equals(input)) {
handleDeleted(fInput);
return true;
}
}
if (((delta.getFlags() & IJavaElementDelta.F_ARCHIVE_CONTENT_CHANGED) != 0) && input.equals(element)) {
handleDeleted(fInput);
return true;
}
if (((delta.getFlags() & IJavaElementDelta.F_REMOVED_FROM_CLASSPATH) != 0) && input.equals(element)) {
handleDeleted(fInput);
return true;
}
IJavaElementDelta[] subdeltas= delta.getAffectedChildren();
for (int i= 0; i < subdeltas.length; i++) {
if (check(input, subdeltas[i]))
return true;
}
if ((delta.getFlags() & IJavaElementDelta.F_SOURCEDETACHED) != 0 ||
(delta.getFlags() & IJavaElementDelta.F_SOURCEATTACHED) != 0)
{
IClassFile file= fInput != null ? fInput.getClassFile() : null;
IJavaProject project= input != null ? input.getJavaProject() : null;
boolean isOnClasspath= false;
if (file != null && project != null)
isOnClasspath= project.isOnClasspath(file);
if (isOnClasspath) {
fireInputChanged(fInput);
return false;
} else {
handleDeleted(fInput);
return true;
}
}
return false;
}
}
/**
* Correcting the visibility of <code>FileSynchronizer</code>.
*/
protected class _FileSynchronizer extends FileSynchronizer {
public _FileSynchronizer(IFileEditorInput fileEditorInput) {
super(fileEditorInput);
}
}
/**
* Bundle of all required informations.
*/
protected class ClassFileInfo extends FileInfo {
ClassFileSynchronizer fClassFileSynchronizer= null;
ClassFileInfo(IDocument document, IAnnotationModel model, _FileSynchronizer fileSynchronizer) {
super(document, model, fileSynchronizer);
}
ClassFileInfo(IDocument document, IAnnotationModel model, ClassFileSynchronizer classFileSynchronizer) {
super(document, model, null);
fClassFileSynchronizer= classFileSynchronizer;
}
}
/** Input change listeners. */
private List fInputListeners= new ArrayList();
/**
* Creates a new document provider.
*/
public ClassFileDocumentProvider() {
super();
}
/*
* @see StorageDocumentProvider#setDocumentContent(IDocument, IEditorInput)
*/
protected boolean setDocumentContent(IDocument document, IEditorInput editorInput, String encoding) throws CoreException {
if (editorInput instanceof IClassFileEditorInput) {
IClassFile classFile= ((IClassFileEditorInput) editorInput).getClassFile();
document.set(classFile.getSource());
return true;
}
return super.setDocumentContent(document, editorInput, encoding);
}
/**
* Creates an annotation model derrived from the given class file editor input.
* @param the editor input from which to query the annotations
* @return the created annotation model
* @exception CoreException if the editor input could not be accessed
*/
protected IAnnotationModel createClassFileAnnotationModel(IClassFileEditorInput classFileEditorInput) throws CoreException {
IResource resource= null;
IClassFile classFile= classFileEditorInput.getClassFile();
IResourceLocator locator= (IResourceLocator) classFile.getAdapter(IResourceLocator.class);
if (locator != null)
resource= locator.getContainingResource(classFile);
if (resource != null) {
ClassFileMarkerAnnotationModel model= new ClassFileMarkerAnnotationModel(resource);
model.setClassFile(classFile);
return model;
}
return null;
}
/*
* @see AbstractDocumentProvider#createDocument(Object)
*/
protected IDocument createDocument(Object element) throws CoreException {
IDocument document= super.createDocument(element);
if (document != null) {
JavaTextTools tools= JavaPlugin.getDefault().getJavaTextTools();
tools.setupDocument(document, IJavaPartitions.JAVA_PARTITIONING);
}
return document;
}
/*
* @see AbstractDocumentProvider#createElementInfo(Object)
*/
protected ElementInfo createElementInfo(Object element) throws CoreException {
if (element instanceof IClassFileEditorInput) {
IClassFileEditorInput input = (IClassFileEditorInput) element;
ExternalClassFileEditorInput external= null;
if (input instanceof ExternalClassFileEditorInput)
external= (ExternalClassFileEditorInput) input;
if (external != null) {
try {
refreshFile(external.getFile());
} catch (CoreException x) {
handleCoreException(x, JavaEditorMessages.getString("ClassFileDocumentProvider.error.createElementInfo")); //$NON-NLS-1$
}
}
IDocument d= createDocument(input);
IAnnotationModel m= createClassFileAnnotationModel(input);
if (external != null) {
ClassFileInfo info= new ClassFileInfo(d, m, (_FileSynchronizer) null);
info.fModificationStamp= computeModificationStamp(external.getFile());
info.fEncoding= getPersistedEncoding(element);
return info;
} else if (input instanceof InternalClassFileEditorInput) {
ClassFileSynchronizer s= new ClassFileSynchronizer(input);
s.install();
ClassFileInfo info= new ClassFileInfo(d, m, s);
info.fEncoding= getPersistedEncoding(element);
return info;
}
}
return null;
}
/*
* @see FileDocumentProvider#disposeElementInfo(Object, ElementInfo)
*/
protected void disposeElementInfo(Object element, ElementInfo info) {
ClassFileInfo classFileInfo= (ClassFileInfo) info;
if (classFileInfo.fClassFileSynchronizer != null) {
classFileInfo.fClassFileSynchronizer.uninstall();
classFileInfo.fClassFileSynchronizer= null;
}
super.disposeElementInfo(element, info);
}
/*
* @see AbstractDocumentProvider#doSaveDocument(IProgressMonitor, Object, IDocument)
*/
protected void doSaveDocument(IProgressMonitor monitor, Object element, IDocument document) throws CoreException {
}
/**
* Handles the deletion of the element underlying the given class file editor input.
* @param input the editor input
*/
protected void handleDeleted(IClassFileEditorInput input) {
fireElementDeleted(input);
}
/**
* Fires input changes to input change listeners.
*/
protected void fireInputChanged(IClassFileEditorInput input) {
List list= new ArrayList(fInputListeners);
for (Iterator i = list.iterator(); i.hasNext();)
((InputChangeListener) i.next()).inputChanged(input);
}
/**
* Adds an input change listener.
*/
public void addInputChangeListener(InputChangeListener listener) {
fInputListeners.add(listener);
}
/**
* Removes an input change listener.
*/
public void removeInputChangeListener(InputChangeListener listener) {
fInputListeners.remove(listener);
}
}
|
41,597 |
Bug 41597 move instance method: fails for "this"-qualified field access [refactoring]
|
Field accesses of the form this.s are not handled properly. Note that they need different behavior depending on context: - As target of a MethodInvocation: => implicit "this" => remove it. - Otherwise: explicit "this". Example: move A::print() to field s ----------------------------------- package p; public class A { Second s; Second s2; public void print() { int s= 17; this.s.foo(s2); this.s2.foo(this.s); } } package p; class Second { public void foo(Second s) { } }
|
resolved fixed
|
ab7c8af
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-15T13:22:25Z | 2003-08-15T09:33:20Z |
org.eclipse.jdt.ui.tests.refactoring/resources/MoveInstanceMethod/canMove/test12/out/B.java
|
package p2;
public class B {
public void mB1() {}
public void mB2() {}
public void mA1(float j, int foo, String bar) {
mB1();
System.out.println(bar + j);
}
}
|
41,597 |
Bug 41597 move instance method: fails for "this"-qualified field access [refactoring]
|
Field accesses of the form this.s are not handled properly. Note that they need different behavior depending on context: - As target of a MethodInvocation: => implicit "this" => remove it. - Otherwise: explicit "this". Example: move A::print() to field s ----------------------------------- package p; public class A { Second s; Second s2; public void print() { int s= 17; this.s.foo(s2); this.s2.foo(this.s); } } package p; class Second { public void foo(Second s) { } }
|
resolved fixed
|
ab7c8af
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-15T13:22:25Z | 2003-08-15T09:33:20Z |
org.eclipse.jdt.ui.tests.refactoring/resources/MoveInstanceMethod/canMove/test21/in/A.java
| |
41,597 |
Bug 41597 move instance method: fails for "this"-qualified field access [refactoring]
|
Field accesses of the form this.s are not handled properly. Note that they need different behavior depending on context: - As target of a MethodInvocation: => implicit "this" => remove it. - Otherwise: explicit "this". Example: move A::print() to field s ----------------------------------- package p; public class A { Second s; Second s2; public void print() { int s= 17; this.s.foo(s2); this.s2.foo(this.s); } } package p; class Second { public void foo(Second s) { } }
|
resolved fixed
|
ab7c8af
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-15T13:22:25Z | 2003-08-15T09:33:20Z |
org.eclipse.jdt.ui.tests.refactoring/resources/MoveInstanceMethod/canMove/test21/in/Second.java
| |
41,597 |
Bug 41597 move instance method: fails for "this"-qualified field access [refactoring]
|
Field accesses of the form this.s are not handled properly. Note that they need different behavior depending on context: - As target of a MethodInvocation: => implicit "this" => remove it. - Otherwise: explicit "this". Example: move A::print() to field s ----------------------------------- package p; public class A { Second s; Second s2; public void print() { int s= 17; this.s.foo(s2); this.s2.foo(this.s); } } package p; class Second { public void foo(Second s) { } }
|
resolved fixed
|
ab7c8af
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-15T13:22:25Z | 2003-08-15T09:33:20Z |
org.eclipse.jdt.ui.tests.refactoring/resources/MoveInstanceMethod/canMove/test21/out/A.java
| |
41,597 |
Bug 41597 move instance method: fails for "this"-qualified field access [refactoring]
|
Field accesses of the form this.s are not handled properly. Note that they need different behavior depending on context: - As target of a MethodInvocation: => implicit "this" => remove it. - Otherwise: explicit "this". Example: move A::print() to field s ----------------------------------- package p; public class A { Second s; Second s2; public void print() { int s= 17; this.s.foo(s2); this.s2.foo(this.s); } } package p; class Second { public void foo(Second s) { } }
|
resolved fixed
|
ab7c8af
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-15T13:22:25Z | 2003-08-15T09:33:20Z |
org.eclipse.jdt.ui.tests.refactoring/resources/MoveInstanceMethod/canMove/test21/out/Second.java
| |
41,597 |
Bug 41597 move instance method: fails for "this"-qualified field access [refactoring]
|
Field accesses of the form this.s are not handled properly. Note that they need different behavior depending on context: - As target of a MethodInvocation: => implicit "this" => remove it. - Otherwise: explicit "this". Example: move A::print() to field s ----------------------------------- package p; public class A { Second s; Second s2; public void print() { int s= 17; this.s.foo(s2); this.s2.foo(this.s); } } package p; class Second { public void foo(Second s) { } }
|
resolved fixed
|
ab7c8af
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-15T13:22:25Z | 2003-08-15T09:33:20Z |
org.eclipse.jdt.ui.tests.refactoring/resources/MoveInstanceMethod/canMove/test22/in/A.java
| |
41,597 |
Bug 41597 move instance method: fails for "this"-qualified field access [refactoring]
|
Field accesses of the form this.s are not handled properly. Note that they need different behavior depending on context: - As target of a MethodInvocation: => implicit "this" => remove it. - Otherwise: explicit "this". Example: move A::print() to field s ----------------------------------- package p; public class A { Second s; Second s2; public void print() { int s= 17; this.s.foo(s2); this.s2.foo(this.s); } } package p; class Second { public void foo(Second s) { } }
|
resolved fixed
|
ab7c8af
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-15T13:22:25Z | 2003-08-15T09:33:20Z |
org.eclipse.jdt.ui.tests.refactoring/resources/MoveInstanceMethod/canMove/test22/in/Second.java
| |
41,597 |
Bug 41597 move instance method: fails for "this"-qualified field access [refactoring]
|
Field accesses of the form this.s are not handled properly. Note that they need different behavior depending on context: - As target of a MethodInvocation: => implicit "this" => remove it. - Otherwise: explicit "this". Example: move A::print() to field s ----------------------------------- package p; public class A { Second s; Second s2; public void print() { int s= 17; this.s.foo(s2); this.s2.foo(this.s); } } package p; class Second { public void foo(Second s) { } }
|
resolved fixed
|
ab7c8af
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-15T13:22:25Z | 2003-08-15T09:33:20Z |
org.eclipse.jdt.ui.tests.refactoring/resources/MoveInstanceMethod/canMove/test22/out/A.java
| |
41,597 |
Bug 41597 move instance method: fails for "this"-qualified field access [refactoring]
|
Field accesses of the form this.s are not handled properly. Note that they need different behavior depending on context: - As target of a MethodInvocation: => implicit "this" => remove it. - Otherwise: explicit "this". Example: move A::print() to field s ----------------------------------- package p; public class A { Second s; Second s2; public void print() { int s= 17; this.s.foo(s2); this.s2.foo(this.s); } } package p; class Second { public void foo(Second s) { } }
|
resolved fixed
|
ab7c8af
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-15T13:22:25Z | 2003-08-15T09:33:20Z |
org.eclipse.jdt.ui.tests.refactoring/resources/MoveInstanceMethod/canMove/test22/out/Second.java
| |
41,597 |
Bug 41597 move instance method: fails for "this"-qualified field access [refactoring]
|
Field accesses of the form this.s are not handled properly. Note that they need different behavior depending on context: - As target of a MethodInvocation: => implicit "this" => remove it. - Otherwise: explicit "this". Example: move A::print() to field s ----------------------------------- package p; public class A { Second s; Second s2; public void print() { int s= 17; this.s.foo(s2); this.s2.foo(this.s); } } package p; class Second { public void foo(Second s) { } }
|
resolved fixed
|
ab7c8af
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-15T13:22:25Z | 2003-08-15T09:33:20Z |
org.eclipse.jdt.ui.tests.refactoring/resources/MoveInstanceMethod/canMove/test23/in/A.java
| |
41,597 |
Bug 41597 move instance method: fails for "this"-qualified field access [refactoring]
|
Field accesses of the form this.s are not handled properly. Note that they need different behavior depending on context: - As target of a MethodInvocation: => implicit "this" => remove it. - Otherwise: explicit "this". Example: move A::print() to field s ----------------------------------- package p; public class A { Second s; Second s2; public void print() { int s= 17; this.s.foo(s2); this.s2.foo(this.s); } } package p; class Second { public void foo(Second s) { } }
|
resolved fixed
|
ab7c8af
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-15T13:22:25Z | 2003-08-15T09:33:20Z |
org.eclipse.jdt.ui.tests.refactoring/resources/MoveInstanceMethod/canMove/test23/in/Second.java
| |
41,597 |
Bug 41597 move instance method: fails for "this"-qualified field access [refactoring]
|
Field accesses of the form this.s are not handled properly. Note that they need different behavior depending on context: - As target of a MethodInvocation: => implicit "this" => remove it. - Otherwise: explicit "this". Example: move A::print() to field s ----------------------------------- package p; public class A { Second s; Second s2; public void print() { int s= 17; this.s.foo(s2); this.s2.foo(this.s); } } package p; class Second { public void foo(Second s) { } }
|
resolved fixed
|
ab7c8af
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-15T13:22:25Z | 2003-08-15T09:33:20Z |
org.eclipse.jdt.ui.tests.refactoring/resources/MoveInstanceMethod/canMove/test23/out/A.java
| |
41,597 |
Bug 41597 move instance method: fails for "this"-qualified field access [refactoring]
|
Field accesses of the form this.s are not handled properly. Note that they need different behavior depending on context: - As target of a MethodInvocation: => implicit "this" => remove it. - Otherwise: explicit "this". Example: move A::print() to field s ----------------------------------- package p; public class A { Second s; Second s2; public void print() { int s= 17; this.s.foo(s2); this.s2.foo(this.s); } } package p; class Second { public void foo(Second s) { } }
|
resolved fixed
|
ab7c8af
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-15T13:22:25Z | 2003-08-15T09:33:20Z |
org.eclipse.jdt.ui.tests.refactoring/resources/MoveInstanceMethod/canMove/test23/out/Second.java
| |
41,597 |
Bug 41597 move instance method: fails for "this"-qualified field access [refactoring]
|
Field accesses of the form this.s are not handled properly. Note that they need different behavior depending on context: - As target of a MethodInvocation: => implicit "this" => remove it. - Otherwise: explicit "this". Example: move A::print() to field s ----------------------------------- package p; public class A { Second s; Second s2; public void print() { int s= 17; this.s.foo(s2); this.s2.foo(this.s); } } package p; class Second { public void foo(Second s) { } }
|
resolved fixed
|
ab7c8af
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-15T13:22:25Z | 2003-08-15T09:33:20Z |
org.eclipse.jdt.ui.tests.refactoring/test
| |
41,597 |
Bug 41597 move instance method: fails for "this"-qualified field access [refactoring]
|
Field accesses of the form this.s are not handled properly. Note that they need different behavior depending on context: - As target of a MethodInvocation: => implicit "this" => remove it. - Otherwise: explicit "this". Example: move A::print() to field s ----------------------------------- package p; public class A { Second s; Second s2; public void print() { int s= 17; this.s.foo(s2); this.s2.foo(this.s); } } package p; class Second { public void foo(Second s) { } }
|
resolved fixed
|
ab7c8af
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-15T13:22:25Z | 2003-08-15T09:33:20Z |
cases/org/eclipse/jdt/ui/tests/refactoring/MoveInstanceMethodTests.java
| |
41,597 |
Bug 41597 move instance method: fails for "this"-qualified field access [refactoring]
|
Field accesses of the form this.s are not handled properly. Note that they need different behavior depending on context: - As target of a MethodInvocation: => implicit "this" => remove it. - Otherwise: explicit "this". Example: move A::print() to field s ----------------------------------- package p; public class A { Second s; Second s2; public void print() { int s= 17; this.s.foo(s2); this.s2.foo(this.s); } } package p; class Second { public void foo(Second s) { } }
|
resolved fixed
|
ab7c8af
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-15T13:22:25Z | 2003-08-15T09:33:20Z |
org.eclipse.jdt.ui/core
| |
41,597 |
Bug 41597 move instance method: fails for "this"-qualified field access [refactoring]
|
Field accesses of the form this.s are not handled properly. Note that they need different behavior depending on context: - As target of a MethodInvocation: => implicit "this" => remove it. - Otherwise: explicit "this". Example: move A::print() to field s ----------------------------------- package p; public class A { Second s; Second s2; public void print() { int s= 17; this.s.foo(s2); this.s2.foo(this.s); } } package p; class Second { public void foo(Second s) { } }
|
resolved fixed
|
ab7c8af
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-15T13:22:25Z | 2003-08-15T09:33:20Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/InstanceMethodMover.java
| |
41,584 |
Bug 41584 Search references not hitting build path for working set [search]
|
This happens in 3.0M2 If I'm searching for references of a method, I usually right click, Search->References->Workspace. However, with large workspaces, this can take pretty long, so I've gotten in the habit of searching for references within a working set. I usually define a workingset for each project and all its contents. The problem is, when I search for references of a method in the workingset, it does not find references to that symbol from the thirdparty jars I have attached to the project's build path (verified the jar is selected as part of the working set). However, if I search the workspace, it does find the references in that thirdparty jar. This is usually for a method defined in the thirdparty jar that I use, and want to see how it is used by the thirdparty.
|
resolved fixed
|
09f2bf3
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-15T14:14:43Z | 2003-08-14T19:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/JavaSearchScopeFactory.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.search;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.ui.IWorkingSet;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.IWorkingSetSelectionDialog;
import org.eclipse.search.ui.ISearchResultViewEntry;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.browsing.LogicalPackage;
public class JavaSearchScopeFactory {
private static JavaSearchScopeFactory fgInstance;
private static final IJavaSearchScope EMPTY_SCOPE= SearchEngine.createJavaSearchScope(new IJavaElement[] {});
private static final Set EMPTY_SET= new HashSet(0);
private JavaSearchScopeFactory() {
}
public static JavaSearchScopeFactory getInstance() {
if (fgInstance == null)
fgInstance= new JavaSearchScopeFactory();
return fgInstance;
}
public IWorkingSet[] queryWorkingSets() throws JavaModelException {
Shell shell= JavaPlugin.getActiveWorkbenchShell();
if (shell == null)
return null;
IWorkingSetSelectionDialog dialog= PlatformUI.getWorkbench().getWorkingSetManager().createWorkingSetSelectionDialog(shell, true);
if (dialog.open() == Window.OK) {
IWorkingSet[] workingSets= dialog.getSelection();
if (workingSets.length > 0)
return workingSets;
}
return null;
}
public IJavaSearchScope createJavaSearchScope(IWorkingSet[] workingSets) {
if (workingSets == null || workingSets.length < 1)
return EMPTY_SCOPE;
Set javaElements= new HashSet(workingSets.length * 10);
for (int i= 0; i < workingSets.length; i++)
addJavaElements(javaElements, workingSets[i]);
return createJavaSearchScope(javaElements);
}
public IJavaSearchScope createJavaSearchScope(IWorkingSet workingSet) {
Set javaElements= new HashSet(10);
addJavaElements(javaElements, workingSet);
return createJavaSearchScope(javaElements);
}
public IJavaSearchScope createJavaSearchScope(IResource[] resources) {
if (resources == null)
return EMPTY_SCOPE;
Set javaElements= new HashSet(resources.length);
addJavaElements(javaElements, resources);
return createJavaSearchScope(javaElements);
}
public IJavaSearchScope createJavaSearchScope(ISelection selection) {
return createJavaSearchScope(getJavaElements(selection));
}
public IJavaSearchScope createJavaProjectSearchScope(ISelection selection) {
Set javaElements= getJavaElements(selection);
Set javaProjects= new HashSet(javaElements.size());
Iterator elements= javaElements.iterator();
while (elements.hasNext()) {
IJavaProject jp= ((IJavaElement)elements.next()).getJavaProject();
if (jp != null)
javaProjects.add(jp);
}
return createJavaSearchScope(javaProjects);
}
private Set getJavaElements(ISelection selection) {
Set javaElements;
if (selection instanceof IStructuredSelection && !selection.isEmpty()) {
Iterator iter= ((IStructuredSelection) selection).iterator();
javaElements= new HashSet(((IStructuredSelection) selection).size());
while (iter.hasNext()) {
Object selectedElement= iter.next();
// Unpack search result view entry
if (selectedElement instanceof ISearchResultViewEntry)
selectedElement= ((ISearchResultViewEntry) selectedElement).getGroupByKey();
if (selectedElement instanceof IJavaElement)
addJavaElements(javaElements, (IJavaElement) selectedElement);
else if (selectedElement instanceof IResource)
addJavaElements(javaElements, (IResource) selectedElement);
else if (selectedElement instanceof LogicalPackage)
addJavaElements(javaElements, (LogicalPackage) selectedElement);
else if (selectedElement instanceof IAdaptable) {
IResource resource= (IResource) ((IAdaptable) selectedElement).getAdapter(IResource.class);
if (resource != null)
addJavaElements(javaElements, resource);
}
}
} else {
javaElements= EMPTY_SET;
}
return javaElements;
}
private IJavaSearchScope createJavaSearchScope(Set javaElements) {
if (javaElements.isEmpty())
return EMPTY_SCOPE;
return SearchEngine.createJavaSearchScope((IJavaElement[])javaElements.toArray(new IJavaElement[javaElements.size()]));
}
private void addJavaElements(Set javaElements, IResource[] resources) {
for (int i= 0; i < resources.length; i++)
addJavaElements(javaElements, resources[i]);
}
private void addJavaElements(Set javaElements, IAdaptable resource) {
IJavaElement javaElement= (IJavaElement)resource.getAdapter(IJavaElement.class);
if (javaElement == null)
// not a Java resource
return;
if (javaElement.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
// add other possible package fragments
try {
addJavaElements(javaElements, ((IFolder)resource).members());
} catch (CoreException ex) {
// don't add elements
}
}
addJavaElements(javaElements, javaElement);
}
private void addJavaElements(Set javaElements, IJavaElement javaElement) {
switch (javaElement.getElementType()) {
case IJavaElement.JAVA_PROJECT:
addJavaElements(javaElements, (IJavaProject)javaElement);
break;
default:
javaElements.add(javaElement);
}
}
private void addJavaElements(Set javaElements, IJavaProject javaProject) {
IPackageFragmentRoot[] roots;
try {
roots= javaProject.getPackageFragmentRoots();
} catch (JavaModelException ex) {
return;
}
for (int i= 0; i < roots.length; i++)
if (!roots[i].isExternal())
javaElements.add(roots[i]);
}
private void addJavaElements(Set javaElements, IWorkingSet workingSet) {
if (workingSet == null)
return;
IAdaptable[] elements= workingSet.getElements();
for (int i= 0; i < elements.length; i++) {
if (elements[i] instanceof IJavaElement)
addJavaElements(javaElements, (IJavaElement)elements[i]);
else
addJavaElements(javaElements, elements[i]);
}
}
public void addJavaElements(Set javaElements, LogicalPackage selectedElement) {
IPackageFragment[] packages= selectedElement.getFragments();
for (int i= 0; i < packages.length; i++)
addJavaElements(javaElements, packages[i]);
}
}
|
41,598 |
Bug 41598 NPE in TypedPosition on commenting
|
20030813+0815 export select a sequence of lines and press ctrl+/ java.fullversion=J2RE 1.3.1 IBM J9 build 20030605 (JIT enabled) BootLoader constants: OS=win32, ARCH=x86, WS=win32, NL=en_US Command-line arguments: -os win32 -ws win32 -arch x86 -data d:\eclipseWorkbench7 \plugins -showlocation -install file:D:/eclipse20030813/eclipse/ !ENTRY org.eclipse.ui 4 4 Aug 15, 2003 11:43:32.739 !MESSAGE Unhandled exception caught in event loop. !ENTRY org.eclipse.ui 4 0 Aug 15, 2003 11:43:32.759 !MESSAGE java.lang.NullPointerException !STACK 0 java.lang.NullPointerException at java.lang.Throwable.<init>(Throwable.java) at java.lang.Throwable.<init>(Throwable.java) at java.lang.NullPointerException.<init>(NullPointerException.java:63) at org.eclipse.jface.text.TypedPosition.<init>(TypedPosition.java:41) at org.eclipse.jface.text.presentation.PresentationReconciler$InternalListener.docu mentAboutToBeChanged(PresentationReconciler.java:153) at org.eclipse.jface.text.AbstractDocument.fireDocumentAboutToBeChanged (AbstractDocument.java:549) at org.eclipse.jface.text.AbstractDocument.replace (AbstractDocument.java:956) at org.eclipse.jdt.internal.ui.javaeditor.PartiallySynchronizedDocument.replace (PartiallySynchronizedDocument.java:61) at org.eclipse.jface.text.TextViewer.shiftRight(TextViewer.java:3594) at org.eclipse.jface.text.TextViewer.shift(TextViewer.java:3546) at org.eclipse.jface.text.TextViewer.doOperation(TextViewer.java:3279) at org.eclipse.jface.text.source.SourceViewer.doOperation (SourceViewer.java:507) at org.eclipse.jdt.internal.ui.javaeditor.JavaSourceViewer.doOperation (JavaSourceViewer.java:72) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor$AdaptedSourceViewer .doOperation(CompilationUnitEditor.java:164) at org.eclipse.ui.texteditor.TextOperationAction$1.run (TextOperationAction.java:127) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java) at org.eclipse.ui.texteditor.TextOperationAction.run (TextOperationAction.java:125) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.ui.actions.RetargetAction.runWithEvent (RetargetAction.java:203) at org.eclipse.ui.internal.WWinPluginAction.runWithEvent (WWinPluginAction.java:212) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:542) at org.eclipse.jface.action.ActionContributionItem.access$4 (ActionContributionItem.java:496) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent (ActionContributionItem.java:468) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1676) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1659) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at java.lang.reflect.AccessibleObject.invokeL(AccessibleObject.java:207) at java.lang.reflect.Method.invoke(Method.java:271) at org.eclipse.core.launcher.Main.basicRun(Main.java:291) at org.eclipse.core.launcher.Main.run(Main.java:747) at org.eclipse.core.launcher.Main.main(Main.java:583)
|
resolved fixed
|
e6789e1
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-15T15:45:35Z | 2003-08-15T09:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/SmartSemicolonAutoEditStrategy.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text.java;
import java.util.Arrays;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DocumentCommand;
import org.eclipse.jface.text.IAutoEditStrategy;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.text.TextUtilities;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.texteditor.ITextEditorExtension2;
import org.eclipse.ui.texteditor.ITextEditorExtension3;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.core.Assert;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor;
import org.eclipse.jdt.internal.ui.text.IJavaPartitions;
/**
* Modifies <code>DocumentCommand</code>s inserting semicolons and opening braces to place them
* smartly, i.e. moving them to the end of a line if that is what the user expects.
*
* <p>In practice, semicolons and braces (and the caret) are moved to the end of the line if they are typed
* anywhere except for semicolons in a <code>for</code> statements definition. If the line contains a semicolon
* or brace after the current caret position, the cursor is moved after it.</p>
*
* @see org.eclipse.jface.text.DocumentCommand
* @since 3.0
*/
public class SmartSemicolonAutoEditStrategy implements IAutoEditStrategy {
/** String representation of a semicolon. */
private static final String SEMICOLON= ";"; //$NON-NLS-1$
/** Char representation of a semicolon. */
private static final char SEMICHAR= ';';
/** String represenattion of a opening brace. */
private static final String BRACE= "{"; //$NON-NLS-1$
/** Char representation of a opening brace */
private static final char BRACECHAR= '{';
private char fCharacter;
private String fPartitioning;
/**
* Creates a new SmartSemicolonAutoEditStrategy.
*
* @param partitioning the document partitioning
*/
public SmartSemicolonAutoEditStrategy(String partitioning) {
fPartitioning= partitioning;
}
/*
* @see org.eclipse.jface.text.IAutoEditStrategy#customizeDocumentCommand(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.DocumentCommand)
*/
public void customizeDocumentCommand(IDocument document, DocumentCommand command) {
// 0: early pruning
// also customize if <code>doit</code> is false (so it works in code completion situations)
// if (!command.doit)
// return;
if (command.text == null)
return;
if (command.text.equals(SEMICOLON))
fCharacter= SEMICHAR;
else if (command.text.equals(BRACE))
fCharacter= BRACECHAR;
else
return;
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
if (fCharacter == SEMICHAR && !store.getBoolean(PreferenceConstants.EDITOR_SMART_SEMICOLON))
return;
if (fCharacter == BRACECHAR && !store.getBoolean(PreferenceConstants.EDITOR_SMART_OPENING_BRACE))
return;
IWorkbenchPage page= JavaPlugin.getActivePage();
if (page == null)
return;
IEditorPart part= page.getActiveEditor();
if (!(part instanceof CompilationUnitEditor))
return;
CompilationUnitEditor editor= (CompilationUnitEditor)part;
if (editor.getInsertMode() != ITextEditorExtension3.SMART_INSERT || !editor.isEditable())
return;
ITextEditorExtension2 extension= (ITextEditorExtension2)editor.getAdapter(ITextEditorExtension2.class);
if (extension != null && !extension.validateEditorInputState())
return;
// 1: find concerned line / position in java code, location in statement
int pos= command.offset;
ITextSelection line;
try {
IRegion l= document.getLineInformationOfOffset(pos);
line= new TextSelection(document, l.getOffset(), l.getLength());
} catch (BadLocationException e) {
return;
}
// 2: choose action based on findings (is for-Statement?)
// for now: compute the best position to insert the new character
int positionInLine= computeCharacterPosition(document, line, pos - line.getOffset(), fCharacter, fPartitioning);
int position= positionInLine + line.getOffset();
// never position before the current position!
if (position < pos)
return;
// never double already existing content
if (alreadyPresent(document, fCharacter, position))
return;
// 3: modify command
command.offset= position;
command.length= 0;
command.caretOffset= position;
command.text= adjustSpacing(document, position, fCharacter);
command.doit= true;
}
/**
* Adds a space before a brace if it is inserted after a parenthesis, equal sign, or one
* of the keywords <code>try, else, do</code>.
*
* @param document the document we are working on
* @param position the insert position of <code>character</code>
* @param character the character to be inserted
* @return a <code>String</code> consisting of <code>character</code> plus any additional spacing
*/
private String adjustSpacing(IDocument doc, int position, char character) {
if (character == BRACECHAR) {
if (position > 0 && position <= doc.getLength()) {
int pos= position - 1;
if (looksLike(doc, pos, ")") //$NON-NLS-1$
|| looksLike(doc, pos, "=") //$NON-NLS-1$
|| looksLike(doc, pos, "]") //$NON-NLS-1$
|| looksLike(doc, pos, "try") //$NON-NLS-1$
|| looksLike(doc, pos, "else") //$NON-NLS-1$
|| looksLike(doc, pos, "synchronized") //$NON-NLS-1$
|| looksLike(doc, pos, "static") //$NON-NLS-1$
|| looksLike(doc, pos, "do")) //$NON-NLS-1$
return new String(new char[] { ' ', character });
}
}
return new String(new char[] { character });
}
/**
* Checks whether a character to be inserted is already present at the insert location (perhaps
* separated by some whitespace from <code>position</code>.
*
* @param document the document we are working on
* @param position the insert position of <code>ch</code>
* @param character the character to be inserted
* @return <code>true</code> if <code>ch</code> is already present at <code>location</code>, <code>false</code> otherwise
*/
private boolean alreadyPresent(IDocument document, char ch, int position) {
int pos= firstNonWhitespaceForward(document, position, fPartitioning, document.getLength());
try {
if (pos != -1 && document.getChar(pos) == ch)
return true;
} catch (BadLocationException e) {
}
return false;
}
/**
* Computes the next insert position of the given character in the current line.
*
* @param document the document we are working on
* @param line the line where the change is being made
* @param offset the position of the caret in the line when <code>character</code> was typed
* @param character the character to look for
* @param partitioning the document partitioning
* @return the position where <code>character</code> should be inserted / replaced
*/
protected static int computeCharacterPosition(IDocument document, ITextSelection line, int offset, char character, String partitioning) {
String text= line.getText();
if (text == null)
return 0;
int insertPos;
if (character == BRACECHAR) {
insertPos= computeArrayInitializationPos(document, line, offset, partitioning);
if (insertPos == -1) {
insertPos= computeAfterTryDoElse(document, line, offset);
}
if (insertPos == -1) {
insertPos= computeAfterParenthesis(document, line, offset, partitioning);
}
} else if (character == SEMICHAR) {
int nextPartitionPos= nextPartitionOrLineEnd(document, line, offset, partitioning);
insertPos= offset;
if (!isForStatement(text, offset)) {
insertPos= startOfWhitespaceBeforeOffset(text, nextPartitionPos);
}
} else {
Assert.isTrue(false);
return -1;
}
return insertPos;
}
/**
* Computes an insert position for an opening brace if <code>offset</code> maps to a position in
* <code>document</code> that looks like being the RHS of an assignment or like an array definition.
*
* @param document the document being modified
* @param line the current line under investigation
* @param offset the offset of the caret position, relative to the line start.
* @param partitioning the document partitioning
* @return an insert position relative to the line start if <code>line</code> looks like being an array initialization at <code>offset</code>, -1 otherwise
*/
private static int computeArrayInitializationPos(IDocument document, ITextSelection line, int offset, String partitioning) {
// search backward while WS, find = (not != <= >= ==) in default partition
int pos= offset + line.getOffset();
if (pos == 0)
return -1;
int p= firstNonWhitespaceBackward(document, pos - 1, partitioning, -1);
if (p == -1)
return -1;
try {
char ch= document.getChar(p);
if (ch != '=' && ch != ']')
return -1;
if (p == 0)
return offset;
p= firstNonWhitespaceBackward(document, p - 1, partitioning, -1);
if (p == -1)
return -1;
ch= document.getChar(p);
if (Character.isJavaIdentifierPart(ch) || ch == ']' || ch == '[')
return offset;
} catch (BadLocationException e) {
}
return -1;
}
/**
* Computes an insert position for an opening brace if <code>offset</code> maps to a position in
* <code>document</code> involving a keyword taking a block after it. These are: <code>try</code>,
* <code>do</code>, <code>synchronized</code>, <code>static</code>, or <code>else</code>.
*
* @param document the document being modified
* @param line the current line under investigation
* @param offset the offset of the caret position, relative to the line start.
* @return an insert position relative to the line start if <code>line</code> contains one of the above keywords at or before <code>offset</code>, -1 otherwise
*/
private static int computeAfterTryDoElse(IDocument doc, ITextSelection line, int offset) {
// search backward while WS, find 'try', 'do', 'else' in default partition
int p= offset + line.getOffset();
p= firstWhitespaceToRight(doc, p);
if (p == -1)
return -1;
p--;
if (looksLike(doc, p, "try") //$NON-NLS-1$
|| looksLike(doc, p, "do") //$NON-NLS-1$
|| looksLike(doc, p, "synchronized") //$NON-NLS-1$
|| looksLike(doc, p, "static") //$NON-NLS-1$
|| looksLike(doc, p, "else")) //$NON-NLS-1$
return p + 1 - line.getOffset();
return -1;
}
/**
* Computes an insert position for an opening brace if <code>offset</code> maps to a position in
* <code>document</code> with a expression in parenthesis that will take a block after the closing parenthesis.
*
* @param document the document being modified
* @param line the current line under investigation
* @param offset the offset of the caret position, relative to the line start.
* @param partitioning the document partitioning
* @return an insert position relative to the line start if <code>line</code> contains a parenthesized expression that can be followed by a block, -1 otherwise
*/
private static int computeAfterParenthesis(IDocument document, ITextSelection line, int offset, String partitioning) {
// find the opening parenthesis for every closing parenthesis on the current line after offset
// return the position behind the closing parenthesis if it looks like a method declaration
// or an expression for an if, while, for, catch statement
int pos= offset + line.getOffset();
int length= line.getOffset() + line.getLength();
int scanTo= scanForward(document, pos, partitioning, length, '}');
if (scanTo == -1)
scanTo= length;
int closingParen= findClosingParenToLeft(document, pos, partitioning) - 1;
while (true) {
int startScan= closingParen + 1;
closingParen= scanForward(document, startScan, partitioning, scanTo, ')');
if (closingParen == -1)
break;
int openingParen= findOpeningParenMatch(document, closingParen, partitioning);
// no way an expression at the beginning of the document can mean anything
if (openingParen < 1)
break;
// only select insert positions for parenthesis currently embracing the caret
if (openingParen > pos)
continue;
if (looksLikeAnonymousClassDef(document, openingParen - 1, partitioning))
return closingParen + 1 - line.getOffset();
if (looksLikeIfWhileForCatch(document, openingParen - 1, partitioning))
return closingParen + 1 - line.getOffset();
if (looksLikeMethodDecl(document, openingParen - 1, partitioning))
return closingParen + 1 - line.getOffset();
}
return -1;
}
/**
* Finds a closing parenthesis to the left of <code>position</code> in document, where that parenthesis is only
* separated by whitespace from <code>position</code>. If no such parenthesis can be found, <code>position</code> is returned.
*
* @param document the document being modified
* @param position the first character position in <code>document</code> to be considered
* @param partitioning the document partitioning
* @return the position of a closing parenthesis left to <code>position</code> separated only by whitespace, or <code>position</code> if no parenthesis can be found
*/
private static int findClosingParenToLeft(IDocument document, int position, String partitioning) {
final char CLOSING_PAREN= ')';
try {
if (position < 1)
return position;
int nonWS= firstNonWhitespaceBackward(document, position - 1, partitioning, -1);
if (nonWS != -1 && document.getChar(nonWS) == CLOSING_PAREN)
return nonWS;
} catch (BadLocationException e1) {
}
return position;
}
/**
* Finds the first whitespace character position to the right of (and including) <code>position</code>.
*
* @param document the document being modified
* @param position the first character position in <code>document</code> to be considered
* @return the position of a whitespace character greater or equal than <code>position</code> separated only by whitespace, or -1 if none found
*/
private static int firstWhitespaceToRight(IDocument document, int position) {
int length= document.getLength();
Assert.isTrue(position >= 0);
Assert.isTrue(position <= length);
try {
while (position < length) {
char ch= document.getChar(position);
if (Character.isWhitespace(ch))
return position;
position++;
}
return position;
} catch (BadLocationException e) {
}
return -1;
}
/**
* Finds the highest position in <code>document</code> such that the position is <= <code>position</code>
* and > <code>bound</code> and <code>Character.isWhitespace(document.getChar(pos))</code> evaluates to <code>true</code>
* and the position is in the default partition.
*
* @param document the document being modified
* @param position the first character position in <code>document</code> to be considered
* @param partitioning the document partitioning
* @param bound the first position in <code>document</code> to not consider any more, with <code>bound</code> > <code>position</code>
* @return the highest position of one element in <code>chars</code> in [<code>position</code>, <code>scanTo</code>) that resides in a Java partition, or <code>-1</code> if none can be found
*/
private static int firstNonWhitespaceBackward(IDocument document, int position, String partitioning, int bound) {
Assert.isTrue(position < document.getLength());
Assert.isTrue(bound >= -1);
try {
while (position > bound) {
char ch= document.getChar(position);
if (!Character.isWhitespace(ch) && isDefaultPartition(document, position, partitioning))
return position;
position--;
}
} catch (BadLocationException e) {
}
return -1;
}
/**
* Finds the smallest position in <code>document</code> such that the position is >= <code>position</code>
* and < <code>bound</code> and <code>Character.isWhitespace(document.getChar(pos))</code> evaluates to <code>true</code>
* and the position is in the default partition.
*
* @param document the document being modified
* @param position the first character position in <code>document</code> to be considered
* @param partitioning the document partitioning
* @param bound the first position in <code>document</code> to not consider any more, with <code>bound</code> > <code>position</code>
* @return the smallest position of one element in <code>chars</code> in [<code>position</code>, <code>scanTo</code>) that resides in a Java partition, or <code>-1</code> if none can be found
*/
private static int firstNonWhitespaceForward(IDocument document, int position, String partitioning, int bound) {
Assert.isTrue(position >= 0);
Assert.isTrue(bound <= document.getLength());
try {
while (position < bound) {
char ch= document.getChar(position);
if (!Character.isWhitespace(ch) && isDefaultPartition(document, position, partitioning))
return position;
position++;
}
} catch (BadLocationException e) {
}
return -1;
}
/**
* Finds the highest position in <code>document</code> such that the position is <= <code>position</code>
* and > <code>bound</code> and <code>document.getChar(position) == ch</code> evaluates to <code>true</code> for at least one
* ch in <code>chars</code> and the position is in the default partition.
*
* @param document the document being modified
* @param position the first character position in <code>document</code> to be considered
* @param partitioning the document partitioning
* @param bound the first position in <code>document</code> to not consider any more, with <code>scanTo</code> > <code>position</code>
* @param chars an array of <code>char</code> to search for
* @return the highest position of one element in <code>chars</code> in (<code>bound</code>, <code>position</code>] that resides in a Java partition, or <code>-1</code> if none can be found
*/
private static int scanBackward(IDocument document, int position, String partitioning, int bound, char[] chars) {
Assert.isTrue(bound >= -1);
Assert.isTrue(position < document.getLength() );
Arrays.sort(chars);
try {
while (position > bound) {
if (Arrays.binarySearch(chars, document.getChar(position)) >= 0 && isDefaultPartition(document, position, partitioning))
return position;
position--;
}
} catch (BadLocationException e) {
}
return -1;
}
// /**
// * Finds the highest position in <code>document</code> such that the position is <= <code>position</code>
// * and > <code>bound</code> and <code>document.getChar(position) == ch</code> evaluates to <code>true</code>
// * and the position is in the default partition.
// *
// * @param document the document being modified
// * @param position the first character position in <code>document</code> to be considered
// * @param bound the first position in <code>document</code> to not consider any more, with <code>scanTo</code> > <code>position</code>
// * @param chars an array of <code>char</code> to search for
// * @return the highest position of one element in <code>chars</code> in [<code>position</code>, <code>scanTo</code>) that resides in a Java partition, or <code>-1</code> if none can be found
// */
// private static int scanBackward(IDocument document, int position, int bound, char ch) {
// return scanBackward(document, position, bound, new char[] {ch});
// }
//
/**
* Finds the lowest position in <code>document</code> such that the position is >= <code>position</code>
* and < <code>bound</code> and <code>document.getChar(position) == ch</code> evaluates to <code>true</code> for at least one
* ch in <code>chars</code> and the position is in the default partition.
*
* @param document the document being modified
* @param position the first character position in <code>document</code> to be considered
* @param partitioning the document partitioning
* @param bound the first position in <code>document</code> to not consider any more, with <code>scanTo</code> > <code>position</code>
* @param chars an array of <code>char</code> to search for
* @return the lowest position of one element in <code>chars</code> in [<code>position</code>, <code>bound</code>) that resides in a Java partition, or <code>-1</code> if none can be found
*/
private static int scanForward(IDocument document, int position, String partitioning, int bound, char[] chars) {
Assert.isTrue(position >= 0);
Assert.isTrue(bound <= document.getLength());
Arrays.sort(chars);
try {
while (position < bound) {
if (Arrays.binarySearch(chars, document.getChar(position)) >= 0 && isDefaultPartition(document, position, partitioning))
return position;
position++;
}
} catch (BadLocationException e) {
}
return -1;
}
/**
* Finds the lowest position in <code>document</code> such that the position is >= <code>position</code>
* and < <code>bound</code> and <code>document.getChar(position) == ch</code> evaluates to <code>true</code>
* and the position is in the default partition.
*
* @param document the document being modified
* @param position the first character position in <code>document</code> to be considered
* @param partitioning the document partitioning
* @param bound the first position in <code>document</code> to not consider any more, with <code>scanTo</code> > <code>position</code>
* @param chars an array of <code>char</code> to search for
* @return the lowest position of one element in <code>chars</code> in [<code>position</code>, <code>bound</code>) that resides in a Java partition, or <code>-1</code> if none can be found
*/
private static int scanForward(IDocument document, int position, String partitioning, int bound, char ch) {
return scanForward(document, position, partitioning, bound, new char[] {ch});
}
/**
* Checks whether the content of <code>document</code> in the range (<code>offset</code>, <code>length</code>)
* contains the <code>new</code> keyword.
*
* @param document the document being modified
* @param offset the first character position in <code>document</code> to be considered
* @param length the length of the character range to be considered
* @param partitioning the document partitioning
* @return <code>true</code> if the specified character range contains a <code>new</code> keyword, <code>false</code> otherwise.
*/
private static boolean isNewMatch(IDocument document, int offset, int length, String partitioning) {
Assert.isTrue(length >= 0);
Assert.isTrue(offset >= 0);
Assert.isTrue(offset + length < document.getLength() + 1);
try {
String text= document.get(offset, length);
int pos= text.indexOf("new"); //$NON-NLS-1$
while (pos != -1 && !isDefaultPartition(document, pos + offset, partitioning))
pos= text.indexOf("new", pos + 2); //$NON-NLS-1$
if (pos < 0)
return false;
if (pos != 0 && Character.isJavaIdentifierPart(document.getChar(pos - 1)))
return false;
if (pos + 3 < length && Character.isJavaIdentifierPart(document.getChar(pos + 3)))
return false;
return true;
} catch (BadLocationException e) {
}
return false;
}
/**
* Checks whether the content of <code>document</code> at <code>position</code> looks like an
* anonymous class definition. <code>position</code> must be to the left of the opening
* parenthesis of the definition's parameter list.
*
* @param document the document being modified
* @param position the first character position in <code>document</code> to be considered
* @param partitioning the document partitioning
* @return <code>true</code> if the content of <code>document</code> looks like an anonymous class definition, <code>false</code> otherwise
*/
private static boolean looksLikeAnonymousClassDef(IDocument document, int position, String partitioning) {
int previousCommaOrParen= scanBackward(document, position - 1, partitioning, -1, new char[] {',', '('});
if (previousCommaOrParen == -1 || position < previousCommaOrParen + 5) // 2 for borders, 3 for "new"
return false;
if (isNewMatch(document, previousCommaOrParen + 1, position - previousCommaOrParen - 2, partitioning))
return true;
return false;
}
/**
* Checks whether <code>position</code> resides in a default (Java) partition of <code>document</code>.
*
* @param document the document being modified
* @param position the position to be checked
* @param partitioning the document partitioning
* @return <code>true</code> if <code>position</code> is in the default partition of <code>document</code>, <code>false</code> otherwise
*/
private static boolean isDefaultPartition(IDocument document, int position, String partitioning) {
Assert.isTrue(position >= 0);
Assert.isTrue(position <= document.getLength());
try {
ITypedRegion region= TextUtilities.getPartition(document, partitioning, position);
return region != null && region.getType().equals(IDocument.DEFAULT_CONTENT_TYPE);
} catch (BadLocationException e) {
}
return false;
}
/**
* Finds the position of the parenthesis matching the closing parenthesis at <code>position</code>.
*
* @param document the document being modified
* @param position the position in <code>document</code> of a closing parenthesis
* @param partitioning the document partitioning
* @return the position in <code>document</code> of the matching parenthesis, or -1 if none can be found
*/
private static int findOpeningParenMatch(IDocument document, int position, String partitioning) {
final char CLOSING_PAREN= ')';
final char OPENING_PAREN= '(';
Assert.isTrue(position < document.getLength());
Assert.isTrue(position >= 0);
Assert.isTrue(isDefaultPartition(document, position, partitioning));
try {
Assert.isTrue(document.getChar(position) == CLOSING_PAREN);
int depth= 1;
while (true) {
position= scanBackward(document, position - 1, partitioning, -1, new char[] {CLOSING_PAREN, OPENING_PAREN});
if (position == -1)
return -1;
if (document.getChar(position) == CLOSING_PAREN)
depth++;
else
depth--;
if (depth == 0)
return position;
}
} catch (BadLocationException e) {
return -1;
}
}
/**
* Checks whether, to the left of <code>position</code> and separated only by whitespace,
* <code>document</code> contains a keyword taking a parameter list and a block after it.
* These are: <code>if</code>, <code>while</code>, <code>catch</code>, <code>for</code>, <code>synchronized</code>.
*
* @param document the document being modified
* @param position the first character position in <code>document</code> to be considered
* @param partitioning the document partitioning
* @return <code>true</code> if <code>document</code> contains any of the above keywords to the left of <code>position</code>, <code>false</code> otherwise
*/
private static boolean looksLikeIfWhileForCatch(IDocument document, int position, String partitioning) {
position= firstNonWhitespaceBackward(document, position, partitioning, -1);
if (position == -1)
return false;
return looksLike(document, position, "if") //$NON-NLS-1$
|| looksLike(document, position, "while") //$NON-NLS-1$
|| looksLike(document, position, "catch") //$NON-NLS-1$
|| looksLike(document, position, "synchronized") //$NON-NLS-1$
|| looksLike(document, position, "for"); //$NON-NLS-1$
}
/**
* Checks whether code>document</code> contains the <code>String</code> <code>like</code> such
* that its last character is at <code>position</code>. If <code>like</code> starts with a
* identifier part (as determined by {@link Character.isJavaIdentifier(char)}), it is also made
* sure that <code>like</code> is preceded by some non-identifier character or stands at the
* document start.
*
* @param document the document being modified
* @param position the first character position in <code>document</code> to be considered
* @param like the <code>String</code> to look for.
* @return <code>true</code> if <code>document</code> contains <code>like</code> such that it ends at <code>position</code>, <code>false</code> otherwise
*/
private static boolean looksLike(IDocument document, int position, String like) {
int length= like.length();
if (position < length - 1)
return false;
try {
if (!like.equals(document.get(position - length + 1, length)))
return false;
if (position >= length && Character.isJavaIdentifierPart(like.charAt(0)) && Character.isJavaIdentifierPart(document.getChar(position - length)))
return false;
} catch (BadLocationException e) {
return false;
}
return true;
}
/**
* Checks whether the content of <code>document</code> at <code>position</code> looks like a
* method declaration header (i.e. only the return type and method name). <code>position</code>
* must be just left of the opening parenthesis of the parameter list.
*
* @param document the document being modified
* @param position the first character position in <code>document</code> to be considered
* @param partitioning the document partitioning
* @return <code>true</code> if the content of <code>document</code> looks like a method definition, <code>false</code> otherwise
*/
private static boolean looksLikeMethodDecl(IDocument document, int position, String partitioning) {
// method name
position= eatIdentToLeft(document, position, partitioning);
if (position < 1)
return false;
position= eatBrackets(document, position - 1, partitioning);
if (position < 1)
return false;
position= eatIdentToLeft(document, position - 1, partitioning);
return position != -1;
}
/**
* From <code>position</code> to the left, eats any whitespace and then a pair of brackets
* as used to declare an array return type like <pre>String [ ]</pre>.
* The return value is either the position of the opening bracket or <code>position</code> if no
* pair of brackets can be parsed.
*
* @param document the document being modified
* @param position the first character position in <code>document</code> to be considered
* @param partitioning the document partitioning
* @return the smallest character position of bracket pair or <code>position</code>
*/
private static int eatBrackets(IDocument document, int position, String partitioning) {
// accept array return type
int pos= firstNonWhitespaceBackward(document, position, partitioning, -1);
try {
if (pos > 1 && document.getChar(pos) == ']') {
pos= firstNonWhitespaceBackward(document, pos - 1, partitioning, -1);
if (pos > 0 && document.getChar(pos) == '[')
return pos;
}
} catch (BadLocationException e) {
// won't happen
}
return position;
}
/**
* From <code>position</code> to the left, eats any whitespace and the first identifier, returning
* the position of the first identifier character (in normal read order).
* <p>When called on a document with content <code>" some string "</code> and positionition 13, the
* return value will be 6 (the first letter in <code>string</code>).
* </p>
*
* @param document the document being modified
* @param position the first character position in <code>document</code> to be considered
* @param partitioning the document partitioning
* @return the smallest character position of an identifier or -1 if none can be found; always <= <code>position</code>
*/
private static int eatIdentToLeft(IDocument document, int position, String partitioning) {
if (position < 0)
return -1;
Assert.isTrue(position < document.getLength());
int p= firstNonWhitespaceBackward(document, position, partitioning, -1);
if (p == -1)
return -1;
try {
while (p >= 0) {
char ch= document.getChar(p);
if (Character.isJavaIdentifierPart(ch)) {
p--;
continue;
}
// length must be > 0
if (Character.isWhitespace(ch) && p != position)
return p + 1;
else
return -1;
}
// start of document reached
return 0;
} catch (BadLocationException e) {
}
return -1;
}
/**
* Returns a position int the first java partition after the last non-empty and non-comment partition.
* There is no non-whitespace from the returned position to the end of the partition it is contained in.
*
* @param document the document being modified
* @param line the line under investigation
* @param offset the caret offset into <code>line</code>
* @param partitioning the document partitioning
* @return the position of the next Java partition, or the end of <code>line</code>
*/
private static int nextPartitionOrLineEnd(IDocument document, ITextSelection line, int offset, String partitioning) {
// run relative to document
final int docOffset= offset + line.getOffset();
final int eol= line.getOffset() + line.getLength();
int nextPartitionPos= eol; // init with line end
int validPosition= docOffset;
try {
ITypedRegion partition= TextUtilities.getPartition(document, partitioning, nextPartitionPos);
validPosition= getValidPositionForPartition(document, partition, eol);
while (validPosition == -1) {
nextPartitionPos= partition.getOffset() - 1;
if (nextPartitionPos <= docOffset) {
validPosition= docOffset;
break;
}
partition= TextUtilities.getPartition(document, partitioning, nextPartitionPos);
validPosition= getValidPositionForPartition(document, partition, eol);
}
} catch (BadLocationException e) {
}
validPosition= Math.max(validPosition, docOffset);
// make relative to line
validPosition -= line.getOffset();
return validPosition;
}
/**
* Returns a valid insert location (except for whitespace) in <code>partition</code> or -1 if
* there is no valid insert location.
* An valid insert location is right after any java string or character partition, or at the end
* of a java default partition, but never behind <code>maxOffset</code>. Comment partitions or
* empty java partitions do never yield valid insert positions.
*
* @param doc the document being modified
* @param partition the current partition
* @param maxOffset the maximum offset to consider
* @return a valid insert location in <code>partition</code>, or -1 if there is no valid insert location
*/
private static int getValidPositionForPartition(IDocument doc, ITypedRegion partition, int maxOffset) {
final int INVALID= -1;
if (IJavaPartitions.JAVA_DOC.equals(partition.getType()))
return INVALID;
if (IJavaPartitions.JAVA_MULTI_LINE_COMMENT.equals(partition.getType()))
return INVALID;
if (IJavaPartitions.JAVA_SINGLE_LINE_COMMENT.equals(partition.getType()))
return INVALID;
int endOffset= Math.min(maxOffset, partition.getOffset() + partition.getLength());
if (IJavaPartitions.JAVA_CHARACTER.equals(partition.getType()))
return endOffset;
if (IJavaPartitions.JAVA_STRING.equals(partition.getType()))
return endOffset;
if (IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType())) {
try {
if (doc.get(partition.getOffset(), endOffset - partition.getOffset()).trim().length() == 0)
return INVALID;
else
return endOffset;
} catch (BadLocationException e) {
return INVALID;
}
}
// default: we don't know anything about the partition - assume valid
return endOffset;
}
/**
* Determines whether the current line contains a for statement.
* Algorithm: any "for" word in the line is a positive, "for" contained in a string literal will
* produce a false positive.
*
* @param line the line where the change is being made
* @param offset the position of the caret
* @return <code>true</code> if <code>line</code> contains <code>for</code>, <code>false</code> otherwise
*/
private static boolean isForStatement(String line, int offset) {
/* searching for (^|\s)for(\s|$) */
int forPos= line.indexOf("for"); //$NON-NLS-1$
if (forPos != -1) {
if ((forPos == 0 || !Character.isJavaIdentifierPart(line.charAt(forPos - 1))) && (line.length() == forPos + 3 || !Character.isJavaIdentifierPart(line.charAt(forPos + 3))))
return true;
}
return false;
}
/**
* Returns the position in <code>text</code> after which there comes only whitespace, up to
* <code>offset</code>.
*
* @param text the text being searched
* @param offset the maximum offset to search for
* @return the smallest value <code>v</code> such that <code>text.substring(v, offset).trim() == 0</code>
*/
private static int startOfWhitespaceBeforeOffset(String text, int offset) {
int i= Math.min(offset, text.length());
for (; i >= 1; i--) {
if (!Character.isWhitespace(text.charAt(i - 1)))
break;
}
return i;
}
}
|
41,598 |
Bug 41598 NPE in TypedPosition on commenting
|
20030813+0815 export select a sequence of lines and press ctrl+/ java.fullversion=J2RE 1.3.1 IBM J9 build 20030605 (JIT enabled) BootLoader constants: OS=win32, ARCH=x86, WS=win32, NL=en_US Command-line arguments: -os win32 -ws win32 -arch x86 -data d:\eclipseWorkbench7 \plugins -showlocation -install file:D:/eclipse20030813/eclipse/ !ENTRY org.eclipse.ui 4 4 Aug 15, 2003 11:43:32.739 !MESSAGE Unhandled exception caught in event loop. !ENTRY org.eclipse.ui 4 0 Aug 15, 2003 11:43:32.759 !MESSAGE java.lang.NullPointerException !STACK 0 java.lang.NullPointerException at java.lang.Throwable.<init>(Throwable.java) at java.lang.Throwable.<init>(Throwable.java) at java.lang.NullPointerException.<init>(NullPointerException.java:63) at org.eclipse.jface.text.TypedPosition.<init>(TypedPosition.java:41) at org.eclipse.jface.text.presentation.PresentationReconciler$InternalListener.docu mentAboutToBeChanged(PresentationReconciler.java:153) at org.eclipse.jface.text.AbstractDocument.fireDocumentAboutToBeChanged (AbstractDocument.java:549) at org.eclipse.jface.text.AbstractDocument.replace (AbstractDocument.java:956) at org.eclipse.jdt.internal.ui.javaeditor.PartiallySynchronizedDocument.replace (PartiallySynchronizedDocument.java:61) at org.eclipse.jface.text.TextViewer.shiftRight(TextViewer.java:3594) at org.eclipse.jface.text.TextViewer.shift(TextViewer.java:3546) at org.eclipse.jface.text.TextViewer.doOperation(TextViewer.java:3279) at org.eclipse.jface.text.source.SourceViewer.doOperation (SourceViewer.java:507) at org.eclipse.jdt.internal.ui.javaeditor.JavaSourceViewer.doOperation (JavaSourceViewer.java:72) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor$AdaptedSourceViewer .doOperation(CompilationUnitEditor.java:164) at org.eclipse.ui.texteditor.TextOperationAction$1.run (TextOperationAction.java:127) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java) at org.eclipse.ui.texteditor.TextOperationAction.run (TextOperationAction.java:125) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.ui.actions.RetargetAction.runWithEvent (RetargetAction.java:203) at org.eclipse.ui.internal.WWinPluginAction.runWithEvent (WWinPluginAction.java:212) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:542) at org.eclipse.jface.action.ActionContributionItem.access$4 (ActionContributionItem.java:496) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent (ActionContributionItem.java:468) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1676) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1659) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at java.lang.reflect.AccessibleObject.invokeL(AccessibleObject.java:207) at java.lang.reflect.Method.invoke(Method.java:271) at org.eclipse.core.launcher.Main.basicRun(Main.java:291) at org.eclipse.core.launcher.Main.run(Main.java:747) at org.eclipse.core.launcher.Main.main(Main.java:583)
|
resolved fixed
|
e6789e1
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-15T15:45:35Z | 2003-08-15T09:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/javadoc/JavaDocAutoIndentStrategy.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text.javadoc;
import java.text.BreakIterator;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DefaultAutoIndentStrategy;
import org.eclipse.jface.text.DocumentCommand;
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.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.texteditor.ITextEditorExtension3;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.CodeGeneration;
import org.eclipse.jdt.ui.IWorkingCopyManager;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.corext.util.CodeFormatterUtil;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.corext.util.Strings;
import org.eclipse.jdt.internal.corext.util.SuperTypeHierarchyCache;
import org.eclipse.jdt.internal.ui.JavaPlugin;
/**
* Auto indent strategy for java doc comments
*/
public class JavaDocAutoIndentStrategy extends DefaultAutoIndentStrategy {
private String fPartitioning;
/**
* Creates a new Javadoc auto indent strategy for the given document partitioning.
*
* @param partitioning the document partitioning
*/
public JavaDocAutoIndentStrategy(String partitioning) {
fPartitioning= partitioning;
}
private static String getLineDelimiter(IDocument document) {
try {
if (document.getNumberOfLines() > 1)
return document.getLineDelimiter(0);
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
return System.getProperty("line.separator"); //$NON-NLS-1$
}
/**
* Copies the indentation of the previous line and add a star.
* If the javadoc just started on this line add standard method tags
* and close the javadoc.
*
* @param d the document to work on
* @param c the command to deal with
*/
private void jdocIndentAfterNewLine(IDocument d, DocumentCommand c) {
if (c.offset == -1 || d.getLength() == 0)
return;
try {
// find start of line
int p= (c.offset == d.getLength() ? c.offset - 1 : c.offset);
IRegion info= d.getLineInformationOfOffset(p);
int start= info.getOffset();
// find white spaces
int end= findEndOfWhiteSpace(d, start, c.offset);
StringBuffer buf= new StringBuffer(c.text);
if (end >= start) { // 1GEYL1R: ITPJUI:ALL - java doc edit smartness not work for class comments
// append to input
String indentation= jdocExtractLinePrefix(d, d.getLineOfOffset(c.offset));
buf.append(indentation);
if (end < c.offset) {
if (d.getChar(end) == '/') {
// javadoc started on this line
buf.append(" * "); //$NON-NLS-1$
if (JavaPlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_CLOSE_JAVADOCS) && isNewComment(d, c.offset, fPartitioning)) {
String lineDelimiter= getLineDelimiter(d);
c.doit= false;
d.replace(c.offset, 0, lineDelimiter + indentation + " */"); //$NON-NLS-1$
// evaluate method signature
ICompilationUnit unit= getCompilationUnit();
if (JavaPlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS) &&
unit != null)
{
try {
unit.reconcile();
String string= createJavaDocTags(d, c, indentation, lineDelimiter, unit);
if (string != null)
d.replace(c.offset, 0, string);
} catch (CoreException e) {
// ignore
}
}
}
}
}
}
c.text= buf.toString();
} catch (BadLocationException excp) {
// stop work
}
}
private String createJavaDocTags(IDocument document, DocumentCommand command, String indentation, String lineDelimiter, ICompilationUnit unit)
throws CoreException, BadLocationException
{
IJavaElement element= unit.getElementAt(command.offset);
if (element == null)
return null;
switch (element.getElementType()) {
case IJavaElement.TYPE:
return createTypeTags(document, command, indentation, lineDelimiter, (IType) element);
case IJavaElement.METHOD:
return createMethodTags(document, command, indentation, lineDelimiter, (IMethod) element);
default:
return null;
}
}
/*
* Removes start and end of a comment and corrects indentation and line delimiters.
*/
private String prepareTemplateComment(String comment, String indentation, String lineDelimiter) {
// trim comment start and end if any
if (comment.endsWith("*/")) //$NON-NLS-1$
comment= comment.substring(0, comment.length() - 2);
comment= comment.trim();
if (comment.startsWith("/*")) { //$NON-NLS-1$
if (comment.length() > 2 && comment.charAt(2) == '*') {
comment= comment.substring(3); // remove '/**'
} else {
comment= comment.substring(2); // remove '/*'
}
}
return Strings.changeIndent(comment, 0, CodeFormatterUtil.getTabWidth(), indentation, lineDelimiter);
}
private String createTypeTags(IDocument document, DocumentCommand command, String indentation, String lineDelimiter, IType type)
throws CoreException
{
String comment= CodeGeneration.getTypeComment(type.getCompilationUnit(), type.getTypeQualifiedName('.'), lineDelimiter);
if (comment != null) {
return prepareTemplateComment(comment.trim(), indentation, lineDelimiter);
}
return null;
}
private String createMethodTags(IDocument document, DocumentCommand command, String indentation, String lineDelimiter, IMethod method)
throws CoreException, BadLocationException
{
IRegion partition= TextUtilities.getPartition(document, fPartitioning, command.offset);
ISourceRange sourceRange= method.getSourceRange();
if (sourceRange == null || sourceRange.getOffset() != partition.getOffset())
return null;
IMethod inheritedMethod= getInheritedMethod(method);
String comment= CodeGeneration.getMethodComment(method, inheritedMethod, lineDelimiter);
if (comment != null) {
comment= comment.trim();
boolean javadocComment= comment.startsWith("/**"); //$NON-NLS-1$
boolean isJavaDoc= partition.getLength() >= 3 && document.get(partition.getOffset(), 3).equals("/**"); //$NON-NLS-1$
if (javadocComment == isJavaDoc) {
return prepareTemplateComment(comment, indentation, lineDelimiter);
}
}
return null;
}
/**
* Returns the method inherited from, <code>null</code> if method is newly defined.
*/
private static IMethod getInheritedMethod(IMethod method) throws JavaModelException {
IType declaringType= method.getDeclaringType();
ITypeHierarchy typeHierarchy= SuperTypeHierarchyCache.getTypeHierarchy(declaringType);
return JavaModelUtil.findMethodDeclarationInHierarchy(typeHierarchy, declaringType,
method.getElementName(), method.getParameterTypes(), method.isConstructor());
}
protected void jdocIndentForCommentEnd(IDocument d, DocumentCommand c) {
if (c.offset < 2 || d.getLength() == 0) {
return;
}
try {
if ("* ".equals(d.get(c.offset - 2, 2))) { //$NON-NLS-1$
// modify document command
c.length++;
c.offset--;
}
} catch (BadLocationException excp) {
// stop work
}
}
/**
* Guesses if the command operates within a newly created javadoc comment or not.
* If in doubt, it will assume that the javadoc is new.
*/
private static boolean isNewComment(IDocument document, int commandOffset, String partitioning) {
try {
int lineIndex= document.getLineOfOffset(commandOffset) + 1;
if (lineIndex >= document.getNumberOfLines())
return true;
IRegion line= document.getLineInformation(lineIndex);
ITypedRegion partition= TextUtilities.getPartition(document, partitioning, commandOffset);
if (document.getLineOffset(lineIndex) >= partition.getOffset() + partition.getLength())
return false;
String string= document.get(line.getOffset(), line.getLength());
if (!string.trim().startsWith("*")) //$NON-NLS-1$
return true;
return false;
} catch (BadLocationException e) {
return false;
}
}
private boolean isSmartMode() {
IWorkbenchPage page= JavaPlugin.getActivePage();
if (page != null) {
IEditorPart part= page.getActiveEditor();
if (part instanceof ITextEditorExtension3) {
ITextEditorExtension3 extension= (ITextEditorExtension3) part;
return extension.getInsertMode() == ITextEditorExtension3.SMART_INSERT;
}
}
return false;
}
/*
* @see IAutoIndentStrategy#customizeDocumentCommand
*/
public void customizeDocumentCommand(IDocument document, DocumentCommand command) {
if (!isSmartMode())
return;
try {
if (command.text != null && command.length == 0) {
String[] lineDelimiters= document.getLegalLineDelimiters();
int index= TextUtilities.endsWith(lineDelimiters, command.text);
if (index > -1) {
// ends with line delimiter
if (lineDelimiters[index].equals(command.text))
// just the line delimiter
jdocIndentAfterNewLine(document, command);
return;
}
}
if (command.text != null && command.text.equals("/")) { //$NON-NLS-1$
jdocIndentForCommentEnd(document, command);
return;
}
ITypedRegion partition= TextUtilities.getPartition(document, fPartitioning, command.offset);
int partitionStart= partition.getOffset();
int partitionEnd= partition.getLength() + partitionStart;
String text= command.text;
int offset= command.offset;
int length= command.length;
// partition change
final int PREFIX_LENGTH= "/*".length(); //$NON-NLS-1$
final int POSTFIX_LENGTH= "*/".length(); //$NON-NLS-1$
if ((offset < partitionStart + PREFIX_LENGTH || offset + length > partitionEnd - POSTFIX_LENGTH) ||
text != null && text.length() >= 2 && ((text.indexOf("*/") != -1) || (document.getChar(offset) == '*' && text.startsWith("/")))) //$NON-NLS-1$ //$NON-NLS-2$
return;
if (command.text == null || command.text.length() == 0)
jdocHandleBackspaceDelete(document, command);
else if (command.text != null && command.length == 0 && command.text.length() > 0)
jdocWrapParagraphOnInsert(document, command);
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
}
private void flushCommand(IDocument document, DocumentCommand command) throws BadLocationException {
if (!command.doit)
return;
document.replace(command.offset, command.length, command.text);
command.doit= false;
if (command.text != null)
command.offset += command.text.length();
command.length= 0;
command.text= null;
}
protected void jdocWrapParagraphOnInsert(IDocument document, DocumentCommand command) throws BadLocationException {
// Assert.isTrue(command.length == 0);
// Assert.isTrue(command.text != null && command.text.length() == 1);
if (!getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_FORMAT_JAVADOCS))
return;
int line= document.getLineOfOffset(command.offset);
IRegion region= document.getLineInformation(line);
int lineOffset= region.getOffset();
int lineLength= region.getLength();
String lineContents= document.get(lineOffset, lineLength);
StringBuffer buffer= new StringBuffer(lineContents);
int start= command.offset - lineOffset;
int end= command.length + start;
buffer.replace(start, end, command.text);
// handle whitespace
if (command.text != null && command.text.length() != 0 && command.text.trim().length() == 0) {
String endOfLine= document.get(command.offset, lineOffset + lineLength - command.offset);
// end of line
if (endOfLine.length() == 0) {
// move caret to next line
flushCommand(document, command);
if (isLineTooShort(document, line)) {
int[] caretOffset= {command.offset};
jdocWrapParagraphFromLine(document, line, caretOffset, false);
command.offset= caretOffset[0];
return;
}
// move caret to next line if possible
if (line < document.getNumberOfLines() - 1 && isJavaDocLine(document, line + 1)) {
String lineDelimiter= document.getLineDelimiter(line);
String nextLinePrefix= jdocExtractLinePrefix(document, line + 1);
command.offset += lineDelimiter.length() + nextLinePrefix.length();
}
return;
// inside whitespace at end of line
} else if (endOfLine.trim().length() == 0) {
// simply insert space
return;
}
}
// change in prefix region
String prefix= jdocExtractLinePrefix(document, line);
boolean wrapAlways= command.offset >= lineOffset && command.offset <= lineOffset + prefix.length();
// must insert the text now because it may include whitepace
flushCommand(document, command);
if (wrapAlways || calculateDisplayedWidth(buffer.toString()) > getMargin() || isLineTooShort(document, line)) {
int[] caretOffset= {command.offset};
jdocWrapParagraphFromLine(document, line, caretOffset, wrapAlways);
if (!wrapAlways)
command.offset= caretOffset[0];
}
}
/**
* Method jdocWrapParagraphFromLine.
*
* @param document
* @param line
* @param always
*/
private void jdocWrapParagraphFromLine(IDocument document, int line, int[] caretOffset, boolean always) throws BadLocationException {
String indent= jdocExtractLinePrefix(document, line);
if (!always) {
if (!indent.trim().startsWith("*")) //$NON-NLS-1$
return;
if (indent.trim().startsWith("*/")) //$NON-NLS-1$
return;
if (!isLineTooLong(document, line) && !isLineTooShort(document, line))
return;
}
boolean caretRelativeToParagraphOffset= false;
int caret= caretOffset[0];
int caretLine= document.getLineOfOffset(caret);
int lineOffset= document.getLineOffset(line);
int paragraphOffset= lineOffset + indent.length();
if (paragraphOffset < caret) {
caret -= paragraphOffset;
caretRelativeToParagraphOffset= true;
} else {
caret -= lineOffset;
}
StringBuffer buffer= new StringBuffer();
int currentLine= line;
while (line == currentLine || isJavaDocLine(document, currentLine)) {
if (buffer.length() != 0 && !Character.isWhitespace(buffer.charAt(buffer.length() - 1))) {
buffer.append(' ');
if (currentLine <= caretLine) {
// in this case caretRelativeToParagraphOffset is always true
++caret;
}
}
String string= getLineContents(document, currentLine);
buffer.append(string);
currentLine++;
}
String paragraph= buffer.toString();
if (paragraph.trim().length() == 0)
return;
caretOffset[0]= caretRelativeToParagraphOffset ? caret : 0;
String delimiter= document.getLineDelimiter(0);
String wrapped= formatParagraph(paragraph, caretOffset, indent, delimiter, getMargin());
int beginning= document.getLineOffset(line);
int end= document.getLineOffset(currentLine);
document.replace(beginning, end - beginning, wrapped.toString());
caretOffset[0]= caretRelativeToParagraphOffset ? caretOffset[0] + beginning : caret + beginning;
}
/**
* Line break iterator to handle whitespaces as first class citizens.
*/
private static class LineBreakIterator {
private final String fString;
private final BreakIterator fIterator= BreakIterator.getLineInstance();
private int fStart;
private int fEnd;
private int fBufferedEnd;
public LineBreakIterator(String string) {
fString= string;
fIterator.setText(string);
}
public int first() {
fBufferedEnd= -1;
fStart= fIterator.first();
return fStart;
}
public int next() {
if (fBufferedEnd != -1) {
fStart= fEnd;
fEnd= fBufferedEnd;
fBufferedEnd= -1;
return fEnd;
}
fStart= fEnd;
fEnd= fIterator.next();
if (fEnd == BreakIterator.DONE)
return fEnd;
final String string= fString.substring(fStart, fEnd);
// whitespace
if (string.trim().length() == 0)
return fEnd;
final String word= string.trim();
if (word.length() == string.length())
return fEnd;
// suspected whitespace
fBufferedEnd= fEnd;
return fStart + word.length();
}
}
/**
* Formats a paragraph, using break iterator.
*
* @param offset an offset within the paragraph, which will be updated with respect to formatting.
*/
private static String formatParagraph(String paragraph, int[] offset, String prefix, String lineDelimiter, int margin) {
LineBreakIterator iterator= new LineBreakIterator(paragraph);
StringBuffer paragraphBuffer= new StringBuffer();
StringBuffer lineBuffer= new StringBuffer();
StringBuffer whiteSpaceBuffer= new StringBuffer();
int index= offset[0];
int indexBuffer= -1;
// line delimiter could be null
if (lineDelimiter == null)
lineDelimiter= ""; //$NON-NLS-1$
for (int start= iterator.first(), end= iterator.next(); end != BreakIterator.DONE; start= end, end= iterator.next()) {
String word= paragraph.substring(start, end);
// word is whitespace
if (word.trim().length() == 0) {
whiteSpaceBuffer.append(word);
// first word of line is always appended
} else if (lineBuffer.length() == 0) {
lineBuffer.append(prefix);
lineBuffer.append(whiteSpaceBuffer.toString());
lineBuffer.append(word);
} else {
String line= lineBuffer.toString() + whiteSpaceBuffer.toString() + word.toString();
// margin exceeded
if (calculateDisplayedWidth(line) > margin) {
// flush line buffer and wrap paragraph
paragraphBuffer.append(lineBuffer.toString());
paragraphBuffer.append(lineDelimiter);
lineBuffer.setLength(0);
lineBuffer.append(prefix);
lineBuffer.append(word);
// flush index buffer
if (indexBuffer != -1) {
offset[0]= indexBuffer;
// correct for caret in whitespace at the end of line
if (whiteSpaceBuffer.length() != 0 && index < start && index >= start - whiteSpaceBuffer.length())
offset[0] -= (index - (start - whiteSpaceBuffer.length()));
indexBuffer= -1;
}
whiteSpaceBuffer.setLength(0);
// margin not exceeded
} else {
lineBuffer.append(whiteSpaceBuffer.toString());
lineBuffer.append(word);
whiteSpaceBuffer.setLength(0);
}
}
if (index >= start && index < end) {
indexBuffer= paragraphBuffer.length() + lineBuffer.length() + (index - start);
if (word.trim().length() != 0)
indexBuffer -= word.length();
}
}
// flush line buffer
paragraphBuffer.append(lineBuffer.toString());
paragraphBuffer.append(lineDelimiter);
// flush index buffer
if (indexBuffer != -1)
offset[0]= indexBuffer;
// last position is not returned by break iterator
else if (offset[0] == paragraph.length())
offset[0]= paragraphBuffer.length() - lineDelimiter.length();
return paragraphBuffer.toString();
}
private static IPreferenceStore getPreferenceStore() {
return JavaPlugin.getDefault().getPreferenceStore();
}
/**
* Returns the displayed width of a string, taking in account the displayed tab width.
* The result can be compared against the print margin.
*/
private static int calculateDisplayedWidth(String string) {
final int tabWidth= getPreferenceStore().getInt(PreferenceConstants.EDITOR_TAB_WIDTH);
int column= 0;
for (int i= 0; i < string.length(); i++)
if ('\t' == string.charAt(i))
column += tabWidth - (column % tabWidth);
else
column++;
return column;
}
private String jdocExtractLinePrefix(IDocument d, int line) throws BadLocationException {
IRegion region= d.getLineInformation(line);
int lineOffset= region.getOffset();
int index= findEndOfWhiteSpace(d, lineOffset, lineOffset + d.getLineLength(line));
if (d.getChar(index) == '*') {
index++;
if (index != lineOffset + region.getLength() &&d.getChar(index) == ' ')
index++;
}
return d.get(lineOffset, index - lineOffset);
}
private String getLineContents(IDocument d, int line) throws BadLocationException {
int offset = d.getLineOffset(line);
int length = d.getLineLength(line);
String lineDelimiter= d.getLineDelimiter(line);
if (lineDelimiter != null)
length= length - lineDelimiter.length();
String lineContents = d.get(offset, length);
int trim = jdocExtractLinePrefix(d, line).length();
return lineContents.substring(trim);
}
private static String getLine(IDocument document, int line) throws BadLocationException {
IRegion region= document.getLineInformation(line);
return document.get(region.getOffset(), region.getLength());
}
/**
* Returns <code>true</code> if the javadoc line is too short, <code>false</code> otherwise.
*/
private boolean isLineTooShort(IDocument document, int line) throws BadLocationException {
if (!isJavaDocLine(document, line + 1))
return false;
String nextLine= getLineContents(document, line + 1);
if (nextLine.trim().length() == 0)
return false;
return true;
}
/**
* Returns <code>true</code> if the line is too long, <code>false</code> otherwise.
*/
private boolean isLineTooLong(IDocument document, int line) throws BadLocationException {
String lineContents= getLine(document, line);
return calculateDisplayedWidth(lineContents) > getMargin();
}
private static int getMargin() {
return getPreferenceStore().getInt(PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN);
}
private static final String[] fgInlineTags= {
"<b>", "<i>", "<em>", "<strong>", "<code>" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
};
private boolean isInlineTag(String string) {
for (int i= 0; i < fgInlineTags.length; i++)
if (string.startsWith(fgInlineTags[i]))
return true;
return false;
}
/**
* returns true if the specified line is part of a paragraph and should be merged with
* the previous line.
*/
private boolean isJavaDocLine(IDocument document, int line) throws BadLocationException {
if (document.getNumberOfLines() < line)
return false;
int offset= document.getLineOffset(line);
int length= document.getLineLength(line);
int firstChar= findEndOfWhiteSpace(document, offset, offset + length);
length -= firstChar - offset;
String lineContents= document.get(firstChar, length);
String prefix= lineContents.trim();
if (!prefix.startsWith("*") || prefix.startsWith("*/")) //$NON-NLS-1$ //$NON-NLS-2$
return false;
lineContents= lineContents.substring(1).trim().toLowerCase();
// preserve empty lines
if (lineContents.length() == 0)
return false;
// preserve @TAGS
if (lineContents.startsWith("@")) //$NON-NLS-1$
return false;
// preserve HTML tags which are not inline
if (lineContents.startsWith("<") && !isInlineTag(lineContents)) //$NON-NLS-1$
return false;
return true;
}
protected void jdocHandleBackspaceDelete(IDocument document, DocumentCommand c) {
if (!getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_FORMAT_JAVADOCS))
return;
try {
String text= document.get(c.offset, c.length);
int line= document.getLineOfOffset(c.offset);
int lineOffset= document.getLineOffset(line);
// erase line delimiter
String lineDelimiter= document.getLineDelimiter(line);
if (lineDelimiter != null && lineDelimiter.equals(text)) {
String prefix= jdocExtractLinePrefix(document, line + 1);
// strip prefix if any
if (prefix.length() > 0) {
int length= document.getLineDelimiter(line).length() + prefix.length();
document.replace(c.offset, length, null);
c.doit= false;
c.length= 0;
return;
}
// backspace: beginning of a javadoc line
} else if (document.getChar(c.offset - 1) == '*' && jdocExtractLinePrefix(document, line).length() - 1 >= c.offset - lineOffset) {
lineDelimiter= document.getLineDelimiter(line - 1);
String prefix= jdocExtractLinePrefix(document, line);
int length= (lineDelimiter != null ? lineDelimiter.length() : 0) + prefix.length();
document.replace(c.offset - length + 1, length, null);
c.doit= false;
c.offset -= length - 1;
c.length= 0;
return;
} else {
document.replace(c.offset, c.length, null);
c.doit= false;
c.length= 0;
}
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
try {
int line= document.getLineOfOffset(c.offset);
int lineOffset= document.getLineOffset(line);
String prefix= jdocExtractLinePrefix(document, line);
boolean always= c.offset > lineOffset && c.offset <= lineOffset + prefix.length();
int[] caretOffset= {c.offset};
jdocWrapParagraphFromLine(document, document.getLineOfOffset(c.offset), caretOffset, always);
c.offset= caretOffset[0];
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
}
/**
* Returns the compilation unit of the CompilationUnitEditor invoking the AutoIndentStrategy,
* might return <code>null</code> on error.
*/
private static ICompilationUnit getCompilationUnit() {
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;
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
ICompilationUnit unit= manager.getWorkingCopy(editor.getEditorInput());
if (unit == null)
return null;
return unit;
}
}
|
41,530 |
Bug 41530 move instance method: moving a method with local type creates syntax errors [refactoring]
| null |
resolved fixed
|
dc28bae
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-15T16:19:59Z | 2003-08-14T11:20:00Z |
org.eclipse.jdt.ui.tests.refactoring/test
| |
41,530 |
Bug 41530 move instance method: moving a method with local type creates syntax errors [refactoring]
| null |
resolved fixed
|
dc28bae
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-15T16:19:59Z | 2003-08-14T11:20:00Z |
cases/org/eclipse/jdt/ui/tests/refactoring/MoveInstanceMethodTests.java
| |
41,530 |
Bug 41530 move instance method: moving a method with local type creates syntax errors [refactoring]
| null |
resolved fixed
|
dc28bae
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-15T16:19:59Z | 2003-08-14T11:20:00Z |
org.eclipse.jdt.ui/core
| |
41,530 |
Bug 41530 move instance method: moving a method with local type creates syntax errors [refactoring]
| null |
resolved fixed
|
dc28bae
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-15T16:19:59Z | 2003-08-14T11:20:00Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/InstanceMethodMover.java
| |
41,313 |
Bug 41313 "Link with Editor" in Java Outline should link on activation
|
I normally work with "Link with Editor" switched off. When editing a long method whose head is out of view, I want to know in which method I am without leaving the editing position. I'd like to *double*click on "Link with Editor" in the Java Outline to synchronize it with the current position (the second click just disables "Link with Editor" again). This works nicely with the Package Explorer, where a doubleclick on "Link with Editor" reveals the current file. I think this doubleclick behavior should be consistently supported by all "Link with Editor" actions.
|
resolved fixed
|
ab0f11e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-18T08:36:43Z | 2003-08-08T08:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/JavaEditor.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.javaeditor;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ResourceBundle;
import java.util.StringTokenizer;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Preferences;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BidiSegmentEvent;
import org.eclipse.swt.custom.BidiSegmentListener;
import org.eclipse.swt.custom.StyleRange;
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.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
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.Separator;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.text.BadLocationException;
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.ITextInputListener;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.ITextViewerExtension2;
import org.eclipse.jface.text.ITextViewerExtension3;
import org.eclipse.jface.text.ITextViewerExtension4;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.text.TextUtilities;
import org.eclipse.jface.text.information.IInformationProvider;
import org.eclipse.jface.text.information.IInformationProviderExtension2;
import org.eclipse.jface.text.information.InformationPresenter;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.AnnotationRulerColumn;
import org.eclipse.jface.text.source.ChangeRulerColumn;
import org.eclipse.jface.text.source.CompositeRuler;
import org.eclipse.jface.text.source.IAnnotationAccess;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.IAnnotationModelExtension;
import org.eclipse.jface.text.source.IChangeRulerColumn;
import org.eclipse.jface.text.source.IOverviewRuler;
import org.eclipse.jface.text.source.ISharedTextColors;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.ISourceViewerExtension;
import org.eclipse.jface.text.source.IVerticalRuler;
import org.eclipse.jface.text.source.IVerticalRulerColumn;
import org.eclipse.jface.text.source.LineNumberChangeRulerColumn;
import org.eclipse.jface.text.source.LineNumberRulerColumn;
import org.eclipse.jface.text.source.OverviewRuler;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.IPostSelectionProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
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.IEditorInput;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPartService;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.editors.quickdiff.IQuickDiffProviderImplementation;
import org.eclipse.ui.editors.text.DefaultEncodingSupport;
import org.eclipse.ui.editors.text.IEncodingSupport;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.EditorActionBarContributor;
import org.eclipse.ui.part.IShowInTargetList;
import org.eclipse.ui.texteditor.AddTaskAction;
import org.eclipse.ui.texteditor.AnnotationPreference;
import org.eclipse.ui.texteditor.DefaultRangeIndicator;
import org.eclipse.ui.texteditor.IAbstractTextEditorHelpContextIds;
import org.eclipse.ui.texteditor.IEditorStatusLine;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
import org.eclipse.ui.texteditor.MarkerAnnotation;
import org.eclipse.ui.texteditor.MarkerAnnotationPreferences;
import org.eclipse.ui.texteditor.ResourceAction;
import org.eclipse.ui.texteditor.SourceViewerDecorationSupport;
import org.eclipse.ui.texteditor.StatusTextEditor;
import org.eclipse.ui.texteditor.TextEditorAction;
import org.eclipse.ui.texteditor.TextOperationAction;
import org.eclipse.ui.views.contentoutline.ContentOutline;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
import org.eclipse.ui.views.tasklist.TaskList;
import org.eclipse.ui.internal.editors.quickdiff.DocumentLineDiffer;
import org.eclipse.ui.internal.editors.quickdiff.ReferenceProviderDescriptor;
import org.eclipse.ui.internal.editors.text.EditorsPlugin;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICodeAssist;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IImportContainer;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IPackageDeclaration;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.ISourceReference;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.actions.IJavaEditorActionDefinitionIds;
import org.eclipse.jdt.ui.actions.JavaSearchActionGroup;
import org.eclipse.jdt.ui.actions.OpenEditorActionGroup;
import org.eclipse.jdt.ui.actions.OpenViewActionGroup;
import org.eclipse.jdt.ui.actions.ShowActionGroup;
import org.eclipse.jdt.ui.text.IColorManager;
import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.GoToNextPreviousMemberAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.SelectionHistory;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectEnclosingAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectHistoryAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectNextAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectPreviousAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectionAction;
import org.eclipse.jdt.internal.ui.text.HTMLTextPresenter;
import org.eclipse.jdt.internal.ui.text.JavaChangeHover;
import org.eclipse.jdt.internal.ui.text.JavaPairMatcher;
import org.eclipse.jdt.internal.ui.text.IJavaPartitions;
import org.eclipse.jdt.internal.ui.util.JavaUIHelp;
import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider;
/**
* Java specific text editor.
*/
public abstract class JavaEditor extends StatusTextEditor implements IViewPartInputProvider {
/**
* Internal implementation class for a change listener.
* @since 3.0
*/
protected abstract class AbstractSelectionChangedListener implements ISelectionChangedListener {
/**
* Installs this selection changed listener with the given selection provider. If
* the selection provider is a post selection provider, post selection changed
* events are the preferred choice, otherwise normal selection changed events
* are requested.
*
* @param selectionProvider
*/
public void install(ISelectionProvider selectionProvider) {
if (selectionProvider == null)
return;
if (selectionProvider instanceof IPostSelectionProvider) {
IPostSelectionProvider provider= (IPostSelectionProvider) selectionProvider;
provider.addPostSelectionChangedListener(this);
} else {
selectionProvider.addSelectionChangedListener(this);
}
}
/**
* Removes this selection changed listener from the given selection provider.
*
* @param selectionProvider
*/
public void uninstall(ISelectionProvider selectionProvider) {
if (selectionProvider == null)
return;
if (selectionProvider instanceof IPostSelectionProvider) {
IPostSelectionProvider provider= (IPostSelectionProvider) selectionProvider;
provider.removePostSelectionChangedListener(this);
} else {
selectionProvider.removeSelectionChangedListener(this);
}
}
}
/**
* Updates the Java outline page selection and this editor's range indicator.
*
* @since 3.0
*/
private class EditorSelectionChangedListener extends AbstractSelectionChangedListener {
/*
* @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent)
*/
public void selectionChanged(SelectionChangedEvent event) {
selectionChanged();
}
public void selectionChanged() {
ISourceReference element= computeHighlightRangeSourceReference();
synchronizeOutlinePage(element);
setSelection(element, false);
}
}
/**
* Updates the selection in the editor's widget with the selection of the outline page.
*/
class OutlineSelectionChangedListener extends AbstractSelectionChangedListener {
public void selectionChanged(SelectionChangedEvent event) {
doSelectionChanged(event);
}
}
/*
* Link mode.
*/
class MouseClickListener implements KeyListener, MouseListener, MouseMoveListener,
FocusListener, PaintListener, IPropertyChangeListener, IDocumentListener, ITextInputListener {
/** The session is active. */
private boolean fActive;
/** The currently active style range. */
private IRegion fActiveRegion;
/** The currently active style range as position. */
private Position fRememberedPosition;
/** The hand cursor. */
private Cursor fCursor;
/** The link color. */
private Color fColor;
/** The key modifier mask. */
private int fKeyModifierMask;
public void deactivate() {
deactivate(false);
}
public void deactivate(boolean redrawAll) {
if (!fActive)
return;
repairRepresentation(redrawAll);
fActive= false;
}
public void install() {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
StyledText text= sourceViewer.getTextWidget();
if (text == null || text.isDisposed())
return;
updateColor(sourceViewer);
sourceViewer.addTextInputListener(this);
IDocument document= sourceViewer.getDocument();
if (document != null)
document.addDocumentListener(this);
text.addKeyListener(this);
text.addMouseListener(this);
text.addMouseMoveListener(this);
text.addFocusListener(this);
text.addPaintListener(this);
updateKeyModifierMask();
IPreferenceStore preferenceStore= getPreferenceStore();
preferenceStore.addPropertyChangeListener(this);
}
private void updateKeyModifierMask() {
String modifiers= getPreferenceStore().getString(BROWSER_LIKE_LINKS_KEY_MODIFIER);
fKeyModifierMask= computeStateMask(modifiers);
if (fKeyModifierMask == -1) {
// Fallback to stored state mask
fKeyModifierMask= getPreferenceStore().getInt(BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK);
}
}
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;
}
public void uninstall() {
if (fColor != null) {
fColor.dispose();
fColor= null;
}
if (fCursor != null) {
fCursor.dispose();
fCursor= null;
}
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
sourceViewer.removeTextInputListener(this);
IDocument document= sourceViewer.getDocument();
if (document != null)
document.removeDocumentListener(this);
IPreferenceStore preferenceStore= getPreferenceStore();
if (preferenceStore != null)
preferenceStore.removePropertyChangeListener(this);
StyledText text= sourceViewer.getTextWidget();
if (text == null || text.isDisposed())
return;
text.removeKeyListener(this);
text.removeMouseListener(this);
text.removeMouseMoveListener(this);
text.removeFocusListener(this);
text.removePaintListener(this);
}
/*
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
if (event.getProperty().equals(JavaEditor.LINK_COLOR)) {
ISourceViewer viewer= getSourceViewer();
if (viewer != null)
updateColor(viewer);
} else if (event.getProperty().equals(BROWSER_LIKE_LINKS_KEY_MODIFIER)) {
updateKeyModifierMask();
}
}
private void updateColor(ISourceViewer viewer) {
if (fColor != null)
fColor.dispose();
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
Display display= text.getDisplay();
fColor= createColor(getPreferenceStore(), JavaEditor.LINK_COLOR, display);
}
/**
* 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);
if (rgb != null)
return new Color(display, rgb);
}
return null;
}
private void repairRepresentation() {
repairRepresentation(false);
}
private void repairRepresentation(boolean redrawAll) {
if (fActiveRegion == null)
return;
ISourceViewer viewer= getSourceViewer();
if (viewer != null) {
resetCursor(viewer);
int offset= fActiveRegion.getOffset();
int length= fActiveRegion.getLength();
// remove style
if (!redrawAll && viewer instanceof ITextViewerExtension2)
((ITextViewerExtension2) viewer).invalidateTextPresentation(offset, length);
else
viewer.invalidateTextPresentation();
// remove underline
if (viewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) viewer;
offset= extension.modelOffset2WidgetOffset(offset);
} else {
offset -= viewer.getVisibleRegion().getOffset();
}
StyledText text= viewer.getTextWidget();
try {
text.redrawRange(offset, length, true);
} catch (IllegalArgumentException x) {
JavaPlugin.log(x);
}
}
fActiveRegion= null;
}
// will eventually be replaced by a method provided by jdt.core
private IRegion selectWord(IDocument document, int anchor) {
try {
int offset= anchor;
char c;
while (offset >= 0) {
c= document.getChar(offset);
if (!Character.isJavaIdentifierPart(c))
break;
--offset;
}
int start= offset;
offset= anchor;
int length= document.getLength();
while (offset < length) {
c= document.getChar(offset);
if (!Character.isJavaIdentifierPart(c))
break;
++offset;
}
int end= offset;
if (start == end)
return new Region(start, 0);
else
return new Region(start + 1, end - start - 1);
} catch (BadLocationException x) {
return null;
}
}
IRegion getCurrentTextRegion(ISourceViewer viewer) {
int offset= getCurrentTextOffset(viewer);
if (offset == -1)
return null;
IJavaElement input= SelectionConverter.getInput(JavaEditor.this);
if (input == null)
return null;
try {
IJavaElement[] elements= null;
synchronized (input) {
elements= ((ICodeAssist) input).codeSelect(offset, 0);
}
if (elements == null || elements.length == 0)
return null;
return selectWord(viewer.getDocument(), offset);
} catch (JavaModelException e) {
return null;
}
}
private int getCurrentTextOffset(ISourceViewer viewer) {
try {
StyledText text= viewer.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 (viewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) viewer;
return extension.widgetOffset2ModelOffset(widgetOffset);
} else {
return widgetOffset + viewer.getVisibleRegion().getOffset();
}
} catch (IllegalArgumentException e) {
return -1;
}
}
private void highlightRegion(ISourceViewer viewer, IRegion region) {
if (region.equals(fActiveRegion))
return;
repairRepresentation();
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
// highlight region
int offset= 0;
int length= 0;
if (viewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) viewer;
IRegion widgetRange= extension.modelRange2WidgetRange(region);
if (widgetRange == null)
return;
offset= widgetRange.getOffset();
length= widgetRange.getLength();
} else {
offset= region.getOffset() - viewer.getVisibleRegion().getOffset();
length= region.getLength();
}
StyleRange oldStyleRange= text.getStyleRangeAtOffset(offset);
Color foregroundColor= fColor;
Color backgroundColor= oldStyleRange == null ? text.getBackground() : oldStyleRange.background;
StyleRange styleRange= new StyleRange(offset, length, foregroundColor, backgroundColor);
text.setStyleRange(styleRange);
// underline
text.redrawRange(offset, length, true);
fActiveRegion= region;
}
private void activateCursor(ISourceViewer 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 void resetCursor(ISourceViewer viewer) {
StyledText text= viewer.getTextWidget();
if (text != null && !text.isDisposed())
text.setCursor(null);
if (fCursor != null) {
fCursor.dispose();
fCursor= null;
}
}
/*
* @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.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;
deactivate();
if (wasActive) {
IAction action= getAction("OpenEditor"); //$NON-NLS-1$
if (action != null)
action.run();
}
}
/*
* @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;
}
ISourceViewer viewer= getSourceViewer();
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= getCurrentTextRegion(viewer);
if (region == null || region.getLength() == 0) {
repairRepresentation();
return;
}
highlightRegion(viewer, region);
activateCursor(viewer);
}
/*
* @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();
}
/*
* @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 && !fRememberedPosition.isDeleted()) {
event.getDocument().removePosition(fRememberedPosition);
fActiveRegion= new Region(fRememberedPosition.getOffset(), fRememberedPosition.getLength());
}
fRememberedPosition= null;
ISourceViewer viewer= getSourceViewer();
if (viewer != null) {
StyledText widget= viewer.getTextWidget();
if (widget != null && !widget.isDisposed()) {
widget.getDisplay().asyncExec(new Runnable() {
public void run() {
deactivate();
}
});
}
}
}
/*
* @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);
}
/*
* @see PaintListener#paintControl(PaintEvent)
*/
public void paintControl(PaintEvent event) {
if (fActiveRegion == null)
return;
ISourceViewer viewer= getSourceViewer();
if (viewer == null)
return;
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
int offset= 0;
int length= 0;
if (viewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) viewer;
IRegion widgetRange= extension.modelRange2WidgetRange(new Region(offset, length));
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);
}
private boolean includes(IRegion region, IRegion position) {
return
position.getOffset() >= region.getOffset() &&
position.getOffset() + position.getLength() <= region.getOffset() + region.getLength();
}
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 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;
}
}
/**
* This action dispatches into two behaviours: If there is no current text
* hover, the javadoc is displayed using information presenter. If there is
* a current text hover, it is converted into a information presenter in
* order to make it sticky.
*/
class InformationDispatchAction extends TextEditorAction {
/** The wrapped text operation action. */
private final TextOperationAction fTextOperationAction;
/**
* Creates a dispatch action.
*/
public InformationDispatchAction(ResourceBundle resourceBundle, String prefix, final TextOperationAction textOperationAction) {
super(resourceBundle, prefix, JavaEditor.this);
if (textOperationAction == null)
throw new IllegalArgumentException();
fTextOperationAction= textOperationAction;
}
/*
* @see org.eclipse.jface.action.IAction#run()
*/
public void run() {
/**
* Information provider used to present the information.
*
* @since 3.0
*/
class InformationProvider implements IInformationProvider, IInformationProviderExtension2 {
private IRegion fHoverRegion;
private String fHoverInfo;
private IInformationControlCreator fControlCreator;
InformationProvider(IRegion hoverRegion, String hoverInfo, IInformationControlCreator controlCreator) {
fHoverRegion= hoverRegion;
fHoverInfo= hoverInfo;
fControlCreator= controlCreator;
}
/*
* @see org.eclipse.jface.text.information.IInformationProvider#getSubject(org.eclipse.jface.text.ITextViewer, int)
*/
public IRegion getSubject(ITextViewer textViewer, int invocationOffset) {
return fHoverRegion;
}
/*
* @see org.eclipse.jface.text.information.IInformationProvider#getInformation(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion)
*/
public String getInformation(ITextViewer textViewer, IRegion subject) {
return fHoverInfo;
}
/*
* @see org.eclipse.jface.text.information.IInformationProviderExtension2#getInformationPresenterControlCreator()
* @since 3.0
*/
public IInformationControlCreator getInformationPresenterControlCreator() {
return fControlCreator;
}
}
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null) {
fTextOperationAction.run();
return;
}
if (sourceViewer instanceof ITextViewerExtension4) {
ITextViewerExtension4 extension4= (ITextViewerExtension4) sourceViewer;
extension4.moveFocusToWidgetToken();
}
if (! (sourceViewer instanceof ITextViewerExtension2)) {
fTextOperationAction.run();
return;
}
ITextViewerExtension2 textViewerExtension2= (ITextViewerExtension2) sourceViewer;
// does a text hover exist?
ITextHover textHover= textViewerExtension2.getCurrentTextHover();
if (textHover == null) {
fTextOperationAction.run();
return;
}
Point hoverEventLocation= textViewerExtension2.getHoverEventLocation();
int offset= computeOffsetAtLocation(sourceViewer, hoverEventLocation.x, hoverEventLocation.y);
if (offset == -1) {
fTextOperationAction.run();
return;
}
try {
// get the text hover content
String contentType= TextUtilities.getContentType(sourceViewer.getDocument(), IJavaPartitions.JAVA_PARTITIONING, offset);
IRegion hoverRegion= textHover.getHoverRegion(sourceViewer, offset);
if (hoverRegion == null)
return;
String hoverInfo= textHover.getHoverInfo(sourceViewer, hoverRegion);
IInformationControlCreator controlCreator= null;
if (textHover instanceof IInformationProviderExtension2)
controlCreator= ((IInformationProviderExtension2)textHover).getInformationPresenterControlCreator();
IInformationProvider informationProvider= new InformationProvider(hoverRegion, hoverInfo, controlCreator);
fInformationPresenter.setOffset(offset);
fInformationPresenter.setInformationProvider(informationProvider, contentType);
fInformationPresenter.showInformation();
} catch (BadLocationException e) {
}
}
// modified version from TextViewer
private int computeOffsetAtLocation(ITextViewer textViewer, int x, int y) {
StyledText styledText= textViewer.getTextWidget();
IDocument document= textViewer.getDocument();
if (document == null)
return -1;
try {
int widgetLocation= styledText.getOffsetAtLocation(new Point(x, y));
if (textViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) textViewer;
return extension.widgetOffset2ModelOffset(widgetLocation);
} else {
IRegion visibleRegion= textViewer.getVisibleRegion();
return widgetLocation + visibleRegion.getOffset();
}
} catch (IllegalArgumentException e) {
return -1;
}
}
}
static protected class AnnotationAccess implements IAnnotationAccess {
/*
* @see org.eclipse.jface.text.source.IAnnotationAccess#getType(org.eclipse.jface.text.source.Annotation)
*/
public Object getType(Annotation annotation) {
if (annotation instanceof IJavaAnnotation) {
IJavaAnnotation javaAnnotation= (IJavaAnnotation) annotation;
if (javaAnnotation.isRelevant())
return javaAnnotation.getAnnotationType();
}
return null;
}
/*
* @see org.eclipse.jface.text.source.IAnnotationAccess#isMultiLine(org.eclipse.jface.text.source.Annotation)
*/
public boolean isMultiLine(Annotation annotation) {
return true;
}
/*
* @see org.eclipse.jface.text.source.IAnnotationAccess#isTemporary(org.eclipse.jface.text.source.Annotation)
*/
public boolean isTemporary(Annotation annotation) {
if (annotation instanceof IJavaAnnotation) {
IJavaAnnotation javaAnnotation= (IJavaAnnotation) annotation;
if (javaAnnotation.isRelevant())
return javaAnnotation.isTemporary();
}
return false;
}
}
private class PropertyChangeListener implements org.eclipse.core.runtime.Preferences.IPropertyChangeListener {
/*
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
handlePreferencePropertyChanged(event);
}
}
/** Preference key for showing the line number ruler */
protected final static String LINE_NUMBER_RULER= PreferenceConstants.EDITOR_LINE_NUMBER_RULER;
/** Preference key for the foreground color of the line numbers */
protected final static String LINE_NUMBER_COLOR= PreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR;
/** Preference key for the link color */
protected final static String LINK_COLOR= PreferenceConstants.EDITOR_LINK_COLOR;
/** Preference key for matching brackets */
protected final static String MATCHING_BRACKETS= PreferenceConstants.EDITOR_MATCHING_BRACKETS;
/** Preference key for matching brackets color */
protected final static String MATCHING_BRACKETS_COLOR= PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR;
/** Preference key for highlighting current line */
protected final static String CURRENT_LINE= PreferenceConstants.EDITOR_CURRENT_LINE;
/** Preference key for highlight color of current line */
protected final static String CURRENT_LINE_COLOR= PreferenceConstants.EDITOR_CURRENT_LINE_COLOR;
/** Preference key for showing print marging ruler */
protected final static String PRINT_MARGIN= PreferenceConstants.EDITOR_PRINT_MARGIN;
/** Preference key for print margin ruler color */
protected final static String PRINT_MARGIN_COLOR= PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR;
/** Preference key for print margin ruler column */
protected final static String PRINT_MARGIN_COLUMN= PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN;
/** Preference key for shwoing the overview ruler */
protected final static String OVERVIEW_RULER= PreferenceConstants.EDITOR_OVERVIEW_RULER;
/** Preference key for compiler task tags */
private final static String COMPILER_TASK_TAGS= JavaCore.COMPILER_TASK_TAGS;
/** Preference key for browser like links */
private final static String BROWSER_LIKE_LINKS= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS;
/** Preference key for key modifier of browser like links */
private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER;
/**
* Preference key for key modifier mask of browser like links.
* The value is only used if the value of <code>EDITOR_BROWSER_LIKE_LINKS</code>
* cannot be resolved to valid SWT modifier bits.
*
* @since 2.1.1
*/
private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK;
protected final static char[] BRACKETS= { '{', '}', '(', ')', '[', ']' };
/** The outline page */
protected JavaOutlinePage fOutlinePage;
/** Outliner context menu Id */
protected String fOutlinerContextMenuId;
/**
* The editor selection changed listener.
*
* @since 3.0
*/
private EditorSelectionChangedListener fEditorSelectionChangedListener;
/** The selection changed listener */
protected AbstractSelectionChangedListener fOutlineSelectionChangedListener= new OutlineSelectionChangedListener();
/** The editor's bracket matcher */
protected JavaPairMatcher fBracketMatcher= new JavaPairMatcher(BRACKETS);
/** The line number ruler column */
private LineNumberRulerColumn fLineNumberRulerColumn;
/**
* The change ruler column.
* @since 3.0
*/
private IChangeRulerColumn fChangeRulerColumn;
/** This editor's encoding support */
private DefaultEncodingSupport fEncodingSupport;
/** The mouse listener */
private MouseClickListener fMouseListener;
/** The information presenter. */
private InformationPresenter fInformationPresenter;
/**
* The annotation preferences.
* @since 3.0
*/
private MarkerAnnotationPreferences fAnnotationPreferences;
/** The annotation access */
protected IAnnotationAccess fAnnotationAccess= new AnnotationAccess();
/** The source viewer decoration support */
protected SourceViewerDecorationSupport fSourceViewerDecorationSupport;
/** The overview ruler */
protected OverviewRuler fOverviewRuler;
/** History for structure select action */
private SelectionHistory fSelectionHistory;
/** The preference property change listener for java core. */
private org.eclipse.core.runtime.Preferences.IPropertyChangeListener fPropertyChangeListener= new PropertyChangeListener();
protected CompositeActionGroup fActionGroups;
private CompositeActionGroup fContextMenuGroup;
/**
* Whether quick diff information is displayed, either on a change ruler or the line number ruler.
* @since 3.0
*/
private boolean fIsChangeInformationShown;
/**
* Returns the most narrow java element including the given offset.
*
* @param offset the offset inside of the requested element
* @return the most narrow java element
*/
abstract protected IJavaElement getElementAt(int offset);
/**
* Returns the java element of this editor's input corresponding to the given IJavaElement
*/
abstract protected IJavaElement getCorrespondingElement(IJavaElement element);
/**
* Sets the input of the editor's outline page.
*/
abstract protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input);
/**
* Default constructor.
*/
public JavaEditor() {
super();
fAnnotationPreferences= new MarkerAnnotationPreferences();
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
setSourceViewerConfiguration(new JavaSourceViewerConfiguration(textTools, this, IJavaPartitions.JAVA_PARTITIONING));
setRangeIndicator(new DefaultRangeIndicator());
setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore());
setKeyBindingScopes(new String[] { "org.eclipse.jdt.ui.javaEditorScope" }); //$NON-NLS-1$
}
/*
* @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
*/
protected final ISourceViewer createSourceViewer(Composite parent, IVerticalRuler verticalRuler, int styles) {
ISharedTextColors sharedColors= JavaPlugin.getDefault().getJavaTextTools().getColorManager();
fOverviewRuler= new OverviewRuler(fAnnotationAccess, VERTICAL_RULER_WIDTH, sharedColors);
Iterator e= fAnnotationPreferences.getAnnotationPreferences().iterator();
while (e.hasNext()) {
AnnotationPreference preference= (AnnotationPreference) e.next();
if (preference.contributesToHeader())
fOverviewRuler.addHeaderAnnotationType(preference.getAnnotationType());
}
ISourceViewer viewer= createJavaSourceViewer(parent, verticalRuler, fOverviewRuler, isOverviewRulerVisible(), styles);
StyledText text= viewer.getTextWidget();
text.addBidiSegmentListener(new BidiSegmentListener() {
public void lineGetSegments(BidiSegmentEvent event) {
event.segments= getBidiLineSegments(event.lineOffset, event.lineText);
}
});
JavaUIHelp.setHelp(this, text, IJavaHelpContextIds.JAVA_EDITOR);
fSourceViewerDecorationSupport= new SourceViewerDecorationSupport(viewer, fOverviewRuler, fAnnotationAccess, sharedColors);
configureSourceViewerDecorationSupport();
return viewer;
}
public final ISourceViewer getViewer() {
return getSourceViewer();
}
/*
* @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
*/
protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean isOverviewRulerVisible, int styles) {
return new JavaSourceViewer(parent, verticalRuler, fOverviewRuler, isOverviewRulerVisible(), styles);
}
/*
* @see AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent)
*/
protected boolean affectsTextPresentation(PropertyChangeEvent event) {
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
return textTools.affectsBehavior(event);
}
/**
* Sets the outliner's context menu ID.
*/
protected void setOutlinerContextMenuId(String menuId) {
fOutlinerContextMenuId= menuId;
}
/**
* Returns the standard action group of this editor.
*/
protected ActionGroup getActionGroup() {
return fActionGroups;
}
/*
* @see AbstractTextEditor#editorContextMenuAboutToShow
*/
public void editorContextMenuAboutToShow(IMenuManager menu) {
super.editorContextMenuAboutToShow(menu);
menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, new Separator(IContextMenuConstants.GROUP_OPEN));
menu.insertAfter(IContextMenuConstants.GROUP_OPEN, new GroupMarker(IContextMenuConstants.GROUP_SHOW));
ActionContext context= new ActionContext(getSelectionProvider().getSelection());
fContextMenuGroup.setContext(context);
fContextMenuGroup.fillContextMenu(menu);
fContextMenuGroup.setContext(null);
}
/**
* Creates the outline page used with this editor.
*/
protected JavaOutlinePage createOutlinePage() {
JavaOutlinePage page= new JavaOutlinePage(fOutlinerContextMenuId, this);
fOutlineSelectionChangedListener.install(page);
setOutlinePageInput(page, getEditorInput());
return page;
}
/**
* Informs the editor that its outliner has been closed.
*/
public void outlinePageClosed() {
if (fOutlinePage != null) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage= null;
resetHighlightRange();
}
}
/**
* Synchronizes the outliner selection with the given element
* position in the editor.
*
* @param element the java element to select
*/
protected void synchronizeOutlinePage(ISourceReference element) {
if (fOutlinePage != null && element != null && !isJavaOutlinePageActive()) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage.select(element);
fOutlineSelectionChangedListener.install(fOutlinePage);
}
}
/**
* Synchronizes the outliner selection with the actual cursor
* position in the editor.
*/
public void synchronizeOutlinePageSelection() {
synchronizeOutlinePage(computeHighlightRangeSourceReference());
}
/*
* Get the desktop's StatusLineManager
*/
protected IStatusLineManager getStatusLineManager() {
IEditorActionBarContributor contributor= getEditorSite().getActionBarContributor();
if (contributor instanceof EditorActionBarContributor) {
return ((EditorActionBarContributor) contributor).getActionBars().getStatusLineManager();
}
return null;
}
/*
* @see AbstractTextEditor#getAdapter(Class)
*/
public Object getAdapter(Class required) {
if (IContentOutlinePage.class.equals(required)) {
if (fOutlinePage == null)
fOutlinePage= createOutlinePage();
return fOutlinePage;
}
if (IEncodingSupport.class.equals(required))
return fEncodingSupport;
if (required == IShowInTargetList.class) {
return new IShowInTargetList() {
public String[] getShowInTargetIds() {
return new String[] { JavaUI.ID_PACKAGES, IPageLayout.ID_OUTLINE, IPageLayout.ID_RES_NAV };
}
};
}
return super.getAdapter(required);
}
protected void setSelection(ISourceReference reference, boolean moveCursor) {
ISelection selection= getSelectionProvider().getSelection();
if (selection instanceof TextSelection) {
TextSelection textSelection= (TextSelection) selection;
if (textSelection.getOffset() != 0 || textSelection.getLength() != 0)
markInNavigationHistory();
}
if (reference != null) {
StyledText textWidget= null;
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer != null)
textWidget= sourceViewer.getTextWidget();
if (textWidget == null)
return;
try {
ISourceRange range= reference.getSourceRange();
if (range == null)
return;
int offset= range.getOffset();
int length= range.getLength();
if (offset < 0 || length < 0)
return;
setHighlightRange(offset, length, moveCursor);
if (!moveCursor)
return;
offset= -1;
length= -1;
if (reference instanceof IMember) {
range= ((IMember) reference).getNameRange();
if (range != null) {
offset= range.getOffset();
length= range.getLength();
}
} else if (reference instanceof IImportDeclaration) {
String name= ((IImportDeclaration) reference).getElementName();
if (name != null && name.length() > 0) {
String content= reference.getSource();
if (content != null) {
offset= range.getOffset() + content.indexOf(name);
length= name.length();
}
}
} else if (reference instanceof IPackageDeclaration) {
String name= ((IPackageDeclaration) reference).getElementName();
if (name != null && name.length() > 0) {
String content= reference.getSource();
if (content != null) {
offset= range.getOffset() + content.indexOf(name);
length= name.length();
}
}
}
if (offset > -1 && length > 0) {
try {
textWidget.setRedraw(false);
sourceViewer.revealRange(offset, length);
sourceViewer.setSelectedRange(offset, length);
} finally {
textWidget.setRedraw(true);
}
markInNavigationHistory();
}
} catch (JavaModelException x) {
} catch (IllegalArgumentException x) {
}
} else if (moveCursor) {
resetHighlightRange();
markInNavigationHistory();
}
}
public void setSelection(IJavaElement element) {
if (element == null || element instanceof ICompilationUnit || element instanceof IClassFile) {
/*
* If the element is an ICompilationUnit this unit is either the input
* of this editor or not being displayed. In both cases, nothing should
* happened. (http://dev.eclipse.org/bugs/show_bug.cgi?id=5128)
*/
return;
}
IJavaElement corresponding= getCorrespondingElement(element);
if (corresponding instanceof ISourceReference) {
ISourceReference reference= (ISourceReference) corresponding;
// set hightlight range
setSelection(reference, true);
// set outliner selection
if (fOutlinePage != null) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage.select(reference);
fOutlineSelectionChangedListener.install(fOutlinePage);
}
}
}
protected void doSelectionChanged(SelectionChangedEvent event) {
ISourceReference reference= null;
ISelection selection= event.getSelection();
Iterator iter= ((IStructuredSelection) selection).iterator();
while (iter.hasNext()) {
Object o= iter.next();
if (o instanceof ISourceReference) {
reference= (ISourceReference) o;
break;
}
}
if (!isActivePart() && JavaPlugin.getActivePage() != null)
JavaPlugin.getActivePage().bringToTop(this);
setSelection(reference, !isActivePart());
}
/*
* @see AbstractTextEditor#adjustHighlightRange(int, int)
*/
protected void adjustHighlightRange(int offset, int length) {
try {
IJavaElement element= getElementAt(offset);
while (element instanceof ISourceReference) {
ISourceRange range= ((ISourceReference) element).getSourceRange();
if (offset < range.getOffset() + range.getLength() && range.getOffset() < offset + length) {
setHighlightRange(range.getOffset(), range.getLength(), true);
if (fOutlinePage != null) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage.select((ISourceReference) element);
fOutlineSelectionChangedListener.install(fOutlinePage);
}
return;
}
element= element.getParent();
}
} catch (JavaModelException x) {
JavaPlugin.log(x.getStatus());
}
resetHighlightRange();
}
protected boolean isActivePart() {
IWorkbenchPart part= getActivePart();
return part != null && part.equals(this);
}
private boolean isJavaOutlinePageActive() {
IWorkbenchPart part= getActivePart();
return part instanceof ContentOutline && ((ContentOutline)part).getCurrentPage() == fOutlinePage;
}
private IWorkbenchPart getActivePart() {
IWorkbenchWindow window= getSite().getWorkbenchWindow();
IPartService service= window.getPartService();
IWorkbenchPart part= service.getActivePart();
return part;
}
/*
* @see StatusTextEditor#getStatusHeader(IStatus)
*/
protected String getStatusHeader(IStatus status) {
if (fEncodingSupport != null) {
String message= fEncodingSupport.getStatusHeader(status);
if (message != null)
return message;
}
return super.getStatusHeader(status);
}
/*
* @see StatusTextEditor#getStatusBanner(IStatus)
*/
protected String getStatusBanner(IStatus status) {
if (fEncodingSupport != null) {
String message= fEncodingSupport.getStatusBanner(status);
if (message != null)
return message;
}
return super.getStatusBanner(status);
}
/*
* @see StatusTextEditor#getStatusMessage(IStatus)
*/
protected String getStatusMessage(IStatus status) {
if (fEncodingSupport != null) {
String message= fEncodingSupport.getStatusMessage(status);
if (message != null)
return message;
}
return super.getStatusMessage(status);
}
/*
* @see AbstractTextEditor#doSetInput
*/
protected void doSetInput(IEditorInput input) throws CoreException {
super.doSetInput(input);
if (fEncodingSupport != null)
fEncodingSupport.reset();
setOutlinePageInput(fOutlinePage, input);
}
/*
* @see IWorkbenchPart#dispose()
*/
public void dispose() {
if (isBrowserLikeLinks())
disableBrowserLikeLinks();
if (fEncodingSupport != null) {
fEncodingSupport.dispose();
fEncodingSupport= null;
}
if (fPropertyChangeListener != null) {
Preferences preferences= JavaCore.getPlugin().getPluginPreferences();
preferences.removePropertyChangeListener(fPropertyChangeListener);
fPropertyChangeListener= null;
}
if (fSourceViewerDecorationSupport != null) {
fSourceViewerDecorationSupport.dispose();
fSourceViewerDecorationSupport= null;
}
if (fBracketMatcher != null) {
fBracketMatcher.dispose();
fBracketMatcher= null;
}
if (fSelectionHistory != null) {
fSelectionHistory.dispose();
fSelectionHistory= null;
}
if (fEditorSelectionChangedListener != null) {
fEditorSelectionChangedListener.uninstall(getSelectionProvider());
fEditorSelectionChangedListener= null;
}
super.dispose();
}
protected void createActions() {
super.createActions();
ResourceAction resAction= new AddTaskAction(JavaEditorMessages.getResourceBundle(), "AddTask.", this); //$NON-NLS-1$
resAction.setHelpContextId(IAbstractTextEditorHelpContextIds.ADD_TASK_ACTION);
resAction.setActionDefinitionId(ITextEditorActionDefinitionIds.ADD_TASK);
setAction(ITextEditorActionConstants.ADD_TASK, resAction);
ActionGroup oeg, ovg, jsg, sg;
fActionGroups= new CompositeActionGroup(new ActionGroup[] {
oeg= new OpenEditorActionGroup(this),
sg= new ShowActionGroup(this),
ovg= new OpenViewActionGroup(this),
jsg= new JavaSearchActionGroup(this)
});
fContextMenuGroup= new CompositeActionGroup(new ActionGroup[] {oeg, ovg, sg, jsg});
resAction= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc.", this, ISourceViewer.INFORMATION, true); //$NON-NLS-1$
resAction= new InformationDispatchAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc.", (TextOperationAction) resAction); //$NON-NLS-1$
resAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_JAVADOC);
setAction("ShowJavaDoc", resAction); //$NON-NLS-1$
WorkbenchHelp.setHelp(resAction, IJavaHelpContextIds.SHOW_JAVADOC_ACTION);
Action action= new GotoMatchingBracketAction(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_MATCHING_BRACKET);
setAction(GotoMatchingBracketAction.GOTO_MATCHING_BRACKET, action);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"ShowOutline.", this, JavaSourceViewer.SHOW_OUTLINE, true); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_OUTLINE);
setAction(IJavaEditorActionDefinitionIds.SHOW_OUTLINE, action);
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.SHOW_OUTLINE_ACTION);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"OpenStructure.", this, JavaSourceViewer.OPEN_STRUCTURE, true); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_STRUCTURE);
setAction(IJavaEditorActionDefinitionIds.OPEN_STRUCTURE, action);
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.OPEN_STRUCTURE_ACTION);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"OpenHierarchy.", this, JavaSourceViewer.SHOW_HIERARCHY, true); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_HIERARCHY);
setAction(IJavaEditorActionDefinitionIds.OPEN_HIERARCHY, action);
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.OPEN_HIERARCHY_ACTION);
fEncodingSupport= new DefaultEncodingSupport();
fEncodingSupport.initialize(this);
fSelectionHistory= new SelectionHistory(this);
action= new StructureSelectEnclosingAction(this, fSelectionHistory);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_ENCLOSING);
setAction(StructureSelectionAction.ENCLOSING, action);
action= new StructureSelectNextAction(this, fSelectionHistory);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_NEXT);
setAction(StructureSelectionAction.NEXT, action);
action= new StructureSelectPreviousAction(this, fSelectionHistory);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_PREVIOUS);
setAction(StructureSelectionAction.PREVIOUS, action);
StructureSelectHistoryAction historyAction= new StructureSelectHistoryAction(this, fSelectionHistory);
historyAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_LAST);
setAction(StructureSelectionAction.HISTORY, historyAction);
fSelectionHistory.setHistoryAction(historyAction);
action= GoToNextPreviousMemberAction.newGoToNextMemberAction(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_NEXT_MEMBER);
setAction(GoToNextPreviousMemberAction.NEXT_MEMBER, action);
action= GoToNextPreviousMemberAction.newGoToPreviousMemberAction(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_PREVIOUS_MEMBER);
setAction(GoToNextPreviousMemberAction.PREVIOUS_MEMBER, action);
}
public void updatedTitleImage(Image image) {
setTitleImage(image);
}
/*
* @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
*/
protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
try {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
String property= event.getProperty();
if (PreferenceConstants.EDITOR_TAB_WIDTH.equals(property)) {
Object value= event.getNewValue();
if (value instanceof Integer) {
sourceViewer.getTextWidget().setTabs(((Integer) value).intValue());
} else if (value instanceof String) {
sourceViewer.getTextWidget().setTabs(Integer.parseInt((String) value));
}
return;
}
if (OVERVIEW_RULER.equals(property)) {
if (isOverviewRulerVisible())
showOverviewRuler();
else
hideOverviewRuler();
return;
}
if (LINE_NUMBER_RULER.equals(property)) {
if (isLineNumberRulerVisible())
showLineNumberRuler();
else
hideLineNumberRuler();
return;
}
if (fLineNumberRulerColumn != null
&& (LINE_NUMBER_COLOR.equals(property)
|| PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT.equals(property)
|| PREFERENCE_COLOR_BACKGROUND.equals(property))) {
initializeLineNumberRulerColumn(fLineNumberRulerColumn);
}
if (PreferenceConstants.QUICK_DIFF_CHANGED_COLOR.equals(property)
|| PreferenceConstants.QUICK_DIFF_ADDED_COLOR.equals(property)
|| PreferenceConstants.QUICK_DIFF_DELETED_COLOR.equals(property)) {
if (fLineNumberRulerColumn instanceof IChangeRulerColumn)
initializeChangeRulerColumn((IChangeRulerColumn) fLineNumberRulerColumn);
else if (fChangeRulerColumn != null)
initializeChangeRulerColumn(fChangeRulerColumn);
}
if (isJavaEditorHoverProperty(property))
updateHoverBehavior();
if (BROWSER_LIKE_LINKS.equals(property)) {
if (isBrowserLikeLinks())
enableBrowserLikeLinks();
else
disableBrowserLikeLinks();
return;
}
if (PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE.equals(property)) {
if ((event.getNewValue() instanceof Boolean) && ((Boolean)event.getNewValue()).booleanValue()) {
fEditorSelectionChangedListener= new EditorSelectionChangedListener();
fEditorSelectionChangedListener.install(getSelectionProvider());
fEditorSelectionChangedListener.selectionChanged();
} else {
fEditorSelectionChangedListener.uninstall(getSelectionProvider());
fEditorSelectionChangedListener= null;
}
return;
}
if (PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE.equals(property)) {
if (event.getNewValue() instanceof Boolean) {
Boolean disable= (Boolean) event.getNewValue();
configureInsertMode(OVERWRITE, !disable.booleanValue());
}
}
} finally {
super.handlePreferenceStoreChanged(event);
}
}
private boolean isJavaEditorHoverProperty(String property) {
return PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS.equals(property);
}
/**
* Return whether the browser like links should be enabled
* according to the preference store settings.
* @return <code>true</code> if the browser like links should be enabled
*/
private boolean isBrowserLikeLinks() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(BROWSER_LIKE_LINKS);
}
/**
* Enables browser like links.
*/
private void enableBrowserLikeLinks() {
if (fMouseListener == null) {
fMouseListener= new MouseClickListener();
fMouseListener.install();
}
}
/**
* Disables browser like links.
*/
private void disableBrowserLikeLinks() {
if (fMouseListener != null) {
fMouseListener.uninstall();
fMouseListener= null;
}
}
/**
* Handles a property change event describing a change
* of the java core's preferences and updates the preference
* related editor properties.
*
* @param event the property change event
*/
protected void handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
if (COMPILER_TASK_TAGS.equals(event.getProperty())) {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer != null && affectsTextPresentation(new PropertyChangeEvent(event.getSource(), event.getProperty(), event.getOldValue(), event.getNewValue())))
sourceViewer.invalidateTextPresentation();
}
}
/*
* @see org.eclipse.ui.texteditor.ITextEditorExtension3#showChangeInformation(boolean)
*/
public void showChangeInformation(boolean show) {
if (show == fIsChangeInformationShown)
return;
if (fIsChangeInformationShown) {
uninstallChangeRulerModel();
showChangeRuler(false); // hide change ruler if its displayed - if the line number ruler is showing, only the colors get removed by deinstalling the model
} else {
ensureChangeInfoCanBeDisplayed(); // can be replaced w/ showChangeRuler(false) once the old line number ruler is gone
installChangeRulerModel();
}
fIsChangeInformationShown= show;
}
/**
* Installs the differ annotation model with the current quick diff display.
* @since R3.0
*/
private void installChangeRulerModel() {
IChangeRulerColumn column= getChangeColumn();
if (column != null)
column.setModel(getOrCreateDiffer());
}
/**
* Uninstalls the differ annotation model from the current quick diff display.
*
* @since R3.0
*/
private void uninstallChangeRulerModel() {
IChangeRulerColumn column= getChangeColumn();
if (column != null)
column.setModel(null);
}
/**
* Ensures that either the line number display is a <code>LineNumberChangeRuler</code> or
* a separate change ruler gets displayed.
*
* @since R3.0
*/
private void ensureChangeInfoCanBeDisplayed() {
if (isLineNumberRulerVisible()) {
if (!(fLineNumberRulerColumn instanceof IChangeRulerColumn)) {
hideLineNumberRuler();
// HACK: set state already so a change ruler is created. Not needed once always a change line number bar gets installed
fIsChangeInformationShown= true;
showLineNumberRuler();
}
} else
showChangeRuler(true);
}
/*
* @see org.eclipse.ui.texteditor.ITextEditorExtension3#isChangeInformationShowing()
*/
public boolean isChangeInformationShowing() {
return fIsChangeInformationShown;
}
/**
* Creates a new <code>DocumentLineDiffer</code> and installs it with <code>model</code>.
* The default reference provider is installed with the newly created differ.
*
* @param model the annotation model of the current document.
* @return a new <code>DocumentLineDiffer</code> instance.
* @since R3.0
*/
private DocumentLineDiffer createDiffer(IAnnotationModelExtension model) {
DocumentLineDiffer differ;
differ= new DocumentLineDiffer();
IQuickDiffProviderImplementation provider= getDefaultReferenceProvider();
if (provider != null)
differ.setReferenceProvider(provider);
model.addAnnotationModel(IChangeRulerColumn.QUICK_DIFF_MODEL_ID, differ);
return differ;
}
/**
* Returns the default quick diff reference provider. It is determined by first trying to
* enable the preferred provider as specified by the preferences; if this is unsuccessful, the
* default provider as specified by the extension point mechanism is installed. If that fails
* as well, <code>null</code> is returned.
*
* @return the default reference provider
* @since R3.0
*/
private IQuickDiffProviderImplementation getDefaultReferenceProvider() {
String defaultID= getPreferenceStore().getString(PreferenceConstants.QUICK_DIFF_DEFAULT_PROVIDER);
EditorsPlugin editorPlugin= EditorsPlugin.getDefault();
ReferenceProviderDescriptor[] descs= editorPlugin.getExtensions();
IQuickDiffProviderImplementation provider= null;
// try to fetch preferred provider; load if needed
for (int i= 0; i < descs.length; i++) {
if (descs[i].getId().equals(defaultID)) {
provider= descs[i].createProvider();
if (provider != null) {
provider.setActiveEditor(this);
if (provider.isEnabled())
break;
provider.dispose();
provider= null;
}
}
}
// if not found, get default provider as specified by the extension point
if (provider == null) {
ReferenceProviderDescriptor defaultDescriptor= editorPlugin.getDefaultProvider();
if (defaultDescriptor != null) {
provider= defaultDescriptor.createProvider();
if (provider != null) {
provider.setActiveEditor(this);
if (!provider.isEnabled()) {
provider.dispose();
provider= null;
}
}
}
}
return provider;
}
/**
* Returns the annotation model associated with the document displayed in the
* viewer if it is an <code>IAnnotationModelExtension</code>, or <code>null</code>.
*
* @return the displayed document's annotation model if it is an <code>IAnnotationModelExtension</code>, or <code>null</code>
* @since R3.0
*/
private IAnnotationModelExtension getModel() {
ISourceViewer viewer= getSourceViewer();
if (viewer == null)
return null;
IAnnotationModel m= viewer.getAnnotationModel();
if (m instanceof IAnnotationModelExtension)
return (IAnnotationModelExtension) m;
else
return null;
}
/**
* Extracts the line differ from the displayed document's annotation model. If none can be found,
* a new differ is created and attached to the annotation model.
*
* @return the linediffer, or <code>null</code> if none could be found or created.
* @since R3.0
*/
private DocumentLineDiffer getOrCreateDiffer() {
IAnnotationModelExtension model= getModel();
if (model == null)
return null;
DocumentLineDiffer differ= (DocumentLineDiffer)model.getAnnotationModel(IChangeRulerColumn.QUICK_DIFF_MODEL_ID);
if (differ == null)
differ= createDiffer(model);
return differ;
}
/**
* Returns the <code>IChangeRulerColumn</code> of this editor, or <code>null</code> if there is none. Either
* the line number bar or a separate change ruler column can be returned.
*
* @return an instance of <code>IChangeRulerColumn</code> or <code>null</code>.
* @since R3.0
*/
private IChangeRulerColumn getChangeColumn() {
if (fChangeRulerColumn != null)
return fChangeRulerColumn;
else if (fLineNumberRulerColumn instanceof IChangeRulerColumn)
return (IChangeRulerColumn) fLineNumberRulerColumn;
else
return null;
}
/**
* Sets the display state of the separate change ruler column (not the quick diff display on
* the line number ruler column) to <code>show</code>.
*
* @param show <code>true</code> if the change ruler column should be shown, <code>false</code> if it should be hidden
* @since R3.0
*/
private void showChangeRuler(boolean show) {
IVerticalRuler v= getVerticalRuler();
if (v instanceof CompositeRuler) {
CompositeRuler c= (CompositeRuler) v;
if (show && fChangeRulerColumn == null)
c.addDecorator(1, createChangeRulerColumn());
else if (!show && fChangeRulerColumn != null) {
c.removeDecorator(fChangeRulerColumn);
fChangeRulerColumn= null;
}
}
}
/**
* Shows the line number ruler column.
*/
private void showLineNumberRuler() {
showChangeRuler(false);
IVerticalRuler v= getVerticalRuler();
if (v instanceof CompositeRuler) {
CompositeRuler c= (CompositeRuler) v;
c.addDecorator(1, createLineNumberRulerColumn());
}
}
/**
* Hides the line number ruler column.
*/
private void hideLineNumberRuler() {
IVerticalRuler v= getVerticalRuler();
if (fLineNumberRulerColumn != null && v instanceof CompositeRuler) {
CompositeRuler c= (CompositeRuler) v;
c.removeDecorator(fLineNumberRulerColumn);
fLineNumberRulerColumn= null;
}
if (fIsChangeInformationShown)
showChangeRuler(true);
}
/**
* Return whether the line number ruler column should be
* visible according to the preference store settings.
*
* @return <code>true</code> if the line numbers should be visible
*/
private boolean isLineNumberRulerVisible() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(LINE_NUMBER_RULER);
}
/**
* Returns whether quick diff info should be visible upon opening an editor
* according to the preference store settings.
*
* @return <code>true</code> if the line numbers should be visible
* @since R3.0
*/
private boolean isQuickDiffAlwaysOn() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(PreferenceConstants.QUICK_DIFF_ALWAYS_ON);
}
/**
* Returns a segmentation of the line of the given viewer's input document appropriate for
* bidi rendering. The default implementation returns only the string literals of a java code
* line as segments.
*
* @param viewer the text viewer
* @param lineOffset the offset of the line
* @return the line's bidi segmentation
* @throws BadLocationException in case lineOffset is not valid in document
*/
public static int[] getBidiLineSegments(ITextViewer viewer, int lineOffset) throws BadLocationException {
IDocument document= viewer.getDocument();
if (document == null)
return null;
IRegion line= document.getLineInformationOfOffset(lineOffset);
ITypedRegion[] linePartitioning= TextUtilities.computePartitioning(document, IJavaPartitions.JAVA_PARTITIONING, lineOffset, line.getLength());
List segmentation= new ArrayList();
for (int i= 0; i < linePartitioning.length; i++) {
if (IJavaPartitions.JAVA_STRING.equals(linePartitioning[i].getType()))
segmentation.add(linePartitioning[i]);
}
if (segmentation.size() == 0)
return null;
int size= segmentation.size();
int[] segments= new int[size * 2 + 1];
int j= 0;
for (int i= 0; i < size; i++) {
ITypedRegion segment= (ITypedRegion) segmentation.get(i);
if (i == 0)
segments[j++]= 0;
int offset= segment.getOffset() - lineOffset;
if (offset > segments[j - 1])
segments[j++]= offset;
if (offset + segment.getLength() >= line.getLength())
break;
segments[j++]= offset + segment.getLength();
}
if (j < segments.length) {
int[] result= new int[j];
System.arraycopy(segments, 0, result, 0, j);
segments= result;
}
return segments;
}
/**
* Returns a segmentation of the given line appropriate for bidi rendering. The default
* implementation returns only the string literals of a java code line as segments.
*
* @param lineOffset the offset of the line
* @param line the content of the line
* @return the line's bidi segmentation
*/
protected int[] getBidiLineSegments(int widgetLineOffset, String line) {
if (line != null && line.length() > 0) {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer != null) {
int lineOffset;
if (sourceViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) sourceViewer;
lineOffset= extension.widgetOffset2ModelOffset(widgetLineOffset);
} else {
IRegion visible= sourceViewer.getVisibleRegion();
lineOffset= visible.getOffset() + widgetLineOffset;
}
try {
return getBidiLineSegments(sourceViewer, lineOffset);
} catch (BadLocationException x) {
// don't segment line in this case
}
}
}
return null;
}
/**
* Initializes the given line number ruler column from the preference store.
*
* @param rulerColumn the ruler column to be initialized
*/
protected void initializeLineNumberRulerColumn(LineNumberRulerColumn rulerColumn) {
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
IColorManager manager= textTools.getColorManager();
IPreferenceStore store= getPreferenceStore();
if (store != null) {
RGB rgb= null;
// foreground color
if (store.contains(LINE_NUMBER_COLOR)) {
if (store.isDefault(LINE_NUMBER_COLOR))
rgb= PreferenceConverter.getDefaultColor(store, LINE_NUMBER_COLOR);
else
rgb= PreferenceConverter.getColor(store, LINE_NUMBER_COLOR);
}
rulerColumn.setForeground(manager.getColor(rgb));
rgb= null;
// background color
if (!store.getBoolean(PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT)) {
if (store.contains(PREFERENCE_COLOR_BACKGROUND)) {
if (store.isDefault(PREFERENCE_COLOR_BACKGROUND))
rgb= PreferenceConverter.getDefaultColor(store, PREFERENCE_COLOR_BACKGROUND);
else
rgb= PreferenceConverter.getColor(store, PREFERENCE_COLOR_BACKGROUND);
}
}
rulerColumn.setBackground(manager.getColor(rgb));
rulerColumn.redraw();
}
}
/**
* Creates a new line number ruler column that is appropriately initialized.
*
* @return a new line number ruler column
*/
protected IVerticalRulerColumn createLineNumberRulerColumn() {
if (isQuickDiffAlwaysOn() || isChangeInformationShowing()) {
LineNumberChangeRulerColumn column= new LineNumberChangeRulerColumn();
column.setHover(new JavaChangeHover(IJavaPartitions.JAVA_PARTITIONING));
initializeChangeRulerColumn(column);
fLineNumberRulerColumn= column;
} else {
fLineNumberRulerColumn= new LineNumberRulerColumn();
}
initializeLineNumberRulerColumn(fLineNumberRulerColumn);
return fLineNumberRulerColumn;
}
/**
* Initializes the given change ruler column from the preference store.
*
* @param changeColumn the ruler column to be initialized
* @since R3.0
*/
private void initializeChangeRulerColumn(IChangeRulerColumn changeColumn) {
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
IColorManager manager= textTools.getColorManager();
IPreferenceStore store= getPreferenceStore();
if (store != null) {
RGB rgb= null;
ISourceViewer v= getSourceViewer();
if (v != null && v.getAnnotationModel() != null) {
changeColumn.setModel(v.getAnnotationModel());
}
rgb= null;
// change color
if (!store.getBoolean(PreferenceConstants.QUICK_DIFF_CHANGED_COLOR)) {
if (store.contains(PreferenceConstants.QUICK_DIFF_CHANGED_COLOR)) {
if (store.isDefault(PreferenceConstants.QUICK_DIFF_CHANGED_COLOR))
rgb= PreferenceConverter.getDefaultColor(store, PreferenceConstants.QUICK_DIFF_CHANGED_COLOR);
else
rgb= PreferenceConverter.getColor(store, PreferenceConstants.QUICK_DIFF_CHANGED_COLOR);
}
}
changeColumn.setChangedColor(manager.getColor(rgb));
rgb= null;
// addition color
if (!store.getBoolean(PreferenceConstants.QUICK_DIFF_ADDED_COLOR)) {
if (store.contains(PreferenceConstants.QUICK_DIFF_ADDED_COLOR)) {
if (store.isDefault(PreferenceConstants.QUICK_DIFF_ADDED_COLOR))
rgb= PreferenceConverter.getDefaultColor(store, PreferenceConstants.QUICK_DIFF_ADDED_COLOR);
else
rgb= PreferenceConverter.getColor(store, PreferenceConstants.QUICK_DIFF_ADDED_COLOR);
}
}
changeColumn.setAddedColor(manager.getColor(rgb));
rgb= null;
// deletion indicator color
if (!store.getBoolean(PreferenceConstants.QUICK_DIFF_DELETED_COLOR)) {
if (store.contains(PreferenceConstants.QUICK_DIFF_DELETED_COLOR)) {
if (store.isDefault(PreferenceConstants.QUICK_DIFF_DELETED_COLOR))
rgb= PreferenceConverter.getDefaultColor(store, PreferenceConstants.QUICK_DIFF_DELETED_COLOR);
else
rgb= PreferenceConverter.getColor(store, PreferenceConstants.QUICK_DIFF_DELETED_COLOR);
}
}
changeColumn.setDeletedColor(manager.getColor(rgb));
}
changeColumn.redraw();
}
/**
* Creates a new change ruler column for quick diff display independent of the
* line number ruler column
*
* @return a new change ruler column
* @since R3.0
*/
protected IChangeRulerColumn createChangeRulerColumn() {
IChangeRulerColumn column= new ChangeRulerColumn();
column.setHover(new JavaChangeHover(IJavaPartitions.JAVA_PARTITIONING));
fChangeRulerColumn= column;
initializeChangeRulerColumn(fChangeRulerColumn);
return fChangeRulerColumn;
}
/*
* @see AbstractTextEditor#createVerticalRuler()
*/
protected IVerticalRuler createVerticalRuler() {
CompositeRuler ruler= new CompositeRuler();
ruler.addDecorator(0, new AnnotationRulerColumn(VERTICAL_RULER_WIDTH));
if (isLineNumberRulerVisible())
ruler.addDecorator(1, createLineNumberRulerColumn());
else if (isQuickDiffAlwaysOn())
ruler.addDecorator(1, createChangeRulerColumn());
return ruler;
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#updatePropertyDependentActions()
*/
protected void updatePropertyDependentActions() {
super.updatePropertyDependentActions();
if (fEncodingSupport != null)
fEncodingSupport.reset();
}
/*
* 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);
}
}
/*
* @see org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput()
*/
public Object getViewPartInput() {
return getEditorInput().getAdapter(IJavaElement.class);
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#doSetSelection(ISelection)
*/
protected void doSetSelection(ISelection selection) {
super.doSetSelection(selection);
synchronizeOutlinePageSelection();
}
/*
* @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite)
*/
public void createPartControl(Composite parent) {
super.createPartControl(parent);
fSourceViewerDecorationSupport.install(getPreferenceStore());
Preferences preferences= JavaCore.getPlugin().getPluginPreferences();
preferences.addPropertyChangeListener(fPropertyChangeListener);
IInformationControlCreator informationControlCreator= new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell shell) {
boolean cutDown= false;
int style= cutDown ? SWT.NONE : (SWT.V_SCROLL | SWT.H_SCROLL);
return new DefaultInformationControl(shell, SWT.RESIZE, style, new HTMLTextPresenter(cutDown));
}
};
fInformationPresenter= new InformationPresenter(informationControlCreator);
fInformationPresenter.setSizeConstraints(60, 10, true, true);
fInformationPresenter.install(getSourceViewer());
if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE)) {
fEditorSelectionChangedListener= new EditorSelectionChangedListener();
fEditorSelectionChangedListener.install(getSelectionProvider());
}
if (isBrowserLikeLinks())
enableBrowserLikeLinks();
if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE))
configureInsertMode(OVERWRITE, false);
if (isQuickDiffAlwaysOn())
showChangeInformation(true);
}
protected void showOverviewRuler() {
if (fOverviewRuler != null) {
if (getSourceViewer() instanceof ISourceViewerExtension) {
((ISourceViewerExtension) getSourceViewer()).showAnnotationsOverview(true);
fSourceViewerDecorationSupport.updateOverviewDecorations();
}
}
}
protected void hideOverviewRuler() {
if (getSourceViewer() instanceof ISourceViewerExtension) {
fSourceViewerDecorationSupport.hideAnnotationOverview();
((ISourceViewerExtension) getSourceViewer()).showAnnotationsOverview(false);
}
}
protected boolean isOverviewRulerVisible() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(OVERVIEW_RULER);
}
protected void configureSourceViewerDecorationSupport() {
Iterator e= fAnnotationPreferences.getAnnotationPreferences().iterator();
while (e.hasNext())
fSourceViewerDecorationSupport.setAnnotationPreference((AnnotationPreference) e.next());
fSourceViewerDecorationSupport.setCharacterPairMatcher(fBracketMatcher);
fSourceViewerDecorationSupport.setCursorLinePainterPreferenceKeys(CURRENT_LINE, CURRENT_LINE_COLOR);
fSourceViewerDecorationSupport.setMarginPainterPreferenceKeys(PRINT_MARGIN, PRINT_MARGIN_COLOR, PRINT_MARGIN_COLUMN);
fSourceViewerDecorationSupport.setMatchingCharacterPainterPreferenceKeys(MATCHING_BRACKETS, MATCHING_BRACKETS_COLOR);
fSourceViewerDecorationSupport.setSymbolicFontName(getFontPropertyPreferenceKey());
}
/**
* Jumps to the matching bracket.
*/
public void gotoMatchingBracket() {
ISourceViewer sourceViewer= getSourceViewer();
IDocument document= sourceViewer.getDocument();
if (document == null)
return;
IRegion selection= getSignedSelection(sourceViewer);
int selectionLength= Math.abs(selection.getLength());
if (selectionLength > 1) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.invalidSelection")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
// #26314
int sourceCaretOffset= selection.getOffset() + selection.getLength();
if (isSurroundedByBrackets(document, sourceCaretOffset))
sourceCaretOffset -= selection.getLength();
IRegion region= fBracketMatcher.match(document, sourceCaretOffset);
if (region == null) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.noMatchingBracket")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
int offset= region.getOffset();
int length= region.getLength();
if (length < 1)
return;
int anchor= fBracketMatcher.getAnchor();
// http://dev.eclipse.org/bugs/show_bug.cgi?id=34195
int targetOffset= (JavaPairMatcher.RIGHT == anchor) ? offset + 1: offset + length;
boolean visible= false;
if (sourceViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) sourceViewer;
visible= (extension.modelOffset2WidgetOffset(targetOffset) > -1);
} else {
IRegion visibleRegion= sourceViewer.getVisibleRegion();
// http://dev.eclipse.org/bugs/show_bug.cgi?id=34195
visible= (targetOffset >= visibleRegion.getOffset() && targetOffset <= visibleRegion.getOffset() + visibleRegion.getLength());
}
if (!visible) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.bracketOutsideSelectedElement")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
if (selection.getLength() < 0)
targetOffset -= selection.getLength();
sourceViewer.setSelectedRange(targetOffset, selection.getLength());
sourceViewer.revealRange(targetOffset, selection.getLength());
}
/**
* Ses the given message as error message to this editor's status line.
* @param msg message to be set
*/
protected void setStatusLineErrorMessage(String msg) {
IEditorStatusLine statusLine= (IEditorStatusLine) getAdapter(IEditorStatusLine.class);
if (statusLine != null)
statusLine.setMessage(true, msg, null);
}
private static IRegion getSignedSelection(ITextViewer viewer) {
StyledText text= viewer.getTextWidget();
int caretOffset= text.getCaretOffset();
Point selection= text.getSelection();
// caret left
int offset, length;
if (caretOffset == selection.x) {
offset= selection.y;
length= selection.x - selection.y;
// caret right
} else {
offset= selection.x;
length= selection.y - selection.x;
}
return new Region(offset, length);
}
private static boolean isBracket(char character) {
for (int i= 0; i != BRACKETS.length; ++i)
if (character == BRACKETS[i])
return true;
return false;
}
private static boolean isSurroundedByBrackets(IDocument document, int offset) {
if (offset == 0 || offset == document.getLength())
return false;
try {
return
isBracket(document.getChar(offset - 1)) &&
isBracket(document.getChar(offset));
} catch (BadLocationException e) {
return false;
}
}
/**
* Jumps to the next enabled annotation according to the given direction.
* An annotation type is enabled if it is configured to be in the
* Next/Previous tool bar drop down menu and if it is checked.
*/
public void gotoAnnotation(boolean forward) {
ISelectionProvider provider= getSelectionProvider();
ITextSelection s= (ITextSelection) provider.getSelection();
Position annotationPosition= new Position(0, 0);
IJavaAnnotation nextAnnotation= getNextAnnotation(s.getOffset(), forward, annotationPosition);
setStatusLineErrorMessage(null);
if (nextAnnotation != null) {
IMarker marker= null;
if (nextAnnotation instanceof MarkerAnnotation)
marker= ((MarkerAnnotation) nextAnnotation).getMarker();
else {
Iterator e= nextAnnotation.getOverlaidIterator();
if (e != null) {
while (e.hasNext()) {
Object o= e.next();
if (o instanceof MarkerAnnotation) {
marker= ((MarkerAnnotation) o).getMarker();
break;
}
}
}
}
if (marker != null) {
IWorkbenchPage page= getSite().getPage();
IViewPart view= view= page.findView("org.eclipse.ui.views.TaskList"); //$NON-NLS-1$
if (view instanceof TaskList) {
StructuredSelection ss= new StructuredSelection(marker);
((TaskList) view).setSelection(ss, true);
}
}
selectAndReveal(annotationPosition.getOffset(), annotationPosition.getLength());
if (nextAnnotation.isProblem())
setStatusLineErrorMessage(nextAnnotation.getMessage());
}
}
private IJavaAnnotation getNextAnnotation(int offset, boolean forward, Position annotationPosition) {
IJavaAnnotation nextAnnotation= null;
Position nextAnnotationPosition= null;
IDocument document= getDocumentProvider().getDocument(getEditorInput());
int endOfDocument= document.getLength();
int distance= 0;
IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput());
Iterator e= new JavaAnnotationIterator(model, true);
while (e.hasNext()) {
IJavaAnnotation a= (IJavaAnnotation) e.next();
Preferences workbenchTextEditorPrefStore= Platform.getPlugin("org.eclipse.ui.workbench.texteditor").getPluginPreferences(); //$NON-NLS-1$
Iterator iter= fAnnotationPreferences.getAnnotationPreferences().iterator();
boolean isNavigationTarget= false;
while (iter.hasNext()) {
AnnotationPreference annotationPref= (AnnotationPreference)iter.next();
if (annotationPref.getAnnotationType().equals(a.getAnnotationType())) {
String key;
if (forward)
key= annotationPref.getIsGoToNextNavigationTargetKey();
else
key= annotationPref.getIsGoToPreviousNavigationTargetKey();
if (key != null)
isNavigationTarget= workbenchTextEditorPrefStore.getBoolean(key);
break;
}
annotationPref= null;
}
if (a.hasOverlay() || !isNavigationTarget)
continue;
Position p= model.getPosition((Annotation) a);
if (!(p.includes(offset) || (p.getLength() == 0 && offset == p.offset))) {
int currentDistance= 0;
if (forward) {
currentDistance= p.getOffset() - offset;
if (currentDistance < 0)
currentDistance= endOfDocument - offset + p.getOffset();
} else {
currentDistance= offset - p.getOffset();
if (currentDistance < 0)
currentDistance= offset + endOfDocument - p.getOffset();
}
if (nextAnnotation == null || currentDistance < distance) {
distance= currentDistance;
nextAnnotation= a;
nextAnnotationPosition= p;
}
}
}
if (nextAnnotationPosition != null) {
annotationPosition.setOffset(nextAnnotationPosition.getOffset());
annotationPosition.setLength(nextAnnotationPosition.getLength());
}
return nextAnnotation;
}
/**
* Computes and returns the source reference that includes the caret and
* serves as provider for the outline page selection and the editor range
* indication.
*
* @return the computed source reference
* @since 3.0
*/
protected ISourceReference computeHighlightRangeSourceReference() {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return null;
StyledText styledText= sourceViewer.getTextWidget();
if (styledText == null)
return null;
int caret= 0;
if (sourceViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3)sourceViewer;
caret= extension.widgetOffset2ModelOffset(styledText.getCaretOffset());
} else {
int offset= sourceViewer.getVisibleRegion().getOffset();
caret= offset + styledText.getCaretOffset();
}
IJavaElement element= getElementAt(caret, false);
if ( !(element instanceof ISourceReference))
return null;
if (element.getElementType() == IJavaElement.IMPORT_DECLARATION) {
IImportDeclaration declaration= (IImportDeclaration) element;
IImportContainer container= (IImportContainer) declaration.getParent();
ISourceRange srcRange= null;
try {
srcRange= container.getSourceRange();
} catch (JavaModelException e) {
}
if (srcRange != null && srcRange.getOffset() == caret)
return container;
}
return (ISourceReference) element;
}
/**
* Returns the most narrow java element including the given offset.
*
* @param offset the offset inside of the requested element
* @param reconcile <code>true</code> if editor input should be reconciled in advance
* @return the most narrow java element
* @since 3.0
*/
protected IJavaElement getElementAt(int offset, boolean reconcile) {
return getElementAt(offset);
}
}
|
41,313 |
Bug 41313 "Link with Editor" in Java Outline should link on activation
|
I normally work with "Link with Editor" switched off. When editing a long method whose head is out of view, I want to know in which method I am without leaving the editing position. I'd like to *double*click on "Link with Editor" in the Java Outline to synchronize it with the current position (the second click just disables "Link with Editor" again). This works nicely with the Package Explorer, where a doubleclick on "Link with Editor" reveals the current file. I think this doubleclick behavior should be consistently supported by all "Link with Editor" actions.
|
resolved fixed
|
ab0f11e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-18T08:36:43Z | 2003-08-08T08:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/JavaOutlinePage.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.javaeditor;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;
import java.util.Vector;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Item;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.Assert;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.ListenerList;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.IBaseLabelProvider;
import org.eclipse.jface.viewers.IPostSelectionProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProviderChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.internal.model.WorkbenchAdapter;
import org.eclipse.ui.model.IWorkbenchAdapter;
import org.eclipse.ui.part.IPageSite;
import org.eclipse.ui.part.IShowInSource;
import org.eclipse.ui.part.IShowInTarget;
import org.eclipse.ui.part.IShowInTargetList;
import org.eclipse.ui.part.Page;
import org.eclipse.ui.part.ShowInContext;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
import org.eclipse.ui.texteditor.IUpdate;
import org.eclipse.ui.texteditor.TextEditorAction;
import org.eclipse.ui.texteditor.TextOperationAction;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
import org.eclipse.jdt.core.ElementChangedEvent;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IElementChangedListener;
import org.eclipse.jdt.core.IInitializer;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaElementDelta;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IParent;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.ISourceReference;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.JavaElementSorter;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.ProblemsLabelDecorator.ProblemsLabelChangedEvent;
import org.eclipse.jdt.ui.actions.CCPActionGroup;
import org.eclipse.jdt.ui.actions.GenerateActionGroup;
import org.eclipse.jdt.ui.actions.JavaSearchActionGroup;
import org.eclipse.jdt.ui.actions.JdtActionConstants;
import org.eclipse.jdt.ui.actions.MemberFilterActionGroup;
import org.eclipse.jdt.ui.actions.OpenViewActionGroup;
import org.eclipse.jdt.ui.actions.RefactorActionGroup;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.actions.AbstractToggleLinkingAction;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.dnd.DelegatingDropAdapter;
import org.eclipse.jdt.internal.ui.dnd.JdtViewerDragAdapter;
import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer;
import org.eclipse.jdt.internal.ui.dnd.TransferDragSourceListener;
import org.eclipse.jdt.internal.ui.dnd.TransferDropTargetListener;
import org.eclipse.jdt.internal.ui.packageview.SelectionTransferDragAdapter;
import org.eclipse.jdt.internal.ui.packageview.SelectionTransferDropAdapter;
import org.eclipse.jdt.internal.ui.viewsupport.AppearanceAwareLabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.DecoratingJavaLabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater;
/**
* The content outline page of the Java editor. The viewer implements a proprietary
* update mechanism based on Java model deltas. It does not react on domain changes.
* It is specified to show the content of ICompilationUnits and IClassFiles.
* Pulishes its context menu under <code>JavaPlugin.getDefault().getPluginId() + ".outline"</code>.
*/
public class JavaOutlinePage extends Page implements IContentOutlinePage, IAdaptable , IPostSelectionProvider {
static Object[] NO_CHILDREN= new Object[0];
/**
* The element change listener of the java outline viewer.
* @see IElementChangedListener
*/
class ElementChangedListener implements IElementChangedListener {
public void elementChanged(final ElementChangedEvent e) {
if (getControl() == null)
return;
Display d= getControl().getDisplay();
if (d != null) {
d.asyncExec(new Runnable() {
public void run() {
ICompilationUnit cu= (ICompilationUnit) fInput;
IJavaElement base= cu;
if (fTopLevelTypeOnly) {
base= getMainType(cu);
if (base == null) {
if (fOutlineViewer != null)
fOutlineViewer.refresh(true);
return;
}
}
IJavaElementDelta delta= findElement(base, e.getDelta());
if (delta != null && fOutlineViewer != null) {
fOutlineViewer.reconcile(delta);
}
}
});
}
}
protected IJavaElementDelta findElement(IJavaElement unit, IJavaElementDelta delta) {
if (delta == null || unit == null)
return null;
IJavaElement element= delta.getElement();
if (unit.equals(element))
return delta;
if (element.getElementType() > IJavaElement.CLASS_FILE)
return null;
IJavaElementDelta[] children= delta.getAffectedChildren();
if (children == null || children.length == 0)
return null;
for (int i= 0; i < children.length; i++) {
IJavaElementDelta d= findElement(unit, children[i]);
if (d != null)
return d;
}
return null;
}
}
static class NoClassElement extends WorkbenchAdapter implements IAdaptable {
/*
* @see java.lang.Object#toString()
*/
public String toString() {
return JavaEditorMessages.getString("JavaOutlinePage.error.NoTopLevelType"); //$NON-NLS-1$
}
/*
* @see org.eclipse.core.runtime.IAdaptable#getAdapter(Class)
*/
public Object getAdapter(Class clas) {
if (clas == IWorkbenchAdapter.class)
return this;
return null;
}
}
/**
* Content provider for the children of an ICompilationUnit or
* an IClassFile
* @see ITreeContentProvider
*/
class ChildrenProvider implements ITreeContentProvider {
private Object[] NO_CLASS= new Object[] {new NoClassElement()};
private ElementChangedListener fListener;
protected boolean matches(IJavaElement element) {
if (element.getElementType() == IJavaElement.METHOD) {
String name= element.getElementName();
return (name != null && name.indexOf('<') >= 0);
}
return false;
}
protected IJavaElement[] filter(IJavaElement[] children) {
boolean initializers= false;
for (int i= 0; i < children.length; i++) {
if (matches(children[i])) {
initializers= true;
break;
}
}
if (!initializers)
return children;
Vector v= new Vector();
for (int i= 0; i < children.length; i++) {
if (matches(children[i]))
continue;
v.addElement(children[i]);
}
IJavaElement[] result= new IJavaElement[v.size()];
v.copyInto(result);
return result;
}
public Object[] getChildren(Object parent) {
if (parent instanceof IParent) {
IParent c= (IParent) parent;
try {
return filter(c.getChildren());
} catch (JavaModelException x) {
JavaPlugin.log(x);
}
}
return NO_CHILDREN;
}
public Object[] getElements(Object parent) {
if (fTopLevelTypeOnly) {
if (parent instanceof ICompilationUnit) {
try {
IType type= getMainType((ICompilationUnit) parent);
return type != null ? type.getChildren() : NO_CLASS;
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
} else if (parent instanceof IClassFile) {
try {
IType type= getMainType((IClassFile) parent);
return type != null ? type.getChildren() : NO_CLASS;
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
}
return getChildren(parent);
}
public Object getParent(Object child) {
if (child instanceof IJavaElement) {
IJavaElement e= (IJavaElement) child;
return e.getParent();
}
return null;
}
public boolean hasChildren(Object parent) {
if (parent instanceof IParent) {
IParent c= (IParent) parent;
try {
IJavaElement[] children= filter(c.getChildren());
return (children != null && children.length > 0);
} catch (JavaModelException x) {
JavaPlugin.log(x);
}
}
return false;
}
public boolean isDeleted(Object o) {
return false;
}
public void dispose() {
if (fListener != null) {
JavaCore.removeElementChangedListener(fListener);
fListener= null;
}
}
/*
* @see IContentProvider#inputChanged(Viewer, Object, Object)
*/
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
boolean isCU= (newInput instanceof ICompilationUnit);
if (isCU && fListener == null) {
fListener= new ElementChangedListener();
JavaCore.addElementChangedListener(fListener);
} else if (!isCU && fListener != null) {
JavaCore.removeElementChangedListener(fListener);
fListener= null;
}
}
}
class JavaOutlineViewer extends TreeViewer {
/**
* Indicates an item which has been reused. At the point of
* its reuse it has been expanded. This field is used to
* communicate between <code>internalExpandToLevel</code> and
* <code>reuseTreeItem</code>.
*/
private Item fReusedExpandedItem;
private boolean fReorderedMembers;
public JavaOutlineViewer(Tree tree) {
super(tree);
setAutoExpandLevel(ALL_LEVELS);
setUseHashlookup(true);
}
/**
* Investigates the given element change event and if affected incrementally
* updates the outline.
*/
public void reconcile(IJavaElementDelta delta) {
fReorderedMembers= false;
if (getSorter() == null) {
if (fTopLevelTypeOnly
&& delta.getElement() instanceof IType
&& (delta.getKind() & IJavaElementDelta.ADDED) != 0)
{
refresh(true);
} else {
Widget w= findItem(fInput);
if (w != null && !w.isDisposed())
update(w, delta);
if (fReorderedMembers) {
refresh(false);
fReorderedMembers= false;
}
}
} else {
// just for now
refresh(true);
}
}
/*
* @see TreeViewer#internalExpandToLevel
*/
protected void internalExpandToLevel(Widget node, int level) {
if (node instanceof Item) {
Item i= (Item) node;
if (i.getData() instanceof IJavaElement) {
IJavaElement je= (IJavaElement) i.getData();
if (je.getElementType() == IJavaElement.IMPORT_CONTAINER || isInnerType(je)) {
if (i != fReusedExpandedItem) {
setExpanded(i, false);
return;
}
}
}
}
super.internalExpandToLevel(node, level);
}
protected void reuseTreeItem(Item item, Object element) {
// remove children
Item[] c= getChildren(item);
if (c != null && c.length > 0) {
if (getExpanded(item))
fReusedExpandedItem= item;
for (int k= 0; k < c.length; k++) {
if (c[k].getData() != null)
disassociate(c[k]);
c[k].dispose();
}
}
updateItem(item, element);
updatePlus(item, element);
internalExpandToLevel(item, ALL_LEVELS);
fReusedExpandedItem= null;
}
protected boolean mustUpdateParent(IJavaElementDelta delta, IJavaElement element) {
if (element instanceof IMethod) {
if ((delta.getKind() & IJavaElementDelta.ADDED) != 0) {
try {
return ((IMethod)element).isMainMethod();
} catch (JavaModelException e) {
JavaPlugin.log(e.getStatus());
}
}
return "main".equals(element.getElementName()); //$NON-NLS-1$
}
return false;
}
protected ISourceRange getSourceRange(IJavaElement element) throws JavaModelException {
if (element instanceof ISourceReference)
return ((ISourceReference) element).getSourceRange();
if (element instanceof IMember && !(element instanceof IInitializer))
return ((IMember) element).getNameRange();
return null;
}
protected boolean overlaps(ISourceRange range, int start, int end) {
return start <= (range.getOffset() + range.getLength() - 1) && range.getOffset() <= end;
}
protected boolean filtered(IJavaElement parent, IJavaElement child) {
Object[] result= new Object[] { child };
ViewerFilter[] filters= getFilters();
for (int i= 0; i < filters.length; i++) {
result= filters[i].filter(this, parent, result);
if (result.length == 0)
return true;
}
return false;
}
protected void update(Widget w, IJavaElementDelta delta) {
Item item;
IJavaElement parent= delta.getElement();
IJavaElementDelta[] affected= delta.getAffectedChildren();
Item[] children= getChildren(w);
boolean doUpdateParent= false;
boolean doUpdateParentsPlus= false;
Vector deletions= new Vector();
Vector additions= new Vector();
for (int i= 0; i < affected.length; i++) {
IJavaElementDelta affectedDelta= affected[i];
IJavaElement affectedElement= affectedDelta.getElement();
int status= affected[i].getKind();
// find tree item with affected element
int j;
for (j= 0; j < children.length; j++)
if (affectedElement.equals(children[j].getData()))
break;
if (j == children.length) {
// remove from collapsed parent
if ((status & IJavaElementDelta.REMOVED) != 0) {
doUpdateParentsPlus= true;
continue;
}
// addition
if ((status & IJavaElementDelta.CHANGED) != 0 &&
(affectedDelta.getFlags() & IJavaElementDelta.F_MODIFIERS) != 0 &&
!filtered(parent, affectedElement))
{
additions.addElement(affectedDelta);
}
continue;
}
item= children[j];
// removed
if ((status & IJavaElementDelta.REMOVED) != 0) {
deletions.addElement(item);
doUpdateParent= doUpdateParent || mustUpdateParent(affectedDelta, affectedElement);
// changed
} else if ((status & IJavaElementDelta.CHANGED) != 0) {
int change= affectedDelta.getFlags();
doUpdateParent= doUpdateParent || mustUpdateParent(affectedDelta, affectedElement);
if ((change & IJavaElementDelta.F_MODIFIERS) != 0) {
if (filtered(parent, affectedElement))
deletions.addElement(item);
else
updateItem(item, affectedElement);
}
if ((change & IJavaElementDelta.F_CONTENT) != 0)
updateItem(item, affectedElement);
if ((change & IJavaElementDelta.F_CHILDREN) != 0)
update(item, affectedDelta);
if ((change & IJavaElementDelta.F_REORDER) != 0)
fReorderedMembers= true;
}
}
// find all elements to add
IJavaElementDelta[] add= delta.getAddedChildren();
if (additions.size() > 0) {
IJavaElementDelta[] tmp= new IJavaElementDelta[add.length + additions.size()];
System.arraycopy(add, 0, tmp, 0, add.length);
for (int i= 0; i < additions.size(); i++)
tmp[i + add.length]= (IJavaElementDelta) additions.elementAt(i);
add= tmp;
}
// add at the right position
go2: for (int i= 0; i < add.length; i++) {
try {
IJavaElement e= add[i].getElement();
if (filtered(parent, e))
continue go2;
doUpdateParent= doUpdateParent || mustUpdateParent(add[i], e);
ISourceRange rng= getSourceRange(e);
int start= rng.getOffset();
int end= start + rng.getLength() - 1;
Item last= null;
item= null;
children= getChildren(w);
for (int j= 0; j < children.length; j++) {
item= children[j];
IJavaElement r= (IJavaElement) item.getData();
if (r == null) {
// parent node collapsed and not be opened before -> do nothing
continue go2;
}
try {
rng= getSourceRange(r);
if (overlaps(rng, start, end)) {
// be tolerant if the delta is not correct, or if
// the tree has been updated other than by a delta
reuseTreeItem(item, e);
continue go2;
} else if (rng.getOffset() > start) {
if (last != null && deletions.contains(last)) {
// reuse item
deletions.removeElement(last);
reuseTreeItem(last, e);
} else {
// nothing to reuse
createTreeItem(w, e, j);
}
continue go2;
}
} catch (JavaModelException x) {
// stumbled over deleted element
}
last= item;
}
// add at the end of the list
if (last != null && deletions.contains(last)) {
// reuse item
deletions.removeElement(last);
reuseTreeItem(last, e);
} else {
// nothing to reuse
createTreeItem(w, e, -1);
}
} catch (JavaModelException x) {
// the element to be added is not present -> don't add it
}
}
// remove items which haven't been reused
Enumeration e= deletions.elements();
while (e.hasMoreElements()) {
item= (Item) e.nextElement();
disassociate(item);
item.dispose();
}
if (doUpdateParent)
updateItem(w, delta.getElement());
if (!doUpdateParent && doUpdateParentsPlus && w instanceof Item)
updatePlus((Item)w, delta.getElement());
}
/*
* @see ContentViewer#handleLabelProviderChanged(LabelProviderChangedEvent)
*/
protected void handleLabelProviderChanged(LabelProviderChangedEvent event) {
Object input= getInput();
if (event instanceof ProblemsLabelChangedEvent) {
ProblemsLabelChangedEvent e= (ProblemsLabelChangedEvent) event;
if (e.isMarkerChange() && input instanceof ICompilationUnit) {
return; // marker changes can be ignored
}
}
// look if the underlying resource changed
Object[] changed= event.getElements();
if (changed != null) {
IResource resource= getUnderlyingResource();
if (resource != null) {
for (int i= 0; i < changed.length; i++) {
if (changed[i] != null && changed[i].equals(resource)) {
// change event to a full refresh
event= new LabelProviderChangedEvent((IBaseLabelProvider) event.getSource());
break;
}
}
}
}
super.handleLabelProviderChanged(event);
}
private IResource getUnderlyingResource() {
Object input= getInput();
if (input instanceof ICompilationUnit) {
ICompilationUnit cu= (ICompilationUnit) input;
cu= JavaModelUtil.toOriginal(cu);
return cu.getResource();
} else if (input instanceof IClassFile) {
return ((IClassFile) input).getResource();
}
return null;
}
}
class LexicalSortingAction extends Action {
private JavaElementSorter fSorter= new JavaElementSorter();
public LexicalSortingAction() {
super();
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.LEXICAL_SORTING_OUTLINE_ACTION);
setText(JavaEditorMessages.getString("JavaOutlinePage.Sort.label")); //$NON-NLS-1$
JavaPluginImages.setLocalImageDescriptors(this, "alphab_sort_co.gif"); //$NON-NLS-1$
setToolTipText(JavaEditorMessages.getString("JavaOutlinePage.Sort.tooltip")); //$NON-NLS-1$
setDescription(JavaEditorMessages.getString("JavaOutlinePage.Sort.description")); //$NON-NLS-1$
boolean checked= JavaPlugin.getDefault().getPreferenceStore().getBoolean("LexicalSortingAction.isChecked"); //$NON-NLS-1$
valueChanged(checked, false);
}
public void run() {
valueChanged(isChecked(), true);
}
private void valueChanged(final boolean on, boolean store) {
setChecked(on);
BusyIndicator.showWhile(fOutlineViewer.getControl().getDisplay(), new Runnable() {
public void run() {
fOutlineViewer.setSorter(on ? fSorter : null); }
});
if (store)
JavaPlugin.getDefault().getPreferenceStore().setValue("LexicalSortingAction.isChecked", on); //$NON-NLS-1$
}
}
class ClassOnlyAction extends Action {
public ClassOnlyAction() {
super();
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.GO_INTO_TOP_LEVEL_TYPE_ACTION);
setText(JavaEditorMessages.getString("JavaOutlinePage.GoIntoTopLevelType.label")); //$NON-NLS-1$
setToolTipText(JavaEditorMessages.getString("JavaOutlinePage.GoIntoTopLevelType.tooltip")); //$NON-NLS-1$
setDescription(JavaEditorMessages.getString("JavaOutlinePage.GoIntoTopLevelType.description")); //$NON-NLS-1$
JavaPluginImages.setLocalImageDescriptors(this, "gointo_toplevel_type.gif"); //$NON-NLS-1$
IPreferenceStore preferenceStore= JavaPlugin.getDefault().getPreferenceStore();
boolean showclass= preferenceStore.getBoolean("GoIntoTopLevelTypeAction.isChecked"); //$NON-NLS-1$
setTopLevelTypeOnly(showclass);
}
/*
* @see org.eclipse.jface.action.Action#run()
*/
public void run() {
setTopLevelTypeOnly(!fTopLevelTypeOnly);
}
private void setTopLevelTypeOnly(boolean show) {
fTopLevelTypeOnly= show;
setChecked(show);
fOutlineViewer.refresh(false);
IPreferenceStore preferenceStore= JavaPlugin.getDefault().getPreferenceStore();
preferenceStore.setValue("GoIntoTopLevelTypeAction.isChecked", show); //$NON-NLS-1$
}
}
/**
* This action toggles whether this Java Outline page links
* its selection to the active editor.
*
* @since 3.0
*/
public class ToggleLinkingAction extends AbstractToggleLinkingAction {
JavaOutlinePage fJavaOutlinePage;
/**
* Constructs a new action.
*/
public ToggleLinkingAction(JavaOutlinePage outlinePage) {
boolean isLinkingEnabled= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE);
setChecked(isLinkingEnabled);
fJavaOutlinePage= outlinePage;
}
/**
* Runs the action.
*/
public void run() {
PreferenceConstants.getPreferenceStore().setValue(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE, isChecked());
}
}
/** A flag to show contents of top level type only */
private boolean fTopLevelTypeOnly;
private IJavaElement fInput;
private String fContextMenuID;
private Menu fMenu;
private JavaOutlineViewer fOutlineViewer;
private JavaEditor fEditor;
private MemberFilterActionGroup fMemberFilterActionGroup;
private ListenerList fSelectionChangedListeners= new ListenerList();
private ListenerList fPostSelectionChangedListeners= new ListenerList();
private Hashtable fActions= new Hashtable();
private TogglePresentationAction fTogglePresentation;
private GotoAnnotationAction fPreviousAnnotation;
private GotoAnnotationAction fNextAnnotation;
private TextEditorAction fShowJavadoc;
private TextOperationAction fUndo;
private TextOperationAction fRedo;
private ToggleLinkingAction fToggleLinkingAction;
private CompositeActionGroup fActionGroups;
private CCPActionGroup fCCPActionGroup;
private IPropertyChangeListener fPropertyChangeListener;
public JavaOutlinePage(String contextMenuID, JavaEditor editor) {
super();
Assert.isNotNull(editor);
fContextMenuID= contextMenuID;
fEditor= editor;
fTogglePresentation= new TogglePresentationAction();
fPreviousAnnotation= new GotoAnnotationAction("PreviousAnnotation.", false); //$NON-NLS-1$
fNextAnnotation= new GotoAnnotationAction("NextAnnotation.", true); //$NON-NLS-1$
fShowJavadoc= (TextEditorAction) fEditor.getAction("ShowJavaDoc"); //$NON-NLS-1$
fUndo= (TextOperationAction) fEditor.getAction(ITextEditorActionConstants.UNDO);
fRedo= (TextOperationAction) fEditor.getAction(ITextEditorActionConstants.REDO);
fTogglePresentation.setEditor(editor);
fPreviousAnnotation.setEditor(editor);
fNextAnnotation.setEditor(editor);
fPropertyChangeListener= new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
doPropertyChange(event);
}
};
JavaPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(fPropertyChangeListener);
}
/**
* Returns the primary type of a compilation unit (has the same
* name as the compilation unit).
*
* @param compilationUnit the compilation unit
* @return returns the primary type of the compilation unit, or
* <code>null</code> if is does not have one
*/
protected IType getMainType(ICompilationUnit compilationUnit) {
if (compilationUnit == null)
return null;
String name= compilationUnit.getElementName();
int index= name.indexOf('.');
if (index != -1)
name= name.substring(0, index);
IType type= compilationUnit.getType(name);
return type.exists() ? type : null;
}
/**
* Returns the primary type of a class file.
*
* @param classFile the class file
* @return returns the primary type of the class file, or <code>null</code>
* if is does not have one
*/
protected IType getMainType(IClassFile classFile) {
try {
IType type= classFile.getType();
return type != null && type.exists() ? type : null;
} catch (JavaModelException e) {
return null;
}
}
/* (non-Javadoc)
* Method declared on Page
*/
public void init(IPageSite pageSite) {
super.init(pageSite);
}
private void doPropertyChange(PropertyChangeEvent event) {
if (fOutlineViewer != null) {
if (PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER.equals(event.getProperty())) {
fOutlineViewer.refresh(false);
}
}
}
/*
* @see ISelectionProvider#addSelectionChangedListener(ISelectionChangedListener)
*/
public void addSelectionChangedListener(ISelectionChangedListener listener) {
if (fOutlineViewer != null)
fOutlineViewer.addSelectionChangedListener(listener);
else
fSelectionChangedListeners.add(listener);
}
/*
* @see ISelectionProvider#removeSelectionChangedListener(ISelectionChangedListener)
*/
public void removeSelectionChangedListener(ISelectionChangedListener listener) {
if (fOutlineViewer != null)
fOutlineViewer.removeSelectionChangedListener(listener);
else
fSelectionChangedListeners.remove(listener);
}
/*
* @see ISelectionProvider#setSelection(ISelection)
*/
public void setSelection(ISelection selection) {
if (fOutlineViewer != null)
fOutlineViewer.setSelection(selection);
}
/*
* @see ISelectionProvider#getSelection()
*/
public ISelection getSelection() {
if (fOutlineViewer == null)
return StructuredSelection.EMPTY;
return fOutlineViewer.getSelection();
}
/*
* @see org.eclipse.jface.text.IPostSelectionProvider#addPostSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener)
*/
public void addPostSelectionChangedListener(ISelectionChangedListener listener) {
if (fOutlineViewer != null)
fOutlineViewer.addPostSelectionChangedListener(listener);
else
fPostSelectionChangedListeners.add(listener);
}
/*
* @see org.eclipse.jface.text.IPostSelectionProvider#removePostSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener)
*/
public void removePostSelectionChangedListener(ISelectionChangedListener listener) {
if (fOutlineViewer != null)
fOutlineViewer.removePostSelectionChangedListener(listener);
else
fPostSelectionChangedListeners.remove(listener);
}
private void registerToolbarActions() {
IToolBarManager toolBarManager= getSite().getActionBars().getToolBarManager();
if (toolBarManager != null) {
toolBarManager.add(new ClassOnlyAction());
toolBarManager.add(new LexicalSortingAction());
fMemberFilterActionGroup= new MemberFilterActionGroup(fOutlineViewer, "JavaOutlineViewer"); //$NON-NLS-1$
fMemberFilterActionGroup.contributeToToolBar(toolBarManager);
fToggleLinkingAction= new ToggleLinkingAction(this);
toolBarManager.add(fToggleLinkingAction);
}
}
/*
* @see IPage#createControl
*/
public void createControl(Composite parent) {
Tree tree= new Tree(parent, SWT.MULTI);
AppearanceAwareLabelProvider lprovider= new AppearanceAwareLabelProvider(
AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS | JavaElementLabels.F_APP_TYPE_SIGNATURE,
AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS
);
fOutlineViewer= new JavaOutlineViewer(tree);
initDragAndDrop();
fOutlineViewer.setContentProvider(new ChildrenProvider());
fOutlineViewer.setLabelProvider(new DecoratingJavaLabelProvider(lprovider));
Object[] listeners= fSelectionChangedListeners.getListeners();
for (int i= 0; i < listeners.length; i++) {
fSelectionChangedListeners.remove(listeners[i]);
fOutlineViewer.addSelectionChangedListener((ISelectionChangedListener) listeners[i]);
}
listeners= fPostSelectionChangedListeners.getListeners();
for (int i= 0; i < listeners.length; i++) {
fPostSelectionChangedListeners.remove(listeners[i]);
fOutlineViewer.addPostSelectionChangedListener((ISelectionChangedListener) listeners[i]);
}
MenuManager manager= new MenuManager(fContextMenuID, fContextMenuID);
manager.setRemoveAllWhenShown(true);
manager.addMenuListener(new IMenuListener() {
public void menuAboutToShow(IMenuManager m) {
contextMenuAboutToShow(m);
}
});
fMenu= manager.createContextMenu(tree);
tree.setMenu(fMenu);
IPageSite site= getSite();
site.registerContextMenu(JavaPlugin.getPluginId() + ".outline", manager, fOutlineViewer); //$NON-NLS-1$
site.setSelectionProvider(fOutlineViewer);
// we must create the groups after we have set the selection provider to the site
fActionGroups= new CompositeActionGroup(new ActionGroup[] {
new OpenViewActionGroup(this),
fCCPActionGroup= new CCPActionGroup(this),
new GenerateActionGroup(this),
new RefactorActionGroup(this),
new JavaSearchActionGroup(this)});
// register global actions
IActionBars bars= site.getActionBars();
bars.setGlobalActionHandler(ITextEditorActionConstants.UNDO, fUndo);
bars.setGlobalActionHandler(ITextEditorActionConstants.REDO, fRedo);
bars.setGlobalActionHandler(ITextEditorActionConstants.PREVIOUS, fPreviousAnnotation);
bars.setGlobalActionHandler(ITextEditorActionConstants.NEXT, fNextAnnotation);
bars.setGlobalActionHandler(JdtActionConstants.SHOW_JAVA_DOC, fShowJavadoc);
bars.setGlobalActionHandler(ITextEditorActionDefinitionIds.TOGGLE_SHOW_SELECTED_ELEMENT_ONLY, fTogglePresentation);
bars.setGlobalActionHandler(ITextEditorActionDefinitionIds.GOTO_NEXT_ANNOTATION, fNextAnnotation);
bars.setGlobalActionHandler(ITextEditorActionDefinitionIds.GOTO_PREVIOUS_ANNOTATION, fPreviousAnnotation);
fActionGroups.fillActionBars(bars);
IStatusLineManager statusLineManager= bars.getStatusLineManager();
if (statusLineManager != null) {
StatusBarUpdater updater= new StatusBarUpdater(statusLineManager);
fOutlineViewer.addPostSelectionChangedListener(updater);
}
registerToolbarActions();
fOutlineViewer.setInput(fInput);
fOutlineViewer.getControl().addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
handleKeyReleased(e);
}
});
}
public void dispose() {
if (fEditor == null)
return;
if (fMemberFilterActionGroup != null) {
fMemberFilterActionGroup.dispose();
fMemberFilterActionGroup= null;
}
fEditor.outlinePageClosed();
fEditor= null;
fSelectionChangedListeners.clear();
fSelectionChangedListeners= null;
fPostSelectionChangedListeners.clear();
fPostSelectionChangedListeners= null;
if (fPropertyChangeListener != null) {
JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(fPropertyChangeListener);
fPropertyChangeListener= null;
}
if (fMenu != null && !fMenu.isDisposed()) {
fMenu.dispose();
fMenu= null;
}
if (fActionGroups != null)
fActionGroups.dispose();
fTogglePresentation.setEditor(null);
fPreviousAnnotation.setEditor(null);
fNextAnnotation.setEditor(null);
fOutlineViewer= null;
super.dispose();
}
public Control getControl() {
if (fOutlineViewer != null)
return fOutlineViewer.getControl();
return null;
}
public void setInput(IJavaElement inputElement) {
fInput= inputElement;
if (fOutlineViewer != null)
fOutlineViewer.setInput(fInput);
}
public void select(ISourceReference reference) {
if (fOutlineViewer != null) {
ISelection s= fOutlineViewer.getSelection();
if (s instanceof IStructuredSelection) {
IStructuredSelection ss= (IStructuredSelection) s;
List elements= ss.toList();
if (!elements.contains(reference)) {
s= (reference == null ? StructuredSelection.EMPTY : new StructuredSelection(reference));
fOutlineViewer.setSelection(s, true);
}
}
}
}
public void setAction(String actionID, IAction action) {
Assert.isNotNull(actionID);
if (action == null)
fActions.remove(actionID);
else
fActions.put(actionID, action);
}
public IAction getAction(String actionID) {
Assert.isNotNull(actionID);
return (IAction) fActions.get(actionID);
}
/**
* Answer the property defined by key.
*/
public Object getAdapter(Class key) {
if (key == IShowInSource.class) {
return getShowInSource();
}
if (key == IShowInTargetList.class) {
return new IShowInTargetList() {
public String[] getShowInTargetIds() {
return new String[] { JavaUI.ID_PACKAGES };
}
};
}
if (key == IShowInTarget.class) {
return getShowInTarget();
}
return null;
}
/**
* Convenience method to add the action installed under the given actionID to the
* specified group of the menu.
*/
protected void addAction(IMenuManager menu, String group, String actionID) {
IAction action= getAction(actionID);
if (action != null) {
if (action instanceof IUpdate)
((IUpdate) action).update();
if (action.isEnabled()) {
IMenuManager subMenu= menu.findMenuUsingPath(group);
if (subMenu != null)
subMenu.add(action);
else
menu.appendToGroup(group, action);
}
}
}
protected void contextMenuAboutToShow(IMenuManager menu) {
JavaPlugin.createStandardGroups(menu);
IStructuredSelection selection= (IStructuredSelection)getSelection();
fActionGroups.setContext(new ActionContext(selection));
fActionGroups.fillContextMenu(menu);
}
/*
* @see Page#setFocus()
*/
public void setFocus() {
if (fOutlineViewer != null)
fOutlineViewer.getControl().setFocus();
}
/**
* Checkes whether a given Java element is an inner type.
*/
private boolean isInnerType(IJavaElement element) {
if (element != null && element.getElementType() == IJavaElement.TYPE) {
IType type= (IType)element;
try {
return type.isMember();
} catch (JavaModelException e) {
IJavaElement parent= type.getParent();
if (parent != null) {
int parentElementType= parent.getElementType();
return (parentElementType != IJavaElement.COMPILATION_UNIT && parentElementType != IJavaElement.CLASS_FILE);
}
}
}
return false;
}
/**
* Handles key events in viewer.
*/
private void handleKeyReleased(KeyEvent event) {
if (event.stateMask != 0)
return;
IAction action= null;
if (event.character == SWT.DEL) {
action= fCCPActionGroup.getDeleteAction();
}
if (action != null && action.isEnabled())
action.run();
}
/**
* Returns the <code>IShowInSource</code> for this view.
*/
protected IShowInSource getShowInSource() {
return new IShowInSource() {
public ShowInContext getShowInContext() {
return new ShowInContext(
null,
getSite().getSelectionProvider().getSelection());
}
};
}
/**
* Returns the <code>IShowInTarget</code> for this view.
*/
protected IShowInTarget getShowInTarget() {
return new IShowInTarget() {
public boolean show(ShowInContext context) {
ISelection sel= context.getSelection();
if (sel instanceof ITextSelection) {
ITextSelection tsel= (ITextSelection) sel;
int offset= tsel.getOffset();
IJavaElement element= fEditor.getElementAt(offset);
if (element != null) {
setSelection(new StructuredSelection(element));
return true;
}
}
return false;
}
};
}
private void initDragAndDrop() {
int ops= DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK;
Transfer[] transfers= new Transfer[] {
LocalSelectionTransfer.getInstance()
};
// Drop Adapter
TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] {
new SelectionTransferDropAdapter(fOutlineViewer)
};
fOutlineViewer.addDropSupport(ops | DND.DROP_DEFAULT, transfers, new DelegatingDropAdapter(dropListeners));
// Drag Adapter
TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] {
new SelectionTransferDragAdapter(fOutlineViewer)
};
fOutlineViewer.addDragSupport(ops, transfers, new JdtViewerDragAdapter(fOutlineViewer, dragListeners));
}
}
|
41,228 |
Bug 41228 Junit - HierachyRunView does not propagate status properly [JUnit]
|
Only the image is updated but not the status in the TestRunInfo.
|
closed fixed
|
fb8961b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-18T22:09:36Z | 2003-08-06T20:00:00Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/HierarchyRunView.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Sebastian Davids - [email protected] bug 26754
*******************************************************************************/
package org.eclipse.jdt.internal.junit.ui;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
import org.eclipse.jdt.junit.ITestRunListener;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
/*
* A view that shows the contents of a test suite
* as a tree.
*/
class HierarchyRunView implements ITestRunView, IMenuListener {
/**
* The tree widget
*/
private Tree fTree;
private TreeItem fCachedParent;
private TreeItem[] fCachedItems;
private boolean fMoveSelection= false;
/**
* Helper used to resurrect test hierarchy
*/
private static class SuiteInfo {
public int fTestCount;
public TreeItem fTreeItem;
public SuiteInfo(TreeItem treeItem, int testCount){
fTreeItem= treeItem;
fTestCount= testCount;
}
}
/**
* Vector of SuiteInfo items
*/
private Vector fSuiteInfos= new Vector();
/**
* Maps test Ids to TreeItems.
*/
private Map fTreeItemMap= new HashMap();
private TestRunnerViewPart fTestRunnerPart;
private final Image fOkIcon= TestRunnerViewPart.createImage("obj16/testok.gif"); //$NON-NLS-1$
private final Image fErrorIcon= TestRunnerViewPart.createImage("obj16/testerr.gif"); //$NON-NLS-1$
private final Image fFailureIcon= TestRunnerViewPart.createImage("obj16/testfail.gif"); //$NON-NLS-1$
private final Image fHierarchyIcon= TestRunnerViewPart.createImage("obj16/testhier.gif"); //$NON-NLS-1$
private final Image fSuiteIcon= TestRunnerViewPart.createImage("obj16/tsuite.gif"); //$NON-NLS-1$
private final Image fSuiteErrorIcon= TestRunnerViewPart.createImage("obj16/tsuiteerror.gif"); //$NON-NLS-1$
private final Image fSuiteFailIcon= TestRunnerViewPart.createImage("obj16/tsuitefail.gif"); //$NON-NLS-1$
private final Image fTestIcon= TestRunnerViewPart.createImage("obj16/test.gif"); //$NON-NLS-1$
private final Image fTestRunningIcon= TestRunnerViewPart.createImage("obj16/testrun.gif"); //$NON-NLS-1$
private class ExpandAllAction extends Action {
public ExpandAllAction() {
setText(JUnitMessages.getString("ExpandAllAction.text")); //$NON-NLS-1$
setToolTipText(JUnitMessages.getString("ExpandAllAction.tooltip")); //$NON-NLS-1$
}
public void run(){
expandAll();
}
}
public HierarchyRunView(CTabFolder tabFolder, TestRunnerViewPart runner) {
fTestRunnerPart= runner;
CTabItem hierarchyTab= new CTabItem(tabFolder, SWT.NONE);
hierarchyTab.setText(getName());
hierarchyTab.setImage(fHierarchyIcon);
Composite testTreePanel= new Composite(tabFolder, SWT.NONE);
GridLayout gridLayout= new GridLayout();
gridLayout.marginHeight= 0;
gridLayout.marginWidth= 0;
testTreePanel.setLayout(gridLayout);
GridData gridData= new GridData(GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL);
testTreePanel.setLayoutData(gridData);
hierarchyTab.setControl(testTreePanel);
hierarchyTab.setToolTipText(JUnitMessages.getString("HierarchyRunView.tab.tooltip")); //$NON-NLS-1$
fTree= new Tree(testTreePanel, SWT.V_SCROLL | SWT.SINGLE);
gridData= new GridData(GridData.FILL_BOTH | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL);
fTree.setLayoutData(gridData);
initMenu();
addListeners();
}
private void disposeIcons() {
fErrorIcon.dispose();
fFailureIcon.dispose();
fOkIcon.dispose();
fHierarchyIcon.dispose();
fTestIcon.dispose();
fTestRunningIcon.dispose();
fSuiteIcon.dispose();
fSuiteErrorIcon.dispose();
fSuiteFailIcon.dispose();
}
private void initMenu() {
MenuManager menuMgr= new MenuManager();
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(this);
Menu menu= menuMgr.createContextMenu(fTree);
fTree.setMenu(menu);
}
private String getTestMethod() {
return getTestInfo().getTestMethodName();
}
private TestRunInfo getTestInfo() {
TreeItem[] treeItems= fTree.getSelection();
if(treeItems.length == 0)
return null;
return ((TestRunInfo)treeItems[0].getData());
}
private boolean isSuiteSelected() {
TreeItem[] treeItems= fTree.getSelection();
if(treeItems.length != 1)
return false;
return treeItems[0].getItemCount() > 0;
}
private String getClassName() {
return getTestInfo().getClassName();
}
public String getSelectedTestId() {
TestRunInfo testInfo= getTestInfo();
if (testInfo == null)
return null;
return testInfo.getTestId();
}
public String getName() {
return JUnitMessages.getString("HierarchyRunView.tab.title"); //$NON-NLS-1$
}
public void setSelectedTest(String testId) {
TreeItem treeItem= findTreeItem(testId);
if (treeItem != null)
fTree.setSelection(new TreeItem[]{treeItem});
}
public void startTest(String testId) {
TreeItem treeItem= findTreeItem(testId);
if (treeItem == null)
return;
setCurrentItem(treeItem);
}
private void setCurrentItem(TreeItem treeItem) {
treeItem.setImage(fTestRunningIcon);
}
public void endTest(String testId) {
TreeItem treeItem= findTreeItem(testId);
if (treeItem == null)
return;
TestRunInfo testInfo= fTestRunnerPart.getTestInfo(testId);
updateItem(treeItem, testInfo);
if (fTestRunnerPart.isAutoScroll()) {
fTree.showItem(treeItem);
cacheItems(treeItem);
collapseIfOK(treeItem);
}
}
private void cacheItems(TreeItem treeItem) {
TreeItem parent= treeItem.getParentItem();
if (parent == fCachedParent)
return;
fCachedItems= parent.getItems();
fCachedParent= parent;
}
private void collapseIfOK(TreeItem treeItem) {
TreeItem parent= treeItem.getParentItem();
if (parent != null) {
TreeItem[] items= null;
if (parent == fCachedParent)
items= fCachedItems;
else
items= parent.getItems();
if (isLast(treeItem, items)) {
boolean ok= true;
for (int i= 0; i < items.length; i++) {
if (isFailure(items[i])) {
ok= false;
break;
}
}
if (ok) {
parent.setExpanded(false);
collapseIfOK(parent);
}
}
}
}
private boolean isLast(TreeItem treeItem, TreeItem[] items) {
return items[items.length-1] == treeItem;
}
private void updateItem(TreeItem treeItem, TestRunInfo testInfo) {
treeItem.setData(testInfo);
if(testInfo.getStatus() == ITestRunListener.STATUS_OK) {
treeItem.setImage(fOkIcon);
return;
}
if (testInfo.getStatus() == ITestRunListener.STATUS_FAILURE)
treeItem.setImage(fFailureIcon);
else if (testInfo.getStatus() == ITestRunListener.STATUS_ERROR)
treeItem.setImage(fErrorIcon);
propagateStatus(treeItem, testInfo.getStatus());
}
private void propagateStatus(TreeItem item, int status) {
TreeItem parent= item.getParentItem();
TestRunInfo testRunInfo= getTestRunInfo(item);
if (parent == null)
return;
Image parentImage= parent.getImage();
if (status == ITestRunListener.STATUS_FAILURE) {
if (parentImage == fSuiteErrorIcon || parentImage == fSuiteFailIcon)
return;
parent.setImage(fSuiteFailIcon);
testRunInfo.setStatus(ITestRunListener.STATUS_FAILURE);
} else {
if (parentImage == fSuiteErrorIcon)
return;
parent.setImage(fSuiteErrorIcon);
testRunInfo.setStatus(ITestRunListener.STATUS_ERROR);
}
propagateStatus(parent, status);
}
private TestRunInfo getTestRunInfo(TreeItem item) {
return (TestRunInfo)item.getData();
}
public void activate() {
fMoveSelection= false;
testSelected();
}
public void setFocus() {
fTree.setFocus();
}
public void aboutToStart() {
fTree.removeAll();
fSuiteInfos.removeAllElements();
fTreeItemMap= new HashMap();
fCachedParent= null;
fCachedItems= null;
fMoveSelection= false;
}
private void testSelected() {
fTestRunnerPart.handleTestSelected(getSelectedTestId());
}
private void addListeners() {
fTree.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
activate();
}
public void widgetDefaultSelected(SelectionEvent e) {
activate();
}
});
fTree.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
disposeIcons();
}
});
fTree.addMouseListener(new MouseAdapter() {
public void mouseDoubleClick(MouseEvent e) {
handleDoubleClick(e);
}
});
}
void handleDoubleClick(MouseEvent e) {
TestRunInfo testInfo= getTestInfo();
if (testInfo == null)
return;
String testLabel= testInfo.getTestName();
OpenTestAction action= null;
if (isSuiteSelected())
action= new OpenTestAction(fTestRunnerPart, testLabel);
else
action= new OpenTestAction(fTestRunnerPart, getClassName(), getTestMethod());
if (action != null && action.isEnabled())
action.run();
}
public void menuAboutToShow(IMenuManager manager) {
if (fTree.getSelectionCount() > 0) {
TreeItem treeItem= fTree.getSelection()[0];
TestRunInfo testInfo= (TestRunInfo) treeItem.getData();
String testLabel= testInfo.getTestName();
if (isSuiteSelected()) {
manager.add(new OpenTestAction(fTestRunnerPart, testLabel));
} else {
manager.add(new OpenTestAction(fTestRunnerPart, getClassName(), getTestMethod()));
manager.add(new RerunAction(fTestRunnerPart, getSelectedTestId(), getClassName(), getTestMethod()));
}
manager.add(new Separator());
manager.add(new ExpandAllAction());
}
}
public void newTreeEntry(String treeEntry) {
// format: testId","testName","isSuite","testcount
int index0= treeEntry.indexOf(',');
StringBuffer testStringBuffer= new StringBuffer(100);
int index1= scanTestName(treeEntry, index0+1, testStringBuffer);
int index2= treeEntry.indexOf(',', index1+1);
String testString= testStringBuffer.toString().trim();
String id= treeEntry.substring(0, index0);
TestRunInfo testInfo= new TestRunInfo(id, testString);
String isSuite= treeEntry.substring(index1+1, index2);
int testCount= Integer.parseInt(treeEntry.substring(index2+1));
TreeItem treeItem;
while((fSuiteInfos.size() > 0) && (((SuiteInfo) fSuiteInfos.lastElement()).fTestCount == 0)) {
fSuiteInfos.removeElementAt(fSuiteInfos.size()-1);
}
if(fSuiteInfos.size() == 0){
treeItem= new TreeItem(fTree, SWT.NONE);
treeItem.setImage(fSuiteIcon);
fSuiteInfos.addElement(new SuiteInfo(treeItem, testCount));
} else if(isSuite.equals("true")) { //$NON-NLS-1$
treeItem= new TreeItem(((SuiteInfo) fSuiteInfos.lastElement()).fTreeItem, SWT.NONE);
treeItem.setImage(fHierarchyIcon);
((SuiteInfo)fSuiteInfos.lastElement()).fTestCount -= 1;
fSuiteInfos.addElement(new SuiteInfo(treeItem, testCount));
} else {
treeItem= new TreeItem(((SuiteInfo) fSuiteInfos.lastElement()).fTreeItem, SWT.NONE);
treeItem.setImage(fTestIcon);
((SuiteInfo)fSuiteInfos.lastElement()).fTestCount -= 1;
mapTest(testInfo, treeItem);
}
treeItem.setText(testInfo.getTestMethodName());
treeItem.setData(testInfo);
}
private int scanTestName(String s, int start, StringBuffer testName) {
boolean inQuote= false;
int i= start;
for (; i < s.length(); i++) {
char c= s.charAt(i);
if (c == '\\' && !inQuote) {
inQuote= true;
continue;
} else if (inQuote) {
inQuote= false;
testName.append(c);
} else if (c == ',')
break;
else
testName.append(c);
}
return i;
}
private void mapTest(TestRunInfo info, TreeItem item) {
fTreeItemMap.put(info.getTestId(), item);
}
private TreeItem findTreeItem(String testId) {
Object o= fTreeItemMap.get(testId);
if (o instanceof TreeItem)
return (TreeItem)o;
return null;
}
/*
* @see ITestRunView#testStatusChanged(TestRunInfo, int)
*/
public void testStatusChanged(TestRunInfo newInfo) {
Object o= fTreeItemMap.get(newInfo.getTestId());
if (o instanceof TreeItem) {
updateItem((TreeItem)o, newInfo);
return;
}
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.junit.ui.ITestRunView#selectNext()
*/
public void selectNext() {
TreeItem selection= getInitialSearchSelection();
if (!moveSelection(selection))
return;
TreeItem failure= findFailure(selection, true, !isLeafFailure(selection));
if (failure != null)
selectTest(failure);
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.junit.ui.ITestRunView#selectPrevious()
*/
public void selectPrevious() {
TreeItem selection= getInitialSearchSelection();
if (!moveSelection(selection))
return;
TreeItem failure= findFailure(selection, false, !isLeafFailure(selection));
if (failure != null)
selectTest(failure);
}
private boolean moveSelection(TreeItem selection) {
if (!fMoveSelection) {
fMoveSelection= true;
if (isLeafFailure(selection)) {
selectTest(selection);
return false;
}
}
return true;
}
private TreeItem getInitialSearchSelection() {
TreeItem[] treeItems= fTree.getSelection();
TreeItem selection= null;
if (treeItems.length == 0)
selection= fTree.getItems()[0];
else
selection= treeItems[0];
return selection;
}
private boolean isFailure(TreeItem selection) {
return !(getTestRunInfo(selection).getStatus() == ITestRunListener.STATUS_OK);
}
private boolean isLeafFailure(TreeItem selection) {
boolean isLeaf= selection.getItemCount() == 0;
return isLeaf && isFailure(selection);
}
private void selectTest(TreeItem selection) {
fTestRunnerPart.showTest(getTestRunInfo(selection));
}
private TreeItem findFailure(TreeItem start, boolean next, boolean includeNode) {
TreeItem[] sib= findSiblings(start, next, includeNode);
if (next) {
for (int i= 0; i < sib.length; i++) {
TreeItem failure= findFailureInTree(sib[i]);
if (failure != null)
return failure;
}
} else {
for (int i= sib.length-1; i >= 0; i--) {
TreeItem failure= findFailureInTree(sib[i]);
if (failure != null)
return failure;
}
}
TreeItem parent= start.getParentItem();
if (parent == null)
return null;
return findFailure(parent, next, false);
}
private TreeItem[] findSiblings(TreeItem item, boolean next, boolean includeNode) {
TreeItem parent= item.getParentItem();
TreeItem[] children= null;
if (parent == null)
children= item.getParent().getItems();
else
children= parent.getItems();
for (int i= 0; i < children.length; i++) {
TreeItem item2= children[i];
if (item2 == item) {
TreeItem[] result= null;
if (next) {
if (!includeNode) {
result= new TreeItem[children.length-i-1];
System.arraycopy(children, i+1, result, 0, children.length-i-1);
} else {
result= new TreeItem[children.length-i];
System.arraycopy(children, i, result, 0, children.length-i);
}
} else {
if (!includeNode) {
result= new TreeItem[i];
System.arraycopy(children, 0, result, 0, i);
} else {
result= new TreeItem[i+1];
System.arraycopy(children, 0, result, 0, i+1);
}
}
return result;
}
}
return new TreeItem[0];
}
private TreeItem findFailureInTree(TreeItem item) {
if (item.getItemCount() == 0) {
if (isFailure(item))
return item;
}
TreeItem[] children= item.getItems();
for (int i= 0; i < children.length; i++) {
TreeItem item2= findFailureInTree(children[i]);
if (item2 != null)
return item2;
}
return null;
}
protected void expandAll() {
TreeItem[] treeItems= fTree.getSelection();
fTree.setRedraw(false);
for (int i= 0; i < treeItems.length; i++) {
expandAll(treeItems[i]);
}
fTree.setRedraw(true);
}
private void expandAll(TreeItem item) {
item.setExpanded(true);
TreeItem[] items= item.getItems();
for (int i= 0; i < items.length; i++) {
expandAll(items[i]);
}
}
}
|
40,967 |
Bug 40967 JUnit: Second list is not accessible [JUnit]
|
20030730 The second list does not have its label read by a screen reader as it has a button between the label and the list in the z order. This can fixed by either a) Using the moveUp() or moveDown() method to change the z order of the widgets. This is the preferable choice as most commercial screen readers use this algorithm but it requires that the label and the list are siblings (have the same parent). b) Add an AccessibleListener to the control. This will likely be a problem in JAWS still though as it does not use MSAA.
|
resolved fixed
|
254ded2
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-19T10:40:46Z | 2003-07-30T18:33:20Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/TestRunnerViewPart.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Julien Ruaux: [email protected] see bug 25324 Ability to know when tests are finished [junit]
* Vincent Massol: [email protected] 25324 Ability to know when tests are finished [junit]
******************************************************************************/
package org.eclipse.jdt.internal.junit.ui;
import java.net.MalformedURLException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.debug.ui.DebugUITools;
import org.eclipse.jdt.core.ElementChangedEvent;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IElementChangedListener;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaElementDelta;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.internal.junit.launcher.JUnitBaseLaunchConfiguration;
import org.eclipse.jdt.junit.ITestRunListener;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.ViewForm;
import org.eclipse.swt.dnd.Clipboard;
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.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorActionBarContributor;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.EditorActionBarContributor;
import org.eclipse.ui.part.ViewPart;
/**
* A ViewPart that shows the results of a test run.
*/
public class TestRunnerViewPart extends ViewPart implements ITestRunListener2, IPropertyChangeListener {
public static final String NAME= "org.eclipse.jdt.junit.ResultView"; //$NON-NLS-1$
/**
* Number of executed tests during a test run
*/
protected int fExecutedTests;
/**
* Number of errors during this test run
*/
protected int fErrorCount;
/**
* Number of failures during this test run
*/
protected int fFailureCount;
/**
* Number of tests run
*/
private int fTestCount;
/**
* Whether the output scrolls and reveals tests as they are executed.
*/
private boolean fAutoScroll = true;
/**
* Map storing TestInfos for each executed test keyed by
* the test name.
*/
private Map fTestInfos= new HashMap();
/**
* The first failure of a test run. Used to reveal the
* first failed tests at the end of a run.
*/
private List fFailures= new ArrayList();
private JUnitProgressBar fProgressBar;
private ProgressImages fProgressImages;
private Image fViewImage;
private CounterPanel fCounterPanel;
private boolean fShowOnErrorOnly= false;
private Clipboard fClipboard;
/**
* The view that shows the stack trace of a failure
*/
private FailureTraceView fFailureView;
/**
* The collection of ITestRunViews
*/
private Vector fTestRunViews = new Vector();
/**
* The currently active run view
*/
private ITestRunView fActiveRunView;
/**
* Is the UI disposed
*/
private boolean fIsDisposed= false;
/**
* The launched project
*/
private IJavaProject fTestProject;
/**
* The launcher that has started the test
*/
private String fLaunchMode;
private ILaunch fLastLaunch;
/**
* Actions
*/
private Action fRerunLastTestAction;
private ScrollLockAction fScrollLockAction;
/**
* The client side of the remote test runner
*/
private RemoteTestRunnerClient fTestRunnerClient;
final Image fStackViewIcon= TestRunnerViewPart.createImage("cview16/stackframe.gif");//$NON-NLS-1$
final Image fTestRunOKIcon= TestRunnerViewPart.createImage("cview16/junitsucc.gif"); //$NON-NLS-1$
final Image fTestRunFailIcon= TestRunnerViewPart.createImage("cview16/juniterr.gif"); //$NON-NLS-1$
final Image fTestRunOKDirtyIcon= TestRunnerViewPart.createImage("cview16/junitsuccq.gif"); //$NON-NLS-1$
final Image fTestRunFailDirtyIcon= TestRunnerViewPart.createImage("cview16/juniterrq.gif"); //$NON-NLS-1$
// Persistance tags.
static final String TAG_PAGE= "page"; //$NON-NLS-1$
static final String TAG_RATIO= "ratio"; //$NON-NLS-1$
static final String TAG_TRACEFILTER= "tracefilter"; //$NON-NLS-1$
private IMemento fMemento;
Image fOriginalViewImage;
IElementChangedListener fDirtyListener;
private CTabFolder fTabFolder;
private SashForm fSashForm;
private Action fNextAction;
private Action fPreviousAction;
private class StopAction extends Action {
public StopAction() {
setText(JUnitMessages.getString("TestRunnerViewPart.stopaction.text"));//$NON-NLS-1$
setToolTipText(JUnitMessages.getString("TestRunnerViewPart.stopaction.tooltip"));//$NON-NLS-1$
setDisabledImageDescriptor(JUnitPlugin.getImageDescriptor("dlcl16/stop.gif")); //$NON-NLS-1$
setHoverImageDescriptor(JUnitPlugin.getImageDescriptor("clcl16/stop.gif")); //$NON-NLS-1$
setImageDescriptor(JUnitPlugin.getImageDescriptor("elcl16/stop.gif")); //$NON-NLS-1$
}
public void run() {
stopTest();
}
}
private class RerunLastAction extends Action {
public RerunLastAction() {
setText(JUnitMessages.getString("TestRunnerViewPart.rerunaction.label")); //$NON-NLS-1$
setToolTipText(JUnitMessages.getString("TestRunnerViewPart.rerunaction.tooltip")); //$NON-NLS-1$
setDisabledImageDescriptor(JUnitPlugin.getImageDescriptor("dlcl16/relaunch.gif")); //$NON-NLS-1$
setHoverImageDescriptor(JUnitPlugin.getImageDescriptor("clcl16/relaunch.gif")); //$NON-NLS-1$
setImageDescriptor(JUnitPlugin.getImageDescriptor("elcl16/relaunch.gif")); //$NON-NLS-1$
}
public void run(){
rerunTestRun();
}
}
/**
* Listen for for modifications to Java elements
*/
private class DirtyListener implements IElementChangedListener {
public void elementChanged(ElementChangedEvent event) {
processDelta(event.getDelta());
}
private boolean processDelta(IJavaElementDelta delta) {
int kind= delta.getKind();
int details= delta.getFlags();
int type= delta.getElement().getElementType();
switch (type) {
// Consider containers for class files.
case IJavaElement.JAVA_MODEL:
case IJavaElement.JAVA_PROJECT:
case IJavaElement.PACKAGE_FRAGMENT_ROOT:
case IJavaElement.PACKAGE_FRAGMENT:
// If we did some different than changing a child we flush the the undo / redo stack.
if (kind != IJavaElementDelta.CHANGED || details != IJavaElementDelta.F_CHILDREN) {
codeHasChanged();
return false;
}
break;
case IJavaElement.COMPILATION_UNIT:
ICompilationUnit unit= (ICompilationUnit)delta.getElement();
// If we change a working copy we do nothing
if (unit.isWorkingCopy()) {
// Don't examine children of a working copy but keep processing siblings.
return true;
} else {
codeHasChanged();
return false;
}
case IJavaElement.CLASS_FILE:
// Don't examine children of a class file but keep on examining siblings.
return true;
default:
codeHasChanged();
return false;
}
IJavaElementDelta[] affectedChildren= delta.getAffectedChildren();
if (affectedChildren == null)
return true;
for (int i= 0; i < affectedChildren.length; i++) {
if (!processDelta(affectedChildren[i]))
return false;
}
return true;
}
}
public void init(IViewSite site, IMemento memento) throws PartInitException {
super.init(site, memento);
fMemento= memento;
}
private void restoreLayoutState(IMemento memento) {
Integer page= memento.getInteger(TAG_PAGE);
if (page != null) {
int p= page.intValue();
fTabFolder.setSelection(p);
fActiveRunView= (ITestRunView)fTestRunViews.get(p);
}
Integer ratio= memento.getInteger(TAG_RATIO);
if (ratio != null)
fSashForm.setWeights(new int[] { ratio.intValue(), 1000 - ratio.intValue()} );
}
/**
* Stops the currently running test and shuts down the RemoteTestRunner
*/
public void stopTest() {
if (fTestRunnerClient != null)
fTestRunnerClient.stopTest();
}
/**
* Stops the currently running test and shuts down the RemoteTestRunner
*/
public void rerunTestRun() {
if (fLastLaunch != null && fLastLaunch.getLaunchConfiguration() != null) {
try {
DebugUITools.saveAndBuildBeforeLaunch();
fLastLaunch.getLaunchConfiguration().launch(fLastLaunch.getLaunchMode(), null);
} catch (CoreException e) {
ErrorDialog.openError(getSite().getShell(),
JUnitMessages.getString("TestRunnerViewPart.error.cannotrerun"), e.getMessage(), e.getStatus() //$NON-NLS-1$
);
}
}
}
public void setAutoScroll(boolean scroll) {
fAutoScroll = scroll;
}
public boolean isAutoScroll() {
return fAutoScroll;
}
/*
* @see ITestRunListener#testRunStarted(testCount)
*/
public void testRunStarted(final int testCount){
reset(testCount);
fShowOnErrorOnly= JUnitPreferencePage.getShowOnErrorOnly();
fExecutedTests++;
}
public void selectNextFailure() {
fActiveRunView.selectNext();
}
public void selectPreviousFailure() {
fActiveRunView.selectPrevious();
}
public void showTest(TestRunInfo test) {
fActiveRunView.setSelectedTest(test.getTestId());
handleTestSelected(test.getTestId());
new OpenTestAction(this, test.getClassName(), test.getTestMethodName()).run();
}
public void reset(){
reset(0);
setViewPartTitle(null);
clearStatus();
resetViewIcon();
}
/*
* @see ITestRunListener#testRunEnded
*/
public void testRunEnded(long elapsedTime){
fExecutedTests--;
String[] keys= {elapsedTimeAsString(elapsedTime), String.valueOf(fErrorCount), String.valueOf(fFailureCount)};
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.finish", keys); //$NON-NLS-1$
if (hasErrorsOrFailures())
postError(msg);
else
postInfo(msg);
postSyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
if (fFailures.size() > 0) {
selectFirstFailure();
}
updateViewIcon();
if (fDirtyListener == null) {
fDirtyListener= new DirtyListener();
JavaCore.addElementChangedListener(fDirtyListener);
}
}
});
}
protected void selectFirstFailure() {
TestRunInfo firstFailure= (TestRunInfo)fFailures.get(0);
if (firstFailure != null && fAutoScroll) {
fActiveRunView.setSelectedTest(firstFailure.getTestId());
handleTestSelected(firstFailure.getTestId());
}
}
private void updateViewIcon() {
if (hasErrorsOrFailures())
fViewImage= fTestRunFailIcon;
else
fViewImage= fTestRunOKIcon;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
private boolean hasErrorsOrFailures() {
return fErrorCount+fFailureCount > 0;
}
private String elapsedTimeAsString(long runTime) {
return NumberFormat.getInstance().format((double)runTime/1000);
}
/*
* @see ITestRunListener#testRunStopped
*/
public void testRunStopped(final long elapsedTime) {
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.stopped", elapsedTimeAsString(elapsedTime)); //$NON-NLS-1$
postInfo(msg);
postSyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
resetViewIcon();
}
});
}
private void resetViewIcon() {
fViewImage= fOriginalViewImage;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
/*
* @see ITestRunListener#testRunTerminated
*/
public void testRunTerminated() {
String msg= JUnitMessages.getString("TestRunnerViewPart.message.terminated"); //$NON-NLS-1$
showMessage(msg);
}
private void showMessage(String msg) {
showInformation(msg);
postError(msg);
}
/*
* @see ITestRunListener#testStarted
*/
public void testStarted(String testId, String testName) {
postStartTest(testId, testName);
// reveal the part when the first test starts
if (!fShowOnErrorOnly && fExecutedTests == 1)
postShowTestResultsView();
postInfo(JUnitMessages.getFormattedString("TestRunnerViewPart.message.started", testName)); //$NON-NLS-1$
TestRunInfo testInfo= getTestInfo(testId);
if (testInfo == null)
fTestInfos.put(testId, new TestRunInfo(testId, testName));
}
/*
* @see ITestRunListener#testEnded
*/
public void testEnded(String testId, String testName){
postEndTest(testId, testName);
fExecutedTests++;
}
/*
* @see ITestRunListener#testFailed
*/
public void testFailed(int status, String testId, String testName, String trace){
TestRunInfo testInfo= getTestInfo(testId);
if (testInfo == null) {
testInfo= new TestRunInfo(testId, testName);
fTestInfos.put(testName, testInfo);
}
testInfo.setTrace(trace);
testInfo.setStatus(status);
if (status == ITestRunListener.STATUS_ERROR)
fErrorCount++;
else
fFailureCount++;
fFailures.add(testInfo);
// show the view on the first error only
if (fShowOnErrorOnly && (fErrorCount + fFailureCount == 1))
postShowTestResultsView();
}
/*
* @see ITestRunListener#testReran
*/
public void testReran(String testId, String className, String testName, int status, String trace) {
if (status == ITestRunListener.STATUS_ERROR) {
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.error", new String[]{testName, className}); //$NON-NLS-1$
postError(msg);
} else if (status == ITestRunListener.STATUS_FAILURE) {
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.failure", new String[]{testName, className}); //$NON-NLS-1$
postError(msg);
} else {
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.success", new String[]{testName, className}); //$NON-NLS-1$
postInfo(msg);
}
TestRunInfo info= getTestInfo(testId);
updateTest(info, status);
if (info.getTrace() == null || !info.getTrace().equals(trace)) {
info.setTrace(trace);
showFailure(info.getTrace());
}
}
private void updateTest(TestRunInfo info, final int status) {
if (status == info.getStatus())
return;
if (info.getStatus() == ITestRunListener.STATUS_OK) {
if (status == ITestRunListener.STATUS_FAILURE)
fFailureCount++;
else if (status == ITestRunListener.STATUS_ERROR)
fErrorCount++;
} else if (info.getStatus() == ITestRunListener.STATUS_ERROR) {
if (status == ITestRunListener.STATUS_OK)
fErrorCount--;
else if (status == ITestRunListener.STATUS_FAILURE) {
fErrorCount--;
fFailureCount++;
}
} else if (info.getStatus() == ITestRunListener.STATUS_FAILURE) {
if (status == ITestRunListener.STATUS_OK)
fFailureCount--;
else if (status == ITestRunListener.STATUS_ERROR) {
fFailureCount--;
fErrorCount++;
}
}
info.setStatus(status);
final TestRunInfo finalInfo= info;
postSyncRunnable(new Runnable() {
public void run() {
refreshCounters();
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.testStatusChanged(finalInfo);
}
}
});
}
/*
* @see ITestRunListener#testTreeEntry
*/
public void testTreeEntry(final String treeEntry){
postSyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.newTreeEntry(treeEntry);
}
}
});
}
public void startTestRunListening(IJavaElement type, int port, ILaunch launch) {
fTestProject= type.getJavaProject();
fLaunchMode= launch.getLaunchMode();
aboutToLaunch();
if (fTestRunnerClient != null) {
stopTest();
}
fTestRunnerClient= new RemoteTestRunnerClient();
// add the TestRunnerViewPart to the list of registered listeners
List listeners= JUnitPlugin.getDefault().getTestRunListeners();
ITestRunListener[] listenerArray= new ITestRunListener[listeners.size()+1];
listeners.toArray(listenerArray);
System.arraycopy(listenerArray, 0, listenerArray, 1, listenerArray.length-1);
listenerArray[0]= this;
fTestRunnerClient.startListening(listenerArray, port);
fLastLaunch= launch;
setViewPartTitle(type);
if (type instanceof IType)
setTitleToolTip(((IType)type).getFullyQualifiedName());
else
setTitleToolTip(type.getElementName());
}
private void setViewPartTitle(IJavaElement type) {
String title;
if (type == null)
title= JUnitMessages.getString("TestRunnerViewPart.title_no_type"); //$NON-NLS-1$
else
title= JUnitMessages.getFormattedString("TestRunnerViewPart.title", type.getElementName()); //$NON-NLS-1$
setTitle(title);
}
private void aboutToLaunch() {
String msg= JUnitMessages.getString("TestRunnerViewPart.message.launching"); //$NON-NLS-1$
showInformation(msg);
postInfo(msg);
fViewImage= fOriginalViewImage;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
public synchronized void dispose(){
fIsDisposed= true;
stopTest();
if (fProgressImages != null)
fProgressImages.dispose();
JUnitPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(this);
fTestRunOKIcon.dispose();
fTestRunFailIcon.dispose();
fStackViewIcon.dispose();
fTestRunOKDirtyIcon.dispose();
fTestRunFailDirtyIcon.dispose();
if (fClipboard != null)
fClipboard.dispose();
}
private void start(final int total) {
resetProgressBar(total);
fCounterPanel.setTotal(total);
fCounterPanel.setRunValue(0);
}
private void resetProgressBar(final int total) {
fProgressBar.reset();
fProgressBar.setMaximum(total);
}
private void postSyncRunnable(Runnable r) {
if (!isDisposed())
getDisplay().syncExec(r);
}
private void aboutToStart() {
postSyncRunnable(new Runnable() {
public void run() {
if (!isDisposed()) {
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.aboutToStart();
}
fNextAction.setEnabled(false);
fPreviousAction.setEnabled(false);
}
}
});
}
private void postEndTest(final String testId, final String testName) {
postSyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
handleEndTest();
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.endTest(testId);
}
if (fFailureCount + fErrorCount > 0) {
fNextAction.setEnabled(true);
fPreviousAction.setEnabled(true);
}
}
});
}
private void postStartTest(final String testId, final String testName) {
postSyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.startTest(testId);
}
}
});
}
private void handleEndTest() {
refreshCounters();
fProgressBar.step(fFailureCount+fErrorCount);
if (fShowOnErrorOnly) {
Image progress= fProgressImages.getImage(fExecutedTests, fTestCount, fErrorCount, fFailureCount);
if (progress != fViewImage) {
fViewImage= progress;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
}
}
private void refreshCounters() {
fCounterPanel.setErrorValue(fErrorCount);
fCounterPanel.setFailureValue(fFailureCount);
fCounterPanel.setRunValue(fExecutedTests);
fProgressBar.refresh(fErrorCount+fFailureCount> 0);
}
protected void postShowTestResultsView() {
postSyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
showTestResultsView();
}
});
}
public void showTestResultsView() {
IWorkbenchWindow window= getSite().getWorkbenchWindow();
IWorkbenchPage page= window.getActivePage();
TestRunnerViewPart testRunner= null;
if (page != null) {
try { // show the result view
testRunner= (TestRunnerViewPart)page.findView(TestRunnerViewPart.NAME);
if(testRunner == null) {
IWorkbenchPart activePart= page.getActivePart();
testRunner= (TestRunnerViewPart)page.showView(TestRunnerViewPart.NAME);
//restore focus stolen by the creation of the console
page.activate(activePart);
} else {
page.bringToTop(testRunner);
}
} catch (PartInitException pie) {
JUnitPlugin.log(pie);
}
}
}
protected void postInfo(final String message) {
postSyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
getStatusLine().setErrorMessage(null);
getStatusLine().setMessage(message);
}
});
}
protected void postError(final String message) {
postSyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
getStatusLine().setMessage(null);
getStatusLine().setErrorMessage(message);
}
});
}
protected void showInformation(final String info){
postSyncRunnable(new Runnable() {
public void run() {
if (!isDisposed())
fFailureView.setInformation(info);
}
});
}
private CTabFolder createTestRunViews(Composite parent) {
CTabFolder tabFolder= new CTabFolder(parent, SWT.TOP);
tabFolder.setLayoutData(new GridData(GridData.FILL_BOTH | GridData.GRAB_VERTICAL));
ITestRunView failureRunView= new FailureRunView(tabFolder, fClipboard, this);
ITestRunView testHierarchyRunView= new HierarchyRunView(tabFolder, this);
fTestRunViews.addElement(failureRunView);
fTestRunViews.addElement(testHierarchyRunView);
tabFolder.setSelection(0);
fActiveRunView= (ITestRunView)fTestRunViews.firstElement();
tabFolder.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
testViewChanged(event);
}
});
return tabFolder;
}
private void testViewChanged(SelectionEvent event) {
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
if (((CTabFolder) event.widget).getSelection().getText() == v.getName()){
v.setSelectedTest(fActiveRunView.getSelectedTestId());
fActiveRunView= v;
fActiveRunView.activate();
}
}
}
private SashForm createSashForm(Composite parent) {
fSashForm= new SashForm(parent, SWT.VERTICAL);
ViewForm top= new ViewForm(fSashForm, SWT.NONE);
fTabFolder= createTestRunViews(top);
fTabFolder.setLayoutData(new TabFolderLayout());
top.setContent(fTabFolder);
ViewForm bottom= new ViewForm(fSashForm, SWT.NONE);
ToolBar failureToolBar= new ToolBar(bottom, SWT.FLAT | SWT.WRAP);
bottom.setTopCenter(failureToolBar);
fFailureView= new FailureTraceView(bottom, fClipboard, this);
bottom.setContent(fFailureView.getComposite());
CLabel label= new CLabel(bottom, SWT.NONE);
label.setText(JUnitMessages.getString("TestRunnerViewPart.label.failure")); //$NON-NLS-1$
label.setImage(fStackViewIcon);
bottom.setTopLeft(label);
// fill the failure trace viewer toolbar
ToolBarManager failureToolBarmanager= new ToolBarManager(failureToolBar);
failureToolBarmanager.add(new EnableStackFilterAction(fFailureView));
failureToolBarmanager.update(true);
fSashForm.setWeights(new int[]{50, 50});
return fSashForm;
}
private void reset(final int testCount) {
postSyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
fCounterPanel.reset();
fFailureView.clear();
fProgressBar.reset();
clearStatus();
start(testCount);
}
});
fExecutedTests= 0;
fFailureCount= 0;
fErrorCount= 0;
fTestCount= testCount;
aboutToStart();
fTestInfos.clear();
fFailures= new ArrayList();
}
private void clearStatus() {
getStatusLine().setMessage(null);
getStatusLine().setErrorMessage(null);
}
public void setFocus() {
if (fActiveRunView != null)
fActiveRunView.setFocus();
}
public void createPartControl(Composite parent) {
fClipboard= new Clipboard(parent.getDisplay());
GridLayout gridLayout= new GridLayout();
gridLayout.marginWidth= 0;
gridLayout.marginHeight= 0;
parent.setLayout(gridLayout);
configureToolBar();
Composite counterPanel= createProgressCountPanel(parent);
counterPanel.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL));
SashForm sashForm= createSashForm(parent);
sashForm.setLayoutData(new GridData(GridData.FILL_BOTH));
IActionBars actionBars= getViewSite().getActionBars();
actionBars.setGlobalActionHandler(
IWorkbenchActionConstants.COPY,
new CopyTraceAction(fFailureView, fClipboard));
JUnitPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(this);
fOriginalViewImage= getTitleImage();
fProgressImages= new ProgressImages();
WorkbenchHelp.setHelp(parent, IJUnitHelpContextIds.RESULTS_VIEW);
if (fMemento != null)
restoreLayoutState(fMemento);
fMemento= null;
}
public void saveState(IMemento memento) {
if (fSashForm == null) {
// part has not been created
if (fMemento != null) //Keep the old state;
memento.putMemento(fMemento);
return;
}
int activePage= fTabFolder.getSelectionIndex();
memento.putInteger(TAG_PAGE, activePage);
int weigths[]= fSashForm.getWeights();
int ratio= (weigths[0] * 1000) / (weigths[0] + weigths[1]);
memento.putInteger(TAG_RATIO, ratio);
}
private void configureToolBar() {
IActionBars actionBars= getViewSite().getActionBars();
IToolBarManager toolBar= actionBars.getToolBarManager();
fRerunLastTestAction= new RerunLastAction();
fScrollLockAction= new ScrollLockAction(this);
fNextAction= new ShowNextFailureAction(this);
fPreviousAction= new ShowPreviousFailureAction(this);
fNextAction.setEnabled(false);
fPreviousAction.setEnabled(false);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.NEXT, fNextAction);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.PREVIOUS, fPreviousAction);
toolBar.add(fNextAction);
toolBar.add(fPreviousAction);
toolBar.add(new StopAction());
toolBar.add(new Separator());
toolBar.add(fRerunLastTestAction);
toolBar.add(fScrollLockAction);
fScrollLockAction.setChecked(!fAutoScroll);
actionBars.updateActionBars();
}
private IStatusLineManager getStatusLine() {
// we want to show messages globally hence we
// have to go throgh the active part
IViewSite site= getViewSite();
IWorkbenchPage page= site.getPage();
IWorkbenchPart activePart= page.getActivePart();
if (activePart instanceof IViewPart) {
IViewPart activeViewPart= (IViewPart)activePart;
IViewSite activeViewSite= activeViewPart.getViewSite();
return activeViewSite.getActionBars().getStatusLineManager();
}
if (activePart instanceof IEditorPart) {
IEditorPart activeEditorPart= (IEditorPart)activePart;
IEditorActionBarContributor contributor= activeEditorPart.getEditorSite().getActionBarContributor();
if (contributor instanceof EditorActionBarContributor)
return ((EditorActionBarContributor) contributor).getActionBars().getStatusLineManager();
}
// no active part
return getViewSite().getActionBars().getStatusLineManager();
}
private Composite createProgressCountPanel(Composite parent) {
Composite composite= new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout());
fProgressBar = new JUnitProgressBar(composite);
fProgressBar.setLayoutData(
new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL));
fCounterPanel = new CounterPanel(composite);
fCounterPanel.setLayoutData(
new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL));
return composite;
}
public TestRunInfo getTestInfo(String testId) {
if (testId == null)
return null;
return (TestRunInfo) fTestInfos.get(testId);
}
public void handleTestSelected(String testId) {
TestRunInfo testInfo= getTestInfo(testId);
if (testInfo == null) {
showFailure(""); //$NON-NLS-1$
} else {
showFailure(testInfo.getTrace());
}
}
private void showFailure(final String failure) {
postSyncRunnable(new Runnable() {
public void run() {
if (!isDisposed())
fFailureView.showFailure(failure);
}
});
}
public IJavaProject getLaunchedProject() {
return fTestProject;
}
public ILaunch getLastLaunch() {
return fLastLaunch;
}
protected static Image createImage(String path) {
try {
ImageDescriptor id= ImageDescriptor.createFromURL(JUnitPlugin.makeIconFileURL(path));
return id.createImage();
} catch (MalformedURLException e) {
// fall through
}
return null;
}
private boolean isDisposed() {
return fIsDisposed || fCounterPanel.isDisposed();
}
private Display getDisplay() {
return getViewSite().getShell().getDisplay();
}
/**
* @see IWorkbenchPart#getTitleImage()
*/
public Image getTitleImage() {
if (fOriginalViewImage == null)
fOriginalViewImage= super.getTitleImage();
if (fViewImage == null)
return super.getTitleImage();
return fViewImage;
}
public void propertyChange(PropertyChangeEvent event) {
if (isDisposed())
return;
if (IJUnitPreferencesConstants.SHOW_ON_ERROR_ONLY.equals(event.getProperty())) {
if (!JUnitPreferencePage.getShowOnErrorOnly()) {
fViewImage= fOriginalViewImage;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
}
}
void codeHasChanged() {
postSyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
if (fDirtyListener != null) {
JavaCore.removeElementChangedListener(fDirtyListener);
fDirtyListener= null;
}
if (fViewImage == fTestRunOKIcon)
fViewImage= fTestRunOKDirtyIcon;
else if (fViewImage == fTestRunFailIcon)
fViewImage= fTestRunFailDirtyIcon;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
});
}
boolean isCreated() {
return fCounterPanel != null;
}
public void rerunTest(String testId, String className, String testName) {
DebugUITools.saveAndBuildBeforeLaunch();
if (fTestRunnerClient != null && fTestRunnerClient.isRunning() && ILaunchManager.DEBUG_MODE.equals(fLaunchMode))
fTestRunnerClient.rerunTest(testId, className, testName);
else if (fLastLaunch != null) {
// run the selected test using the previous launch configuration
ILaunchConfiguration launchConfiguration= fLastLaunch.getLaunchConfiguration();
if (launchConfiguration != null) {
try {
ILaunchConfigurationWorkingCopy tmp= launchConfiguration.copy("Rerun "+testName); //$NON-NLS-1$
tmp.setAttribute(JUnitBaseLaunchConfiguration.TESTNAME_ATTR, testName);
tmp.launch(fLastLaunch.getLaunchMode(), null);
return;
} catch (CoreException e) {
ErrorDialog.openError(getSite().getShell(),
JUnitMessages.getString("TestRunnerViewPart.error.cannotrerun"), e.getMessage(), e.getStatus() //$NON-NLS-1$
);
}
}
MessageDialog.openInformation(getSite().getShell(),
JUnitMessages.getString("TestRunnerViewPart.cannotrerun.title"), //$NON-NLS-1$
JUnitMessages.getString("TestRunnerViewPart.cannotrerurn.message") //$NON-NLS-1$
);
}
}
}
|
40,542 |
Bug 40542 JUnit - status bar should better show test class name [JUnit]
|
Build 3.0M2 In addition to showing the test method name, it should prefix it with the class name. The test hierarchy shows this information, but the animation time penalty is quite bad, and for big suites, it is not a viable alternative.
|
resolved fixed
|
74ac007
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-19T12:00:25Z | 2003-07-21T09:33:20Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/TestRunnerViewPart.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Julien Ruaux: [email protected] see bug 25324 Ability to know when tests are finished [junit]
* Vincent Massol: [email protected] 25324 Ability to know when tests are finished [junit]
******************************************************************************/
package org.eclipse.jdt.internal.junit.ui;
import java.net.MalformedURLException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.debug.ui.DebugUITools;
import org.eclipse.jdt.core.ElementChangedEvent;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IElementChangedListener;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaElementDelta;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.internal.junit.launcher.JUnitBaseLaunchConfiguration;
import org.eclipse.jdt.junit.ITestRunListener;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.ViewForm;
import org.eclipse.swt.dnd.Clipboard;
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.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorActionBarContributor;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.EditorActionBarContributor;
import org.eclipse.ui.part.ViewPart;
/**
* A ViewPart that shows the results of a test run.
*/
public class TestRunnerViewPart extends ViewPart implements ITestRunListener2, IPropertyChangeListener {
public static final String NAME= "org.eclipse.jdt.junit.ResultView"; //$NON-NLS-1$
/**
* Number of executed tests during a test run
*/
protected int fExecutedTests;
/**
* Number of errors during this test run
*/
protected int fErrorCount;
/**
* Number of failures during this test run
*/
protected int fFailureCount;
/**
* Number of tests run
*/
private int fTestCount;
/**
* Whether the output scrolls and reveals tests as they are executed.
*/
private boolean fAutoScroll = true;
/**
* Map storing TestInfos for each executed test keyed by
* the test name.
*/
private Map fTestInfos= new HashMap();
/**
* The first failure of a test run. Used to reveal the
* first failed tests at the end of a run.
*/
private List fFailures= new ArrayList();
private JUnitProgressBar fProgressBar;
private ProgressImages fProgressImages;
private Image fViewImage;
private CounterPanel fCounterPanel;
private boolean fShowOnErrorOnly= false;
private Clipboard fClipboard;
/**
* The view that shows the stack trace of a failure
*/
private FailureTraceView fFailureView;
/**
* The collection of ITestRunViews
*/
private Vector fTestRunViews = new Vector();
/**
* The currently active run view
*/
private ITestRunView fActiveRunView;
/**
* Is the UI disposed
*/
private boolean fIsDisposed= false;
/**
* The launched project
*/
private IJavaProject fTestProject;
/**
* The launcher that has started the test
*/
private String fLaunchMode;
private ILaunch fLastLaunch;
/**
* Actions
*/
private Action fRerunLastTestAction;
private ScrollLockAction fScrollLockAction;
/**
* The client side of the remote test runner
*/
private RemoteTestRunnerClient fTestRunnerClient;
final Image fStackViewIcon= TestRunnerViewPart.createImage("cview16/stackframe.gif");//$NON-NLS-1$
final Image fTestRunOKIcon= TestRunnerViewPart.createImage("cview16/junitsucc.gif"); //$NON-NLS-1$
final Image fTestRunFailIcon= TestRunnerViewPart.createImage("cview16/juniterr.gif"); //$NON-NLS-1$
final Image fTestRunOKDirtyIcon= TestRunnerViewPart.createImage("cview16/junitsuccq.gif"); //$NON-NLS-1$
final Image fTestRunFailDirtyIcon= TestRunnerViewPart.createImage("cview16/juniterrq.gif"); //$NON-NLS-1$
// Persistance tags.
static final String TAG_PAGE= "page"; //$NON-NLS-1$
static final String TAG_RATIO= "ratio"; //$NON-NLS-1$
static final String TAG_TRACEFILTER= "tracefilter"; //$NON-NLS-1$
private IMemento fMemento;
Image fOriginalViewImage;
IElementChangedListener fDirtyListener;
private CTabFolder fTabFolder;
private SashForm fSashForm;
private Action fNextAction;
private Action fPreviousAction;
private class StopAction extends Action {
public StopAction() {
setText(JUnitMessages.getString("TestRunnerViewPart.stopaction.text"));//$NON-NLS-1$
setToolTipText(JUnitMessages.getString("TestRunnerViewPart.stopaction.tooltip"));//$NON-NLS-1$
setDisabledImageDescriptor(JUnitPlugin.getImageDescriptor("dlcl16/stop.gif")); //$NON-NLS-1$
setHoverImageDescriptor(JUnitPlugin.getImageDescriptor("clcl16/stop.gif")); //$NON-NLS-1$
setImageDescriptor(JUnitPlugin.getImageDescriptor("elcl16/stop.gif")); //$NON-NLS-1$
}
public void run() {
stopTest();
}
}
private class RerunLastAction extends Action {
public RerunLastAction() {
setText(JUnitMessages.getString("TestRunnerViewPart.rerunaction.label")); //$NON-NLS-1$
setToolTipText(JUnitMessages.getString("TestRunnerViewPart.rerunaction.tooltip")); //$NON-NLS-1$
setDisabledImageDescriptor(JUnitPlugin.getImageDescriptor("dlcl16/relaunch.gif")); //$NON-NLS-1$
setHoverImageDescriptor(JUnitPlugin.getImageDescriptor("clcl16/relaunch.gif")); //$NON-NLS-1$
setImageDescriptor(JUnitPlugin.getImageDescriptor("elcl16/relaunch.gif")); //$NON-NLS-1$
}
public void run(){
rerunTestRun();
}
}
/**
* Listen for for modifications to Java elements
*/
private class DirtyListener implements IElementChangedListener {
public void elementChanged(ElementChangedEvent event) {
processDelta(event.getDelta());
}
private boolean processDelta(IJavaElementDelta delta) {
int kind= delta.getKind();
int details= delta.getFlags();
int type= delta.getElement().getElementType();
switch (type) {
// Consider containers for class files.
case IJavaElement.JAVA_MODEL:
case IJavaElement.JAVA_PROJECT:
case IJavaElement.PACKAGE_FRAGMENT_ROOT:
case IJavaElement.PACKAGE_FRAGMENT:
// If we did some different than changing a child we flush the the undo / redo stack.
if (kind != IJavaElementDelta.CHANGED || details != IJavaElementDelta.F_CHILDREN) {
codeHasChanged();
return false;
}
break;
case IJavaElement.COMPILATION_UNIT:
ICompilationUnit unit= (ICompilationUnit)delta.getElement();
// If we change a working copy we do nothing
if (unit.isWorkingCopy()) {
// Don't examine children of a working copy but keep processing siblings.
return true;
} else {
codeHasChanged();
return false;
}
case IJavaElement.CLASS_FILE:
// Don't examine children of a class file but keep on examining siblings.
return true;
default:
codeHasChanged();
return false;
}
IJavaElementDelta[] affectedChildren= delta.getAffectedChildren();
if (affectedChildren == null)
return true;
for (int i= 0; i < affectedChildren.length; i++) {
if (!processDelta(affectedChildren[i]))
return false;
}
return true;
}
}
public void init(IViewSite site, IMemento memento) throws PartInitException {
super.init(site, memento);
fMemento= memento;
}
private void restoreLayoutState(IMemento memento) {
Integer page= memento.getInteger(TAG_PAGE);
if (page != null) {
int p= page.intValue();
fTabFolder.setSelection(p);
fActiveRunView= (ITestRunView)fTestRunViews.get(p);
}
Integer ratio= memento.getInteger(TAG_RATIO);
if (ratio != null)
fSashForm.setWeights(new int[] { ratio.intValue(), 1000 - ratio.intValue()} );
}
/**
* Stops the currently running test and shuts down the RemoteTestRunner
*/
public void stopTest() {
if (fTestRunnerClient != null)
fTestRunnerClient.stopTest();
}
/**
* Stops the currently running test and shuts down the RemoteTestRunner
*/
public void rerunTestRun() {
if (fLastLaunch != null && fLastLaunch.getLaunchConfiguration() != null) {
try {
DebugUITools.saveAndBuildBeforeLaunch();
fLastLaunch.getLaunchConfiguration().launch(fLastLaunch.getLaunchMode(), null);
} catch (CoreException e) {
ErrorDialog.openError(getSite().getShell(),
JUnitMessages.getString("TestRunnerViewPart.error.cannotrerun"), e.getMessage(), e.getStatus() //$NON-NLS-1$
);
}
}
}
public void setAutoScroll(boolean scroll) {
fAutoScroll = scroll;
}
public boolean isAutoScroll() {
return fAutoScroll;
}
/*
* @see ITestRunListener#testRunStarted(testCount)
*/
public void testRunStarted(final int testCount){
reset(testCount);
fShowOnErrorOnly= JUnitPreferencePage.getShowOnErrorOnly();
fExecutedTests++;
}
public void selectNextFailure() {
fActiveRunView.selectNext();
}
public void selectPreviousFailure() {
fActiveRunView.selectPrevious();
}
public void showTest(TestRunInfo test) {
fActiveRunView.setSelectedTest(test.getTestId());
handleTestSelected(test.getTestId());
new OpenTestAction(this, test.getClassName(), test.getTestMethodName()).run();
}
public void reset(){
reset(0);
setViewPartTitle(null);
clearStatus();
resetViewIcon();
}
/*
* @see ITestRunListener#testRunEnded
*/
public void testRunEnded(long elapsedTime){
fExecutedTests--;
String[] keys= {elapsedTimeAsString(elapsedTime), String.valueOf(fErrorCount), String.valueOf(fFailureCount)};
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.finish", keys); //$NON-NLS-1$
if (hasErrorsOrFailures())
postError(msg);
else
postInfo(msg);
postSyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
if (fFailures.size() > 0) {
selectFirstFailure();
}
updateViewIcon();
if (fDirtyListener == null) {
fDirtyListener= new DirtyListener();
JavaCore.addElementChangedListener(fDirtyListener);
}
}
});
}
protected void selectFirstFailure() {
TestRunInfo firstFailure= (TestRunInfo)fFailures.get(0);
if (firstFailure != null && fAutoScroll) {
fActiveRunView.setSelectedTest(firstFailure.getTestId());
handleTestSelected(firstFailure.getTestId());
}
}
private void updateViewIcon() {
if (hasErrorsOrFailures())
fViewImage= fTestRunFailIcon;
else
fViewImage= fTestRunOKIcon;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
private boolean hasErrorsOrFailures() {
return fErrorCount+fFailureCount > 0;
}
private String elapsedTimeAsString(long runTime) {
return NumberFormat.getInstance().format((double)runTime/1000);
}
/*
* @see ITestRunListener#testRunStopped
*/
public void testRunStopped(final long elapsedTime) {
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.stopped", elapsedTimeAsString(elapsedTime)); //$NON-NLS-1$
postInfo(msg);
postSyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
resetViewIcon();
}
});
}
private void resetViewIcon() {
fViewImage= fOriginalViewImage;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
/*
* @see ITestRunListener#testRunTerminated
*/
public void testRunTerminated() {
String msg= JUnitMessages.getString("TestRunnerViewPart.message.terminated"); //$NON-NLS-1$
showMessage(msg);
}
private void showMessage(String msg) {
showInformation(msg);
postError(msg);
}
/*
* @see ITestRunListener#testStarted
*/
public void testStarted(String testId, String testName) {
postStartTest(testId, testName);
// reveal the part when the first test starts
if (!fShowOnErrorOnly && fExecutedTests == 1)
postShowTestResultsView();
postInfo(JUnitMessages.getFormattedString("TestRunnerViewPart.message.started", testName)); //$NON-NLS-1$
TestRunInfo testInfo= getTestInfo(testId);
if (testInfo == null)
fTestInfos.put(testId, new TestRunInfo(testId, testName));
}
/*
* @see ITestRunListener#testEnded
*/
public void testEnded(String testId, String testName){
postEndTest(testId, testName);
fExecutedTests++;
}
/*
* @see ITestRunListener#testFailed
*/
public void testFailed(int status, String testId, String testName, String trace){
TestRunInfo testInfo= getTestInfo(testId);
if (testInfo == null) {
testInfo= new TestRunInfo(testId, testName);
fTestInfos.put(testName, testInfo);
}
testInfo.setTrace(trace);
testInfo.setStatus(status);
if (status == ITestRunListener.STATUS_ERROR)
fErrorCount++;
else
fFailureCount++;
fFailures.add(testInfo);
// show the view on the first error only
if (fShowOnErrorOnly && (fErrorCount + fFailureCount == 1))
postShowTestResultsView();
}
/*
* @see ITestRunListener#testReran
*/
public void testReran(String testId, String className, String testName, int status, String trace) {
if (status == ITestRunListener.STATUS_ERROR) {
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.error", new String[]{testName, className}); //$NON-NLS-1$
postError(msg);
} else if (status == ITestRunListener.STATUS_FAILURE) {
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.failure", new String[]{testName, className}); //$NON-NLS-1$
postError(msg);
} else {
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.success", new String[]{testName, className}); //$NON-NLS-1$
postInfo(msg);
}
TestRunInfo info= getTestInfo(testId);
updateTest(info, status);
if (info.getTrace() == null || !info.getTrace().equals(trace)) {
info.setTrace(trace);
showFailure(info.getTrace());
}
}
private void updateTest(TestRunInfo info, final int status) {
if (status == info.getStatus())
return;
if (info.getStatus() == ITestRunListener.STATUS_OK) {
if (status == ITestRunListener.STATUS_FAILURE)
fFailureCount++;
else if (status == ITestRunListener.STATUS_ERROR)
fErrorCount++;
} else if (info.getStatus() == ITestRunListener.STATUS_ERROR) {
if (status == ITestRunListener.STATUS_OK)
fErrorCount--;
else if (status == ITestRunListener.STATUS_FAILURE) {
fErrorCount--;
fFailureCount++;
}
} else if (info.getStatus() == ITestRunListener.STATUS_FAILURE) {
if (status == ITestRunListener.STATUS_OK)
fFailureCount--;
else if (status == ITestRunListener.STATUS_ERROR) {
fFailureCount--;
fErrorCount++;
}
}
info.setStatus(status);
final TestRunInfo finalInfo= info;
postSyncRunnable(new Runnable() {
public void run() {
refreshCounters();
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.testStatusChanged(finalInfo);
}
}
});
}
/*
* @see ITestRunListener#testTreeEntry
*/
public void testTreeEntry(final String treeEntry){
postSyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.newTreeEntry(treeEntry);
}
}
});
}
public void startTestRunListening(IJavaElement type, int port, ILaunch launch) {
fTestProject= type.getJavaProject();
fLaunchMode= launch.getLaunchMode();
aboutToLaunch();
if (fTestRunnerClient != null) {
stopTest();
}
fTestRunnerClient= new RemoteTestRunnerClient();
// add the TestRunnerViewPart to the list of registered listeners
List listeners= JUnitPlugin.getDefault().getTestRunListeners();
ITestRunListener[] listenerArray= new ITestRunListener[listeners.size()+1];
listeners.toArray(listenerArray);
System.arraycopy(listenerArray, 0, listenerArray, 1, listenerArray.length-1);
listenerArray[0]= this;
fTestRunnerClient.startListening(listenerArray, port);
fLastLaunch= launch;
setViewPartTitle(type);
if (type instanceof IType)
setTitleToolTip(((IType)type).getFullyQualifiedName());
else
setTitleToolTip(type.getElementName());
}
private void setViewPartTitle(IJavaElement type) {
String title;
if (type == null)
title= JUnitMessages.getString("TestRunnerViewPart.title_no_type"); //$NON-NLS-1$
else
title= JUnitMessages.getFormattedString("TestRunnerViewPart.title", type.getElementName()); //$NON-NLS-1$
setTitle(title);
}
private void aboutToLaunch() {
String msg= JUnitMessages.getString("TestRunnerViewPart.message.launching"); //$NON-NLS-1$
showInformation(msg);
postInfo(msg);
fViewImage= fOriginalViewImage;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
public synchronized void dispose(){
fIsDisposed= true;
stopTest();
if (fProgressImages != null)
fProgressImages.dispose();
JUnitPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(this);
fTestRunOKIcon.dispose();
fTestRunFailIcon.dispose();
fStackViewIcon.dispose();
fTestRunOKDirtyIcon.dispose();
fTestRunFailDirtyIcon.dispose();
if (fClipboard != null)
fClipboard.dispose();
}
private void start(final int total) {
resetProgressBar(total);
fCounterPanel.setTotal(total);
fCounterPanel.setRunValue(0);
}
private void resetProgressBar(final int total) {
fProgressBar.reset();
fProgressBar.setMaximum(total);
}
private void postSyncRunnable(Runnable r) {
if (!isDisposed())
getDisplay().syncExec(r);
}
private void aboutToStart() {
postSyncRunnable(new Runnable() {
public void run() {
if (!isDisposed()) {
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.aboutToStart();
}
fNextAction.setEnabled(false);
fPreviousAction.setEnabled(false);
}
}
});
}
private void postEndTest(final String testId, final String testName) {
postSyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
handleEndTest();
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.endTest(testId);
}
if (fFailureCount + fErrorCount > 0) {
fNextAction.setEnabled(true);
fPreviousAction.setEnabled(true);
}
}
});
}
private void postStartTest(final String testId, final String testName) {
postSyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.startTest(testId);
}
}
});
}
private void handleEndTest() {
refreshCounters();
fProgressBar.step(fFailureCount+fErrorCount);
if (fShowOnErrorOnly) {
Image progress= fProgressImages.getImage(fExecutedTests, fTestCount, fErrorCount, fFailureCount);
if (progress != fViewImage) {
fViewImage= progress;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
}
}
private void refreshCounters() {
fCounterPanel.setErrorValue(fErrorCount);
fCounterPanel.setFailureValue(fFailureCount);
fCounterPanel.setRunValue(fExecutedTests);
fProgressBar.refresh(fErrorCount+fFailureCount> 0);
}
protected void postShowTestResultsView() {
postSyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
showTestResultsView();
}
});
}
public void showTestResultsView() {
IWorkbenchWindow window= getSite().getWorkbenchWindow();
IWorkbenchPage page= window.getActivePage();
TestRunnerViewPart testRunner= null;
if (page != null) {
try { // show the result view
testRunner= (TestRunnerViewPart)page.findView(TestRunnerViewPart.NAME);
if(testRunner == null) {
IWorkbenchPart activePart= page.getActivePart();
testRunner= (TestRunnerViewPart)page.showView(TestRunnerViewPart.NAME);
//restore focus stolen by the creation of the console
page.activate(activePart);
} else {
page.bringToTop(testRunner);
}
} catch (PartInitException pie) {
JUnitPlugin.log(pie);
}
}
}
protected void postInfo(final String message) {
postSyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
getStatusLine().setErrorMessage(null);
getStatusLine().setMessage(message);
}
});
}
protected void postError(final String message) {
postSyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
getStatusLine().setMessage(null);
getStatusLine().setErrorMessage(message);
}
});
}
protected void showInformation(final String info){
postSyncRunnable(new Runnable() {
public void run() {
if (!isDisposed())
fFailureView.setInformation(info);
}
});
}
private CTabFolder createTestRunViews(Composite parent) {
CTabFolder tabFolder= new CTabFolder(parent, SWT.TOP);
tabFolder.setLayoutData(new GridData(GridData.FILL_BOTH | GridData.GRAB_VERTICAL));
ITestRunView failureRunView= new FailureRunView(tabFolder, fClipboard, this);
ITestRunView testHierarchyRunView= new HierarchyRunView(tabFolder, this);
fTestRunViews.addElement(failureRunView);
fTestRunViews.addElement(testHierarchyRunView);
tabFolder.setSelection(0);
fActiveRunView= (ITestRunView)fTestRunViews.firstElement();
tabFolder.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
testViewChanged(event);
}
});
return tabFolder;
}
private void testViewChanged(SelectionEvent event) {
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
if (((CTabFolder) event.widget).getSelection().getText() == v.getName()){
v.setSelectedTest(fActiveRunView.getSelectedTestId());
fActiveRunView= v;
fActiveRunView.activate();
}
}
}
private SashForm createSashForm(Composite parent) {
fSashForm= new SashForm(parent, SWT.VERTICAL);
ViewForm top= new ViewForm(fSashForm, SWT.NONE);
fTabFolder= createTestRunViews(top);
fTabFolder.setLayoutData(new TabFolderLayout());
top.setContent(fTabFolder);
ViewForm bottom= new ViewForm(fSashForm, SWT.NONE);
CLabel label= new CLabel(bottom, SWT.NONE);
label.setText(JUnitMessages.getString("TestRunnerViewPart.label.failure")); //$NON-NLS-1$
label.setImage(fStackViewIcon);
bottom.setTopLeft(label);
ToolBar failureToolBar= new ToolBar(bottom, SWT.FLAT | SWT.WRAP);
bottom.setTopCenter(failureToolBar);
fFailureView= new FailureTraceView(bottom, fClipboard, this);
bottom.setContent(fFailureView.getComposite());
// fill the failure trace viewer toolbar
ToolBarManager failureToolBarmanager= new ToolBarManager(failureToolBar);
failureToolBarmanager.add(new EnableStackFilterAction(fFailureView));
failureToolBarmanager.update(true);
fSashForm.setWeights(new int[]{50, 50});
return fSashForm;
}
private void reset(final int testCount) {
postSyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
fCounterPanel.reset();
fFailureView.clear();
fProgressBar.reset();
clearStatus();
start(testCount);
}
});
fExecutedTests= 0;
fFailureCount= 0;
fErrorCount= 0;
fTestCount= testCount;
aboutToStart();
fTestInfos.clear();
fFailures= new ArrayList();
}
private void clearStatus() {
getStatusLine().setMessage(null);
getStatusLine().setErrorMessage(null);
}
public void setFocus() {
if (fActiveRunView != null)
fActiveRunView.setFocus();
}
public void createPartControl(Composite parent) {
fClipboard= new Clipboard(parent.getDisplay());
GridLayout gridLayout= new GridLayout();
gridLayout.marginWidth= 0;
gridLayout.marginHeight= 0;
parent.setLayout(gridLayout);
configureToolBar();
Composite counterPanel= createProgressCountPanel(parent);
counterPanel.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL));
SashForm sashForm= createSashForm(parent);
sashForm.setLayoutData(new GridData(GridData.FILL_BOTH));
IActionBars actionBars= getViewSite().getActionBars();
actionBars.setGlobalActionHandler(
IWorkbenchActionConstants.COPY,
new CopyTraceAction(fFailureView, fClipboard));
JUnitPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(this);
fOriginalViewImage= getTitleImage();
fProgressImages= new ProgressImages();
WorkbenchHelp.setHelp(parent, IJUnitHelpContextIds.RESULTS_VIEW);
if (fMemento != null)
restoreLayoutState(fMemento);
fMemento= null;
}
public void saveState(IMemento memento) {
if (fSashForm == null) {
// part has not been created
if (fMemento != null) //Keep the old state;
memento.putMemento(fMemento);
return;
}
int activePage= fTabFolder.getSelectionIndex();
memento.putInteger(TAG_PAGE, activePage);
int weigths[]= fSashForm.getWeights();
int ratio= (weigths[0] * 1000) / (weigths[0] + weigths[1]);
memento.putInteger(TAG_RATIO, ratio);
}
private void configureToolBar() {
IActionBars actionBars= getViewSite().getActionBars();
IToolBarManager toolBar= actionBars.getToolBarManager();
fRerunLastTestAction= new RerunLastAction();
fScrollLockAction= new ScrollLockAction(this);
fNextAction= new ShowNextFailureAction(this);
fPreviousAction= new ShowPreviousFailureAction(this);
fNextAction.setEnabled(false);
fPreviousAction.setEnabled(false);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.NEXT, fNextAction);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.PREVIOUS, fPreviousAction);
toolBar.add(fNextAction);
toolBar.add(fPreviousAction);
toolBar.add(new StopAction());
toolBar.add(new Separator());
toolBar.add(fRerunLastTestAction);
toolBar.add(fScrollLockAction);
fScrollLockAction.setChecked(!fAutoScroll);
actionBars.updateActionBars();
}
private IStatusLineManager getStatusLine() {
// we want to show messages globally hence we
// have to go throgh the active part
IViewSite site= getViewSite();
IWorkbenchPage page= site.getPage();
IWorkbenchPart activePart= page.getActivePart();
if (activePart instanceof IViewPart) {
IViewPart activeViewPart= (IViewPart)activePart;
IViewSite activeViewSite= activeViewPart.getViewSite();
return activeViewSite.getActionBars().getStatusLineManager();
}
if (activePart instanceof IEditorPart) {
IEditorPart activeEditorPart= (IEditorPart)activePart;
IEditorActionBarContributor contributor= activeEditorPart.getEditorSite().getActionBarContributor();
if (contributor instanceof EditorActionBarContributor)
return ((EditorActionBarContributor) contributor).getActionBars().getStatusLineManager();
}
// no active part
return getViewSite().getActionBars().getStatusLineManager();
}
private Composite createProgressCountPanel(Composite parent) {
Composite composite= new Composite(parent, SWT.NONE);
composite.setLayout(new GridLayout());
fProgressBar = new JUnitProgressBar(composite);
fProgressBar.setLayoutData(
new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL));
fCounterPanel = new CounterPanel(composite);
fCounterPanel.setLayoutData(
new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL));
return composite;
}
public TestRunInfo getTestInfo(String testId) {
if (testId == null)
return null;
return (TestRunInfo) fTestInfos.get(testId);
}
public void handleTestSelected(String testId) {
TestRunInfo testInfo= getTestInfo(testId);
if (testInfo == null) {
showFailure(""); //$NON-NLS-1$
} else {
showFailure(testInfo.getTrace());
}
}
private void showFailure(final String failure) {
postSyncRunnable(new Runnable() {
public void run() {
if (!isDisposed())
fFailureView.showFailure(failure);
}
});
}
public IJavaProject getLaunchedProject() {
return fTestProject;
}
public ILaunch getLastLaunch() {
return fLastLaunch;
}
protected static Image createImage(String path) {
try {
ImageDescriptor id= ImageDescriptor.createFromURL(JUnitPlugin.makeIconFileURL(path));
return id.createImage();
} catch (MalformedURLException e) {
// fall through
}
return null;
}
private boolean isDisposed() {
return fIsDisposed || fCounterPanel.isDisposed();
}
private Display getDisplay() {
return getViewSite().getShell().getDisplay();
}
/**
* @see IWorkbenchPart#getTitleImage()
*/
public Image getTitleImage() {
if (fOriginalViewImage == null)
fOriginalViewImage= super.getTitleImage();
if (fViewImage == null)
return super.getTitleImage();
return fViewImage;
}
public void propertyChange(PropertyChangeEvent event) {
if (isDisposed())
return;
if (IJUnitPreferencesConstants.SHOW_ON_ERROR_ONLY.equals(event.getProperty())) {
if (!JUnitPreferencePage.getShowOnErrorOnly()) {
fViewImage= fOriginalViewImage;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
}
}
void codeHasChanged() {
postSyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
if (fDirtyListener != null) {
JavaCore.removeElementChangedListener(fDirtyListener);
fDirtyListener= null;
}
if (fViewImage == fTestRunOKIcon)
fViewImage= fTestRunOKDirtyIcon;
else if (fViewImage == fTestRunFailIcon)
fViewImage= fTestRunFailDirtyIcon;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
});
}
boolean isCreated() {
return fCounterPanel != null;
}
public void rerunTest(String testId, String className, String testName) {
DebugUITools.saveAndBuildBeforeLaunch();
if (fTestRunnerClient != null && fTestRunnerClient.isRunning() && ILaunchManager.DEBUG_MODE.equals(fLaunchMode))
fTestRunnerClient.rerunTest(testId, className, testName);
else if (fLastLaunch != null) {
// run the selected test using the previous launch configuration
ILaunchConfiguration launchConfiguration= fLastLaunch.getLaunchConfiguration();
if (launchConfiguration != null) {
try {
ILaunchConfigurationWorkingCopy tmp= launchConfiguration.copy("Rerun "+testName); //$NON-NLS-1$
tmp.setAttribute(JUnitBaseLaunchConfiguration.TESTNAME_ATTR, testName);
tmp.launch(fLastLaunch.getLaunchMode(), null);
return;
} catch (CoreException e) {
ErrorDialog.openError(getSite().getShell(),
JUnitMessages.getString("TestRunnerViewPart.error.cannotrerun"), e.getMessage(), e.getStatus() //$NON-NLS-1$
);
}
}
MessageDialog.openInformation(getSite().getShell(),
JUnitMessages.getString("TestRunnerViewPart.cannotrerun.title"), //$NON-NLS-1$
JUnitMessages.getString("TestRunnerViewPart.cannotrerurn.message") //$NON-NLS-1$
);
}
}
}
|
13,617 |
Bug 13617 [navigation] Next problem doesn't always update status line
|
Build 20020409 - new Java class Test - insert method: public void run() { } - replace void with voyd by replacing i with y (cursor should be positions after y) - save (with autobuild on) - it finds the problem and displays it in the ruler, shows squiggles, and adds it to the task list - however, it is not shown in the status line - hit Ctrl+E - it has no effect - move the cursor outside the squiggle - hit Ctrl+E again - now it works and the status line updates - place the cursor above this line - hit Ctrl+E - it repositions on the error, but the status line is blank The status line should always show the error when Next/Prev Problem is used. Also, it would be good if it showed the error whenever the cursor entered an error range.
|
resolved fixed
|
10bb3e7
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-19T13:11:54Z | 2002-04-12T14:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/JavaEditor.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.javaeditor;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ResourceBundle;
import java.util.StringTokenizer;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Preferences;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BidiSegmentEvent;
import org.eclipse.swt.custom.BidiSegmentListener;
import org.eclipse.swt.custom.StyleRange;
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.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
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.Separator;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.IPostSelectionProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.text.BadLocationException;
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.ITextInputListener;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.ITextViewerExtension2;
import org.eclipse.jface.text.ITextViewerExtension3;
import org.eclipse.jface.text.ITextViewerExtension4;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.text.TextUtilities;
import org.eclipse.jface.text.information.IInformationProvider;
import org.eclipse.jface.text.information.IInformationProviderExtension2;
import org.eclipse.jface.text.information.InformationPresenter;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.IAnnotationAccess;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.IOverviewRuler;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.IVerticalRuler;
import org.eclipse.jface.text.source.LineChangeHover;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
import org.eclipse.ui.IEditorActionBarContributor;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPartService;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.EditorActionBarContributor;
import org.eclipse.ui.part.IShowInTargetList;
import org.eclipse.ui.texteditor.AddTaskAction;
import org.eclipse.ui.texteditor.AnnotationPreference;
import org.eclipse.ui.texteditor.DefaultRangeIndicator;
import org.eclipse.ui.texteditor.ExtendedTextEditor;
import org.eclipse.ui.texteditor.IAbstractTextEditorHelpContextIds;
import org.eclipse.ui.texteditor.IEditorStatusLine;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
import org.eclipse.ui.texteditor.MarkerAnnotation;
import org.eclipse.ui.texteditor.ResourceAction;
import org.eclipse.ui.texteditor.SourceViewerDecorationSupport;
import org.eclipse.ui.texteditor.TextEditorAction;
import org.eclipse.ui.texteditor.TextOperationAction;
import org.eclipse.ui.views.contentoutline.ContentOutline;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
import org.eclipse.ui.views.tasklist.TaskList;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICodeAssist;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IImportContainer;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IPackageDeclaration;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.ISourceReference;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.actions.IJavaEditorActionDefinitionIds;
import org.eclipse.jdt.ui.actions.JavaSearchActionGroup;
import org.eclipse.jdt.ui.actions.OpenEditorActionGroup;
import org.eclipse.jdt.ui.actions.OpenViewActionGroup;
import org.eclipse.jdt.ui.actions.ShowActionGroup;
import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.GoToNextPreviousMemberAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.SelectionHistory;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectEnclosingAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectHistoryAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectNextAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectPreviousAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectionAction;
import org.eclipse.jdt.internal.ui.text.HTMLTextPresenter;
import org.eclipse.jdt.internal.ui.text.IJavaPartitions;
import org.eclipse.jdt.internal.ui.text.JavaChangeHover;
import org.eclipse.jdt.internal.ui.text.JavaPairMatcher;
import org.eclipse.jdt.internal.ui.util.JavaUIHelp;
import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider;
/**
* Java specific text editor.
*/
public abstract class JavaEditor extends ExtendedTextEditor implements IViewPartInputProvider {
/**
* Internal implementation class for a change listener.
* @since 3.0
*/
protected abstract class AbstractSelectionChangedListener implements ISelectionChangedListener {
/**
* Installs this selection changed listener with the given selection provider. If
* the selection provider is a post selection provider, post selection changed
* events are the preferred choice, otherwise normal selection changed events
* are requested.
*
* @param selectionProvider
*/
public void install(ISelectionProvider selectionProvider) {
if (selectionProvider == null)
return;
if (selectionProvider instanceof IPostSelectionProvider) {
IPostSelectionProvider provider= (IPostSelectionProvider) selectionProvider;
provider.addPostSelectionChangedListener(this);
} else {
selectionProvider.addSelectionChangedListener(this);
}
}
/**
* Removes this selection changed listener from the given selection provider.
*
* @param selectionProvider
*/
public void uninstall(ISelectionProvider selectionProvider) {
if (selectionProvider == null)
return;
if (selectionProvider instanceof IPostSelectionProvider) {
IPostSelectionProvider provider= (IPostSelectionProvider) selectionProvider;
provider.removePostSelectionChangedListener(this);
} else {
selectionProvider.removeSelectionChangedListener(this);
}
}
}
/**
* Updates the Java outline page selection and this editor's range indicator.
*
* @since 3.0
*/
private class EditorSelectionChangedListener extends AbstractSelectionChangedListener {
/*
* @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent)
*/
public void selectionChanged(SelectionChangedEvent event) {
selectionChanged();
}
public void selectionChanged() {
ISourceReference element= computeHighlightRangeSourceReference();
synchronizeOutlinePage(element);
setSelection(element, false);
}
}
/**
* Updates the selection in the editor's widget with the selection of the outline page.
*/
class OutlineSelectionChangedListener extends AbstractSelectionChangedListener {
public void selectionChanged(SelectionChangedEvent event) {
doSelectionChanged(event);
}
}
/*
* Link mode.
*/
class MouseClickListener implements KeyListener, MouseListener, MouseMoveListener,
FocusListener, PaintListener, IPropertyChangeListener, IDocumentListener, ITextInputListener {
/** The session is active. */
private boolean fActive;
/** The currently active style range. */
private IRegion fActiveRegion;
/** The currently active style range as position. */
private Position fRememberedPosition;
/** The hand cursor. */
private Cursor fCursor;
/** The link color. */
private Color fColor;
/** The key modifier mask. */
private int fKeyModifierMask;
public void deactivate() {
deactivate(false);
}
public void deactivate(boolean redrawAll) {
if (!fActive)
return;
repairRepresentation(redrawAll);
fActive= false;
}
public void install() {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
StyledText text= sourceViewer.getTextWidget();
if (text == null || text.isDisposed())
return;
updateColor(sourceViewer);
sourceViewer.addTextInputListener(this);
IDocument document= sourceViewer.getDocument();
if (document != null)
document.addDocumentListener(this);
text.addKeyListener(this);
text.addMouseListener(this);
text.addMouseMoveListener(this);
text.addFocusListener(this);
text.addPaintListener(this);
updateKeyModifierMask();
IPreferenceStore preferenceStore= getPreferenceStore();
preferenceStore.addPropertyChangeListener(this);
}
private void updateKeyModifierMask() {
String modifiers= getPreferenceStore().getString(BROWSER_LIKE_LINKS_KEY_MODIFIER);
fKeyModifierMask= computeStateMask(modifiers);
if (fKeyModifierMask == -1) {
// Fallback to stored state mask
fKeyModifierMask= getPreferenceStore().getInt(BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK);
}
}
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;
}
public void uninstall() {
if (fColor != null) {
fColor.dispose();
fColor= null;
}
if (fCursor != null) {
fCursor.dispose();
fCursor= null;
}
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
sourceViewer.removeTextInputListener(this);
IDocument document= sourceViewer.getDocument();
if (document != null)
document.removeDocumentListener(this);
IPreferenceStore preferenceStore= getPreferenceStore();
if (preferenceStore != null)
preferenceStore.removePropertyChangeListener(this);
StyledText text= sourceViewer.getTextWidget();
if (text == null || text.isDisposed())
return;
text.removeKeyListener(this);
text.removeMouseListener(this);
text.removeMouseMoveListener(this);
text.removeFocusListener(this);
text.removePaintListener(this);
}
/*
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
if (event.getProperty().equals(JavaEditor.LINK_COLOR)) {
ISourceViewer viewer= getSourceViewer();
if (viewer != null)
updateColor(viewer);
} else if (event.getProperty().equals(BROWSER_LIKE_LINKS_KEY_MODIFIER)) {
updateKeyModifierMask();
}
}
private void updateColor(ISourceViewer viewer) {
if (fColor != null)
fColor.dispose();
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
Display display= text.getDisplay();
fColor= createColor(getPreferenceStore(), JavaEditor.LINK_COLOR, display);
}
/**
* 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);
if (rgb != null)
return new Color(display, rgb);
}
return null;
}
private void repairRepresentation() {
repairRepresentation(false);
}
private void repairRepresentation(boolean redrawAll) {
if (fActiveRegion == null)
return;
ISourceViewer viewer= getSourceViewer();
if (viewer != null) {
resetCursor(viewer);
int offset= fActiveRegion.getOffset();
int length= fActiveRegion.getLength();
// remove style
if (!redrawAll && viewer instanceof ITextViewerExtension2)
((ITextViewerExtension2) viewer).invalidateTextPresentation(offset, length);
else
viewer.invalidateTextPresentation();
// remove underline
if (viewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) viewer;
offset= extension.modelOffset2WidgetOffset(offset);
} else {
offset -= viewer.getVisibleRegion().getOffset();
}
StyledText text= viewer.getTextWidget();
try {
text.redrawRange(offset, length, true);
} catch (IllegalArgumentException x) {
JavaPlugin.log(x);
}
}
fActiveRegion= null;
}
// will eventually be replaced by a method provided by jdt.core
private IRegion selectWord(IDocument document, int anchor) {
try {
int offset= anchor;
char c;
while (offset >= 0) {
c= document.getChar(offset);
if (!Character.isJavaIdentifierPart(c))
break;
--offset;
}
int start= offset;
offset= anchor;
int length= document.getLength();
while (offset < length) {
c= document.getChar(offset);
if (!Character.isJavaIdentifierPart(c))
break;
++offset;
}
int end= offset;
if (start == end)
return new Region(start, 0);
else
return new Region(start + 1, end - start - 1);
} catch (BadLocationException x) {
return null;
}
}
IRegion getCurrentTextRegion(ISourceViewer viewer) {
int offset= getCurrentTextOffset(viewer);
if (offset == -1)
return null;
IJavaElement input= SelectionConverter.getInput(JavaEditor.this);
if (input == null)
return null;
try {
IJavaElement[] elements= null;
synchronized (input) {
elements= ((ICodeAssist) input).codeSelect(offset, 0);
}
if (elements == null || elements.length == 0)
return null;
return selectWord(viewer.getDocument(), offset);
} catch (JavaModelException e) {
return null;
}
}
private int getCurrentTextOffset(ISourceViewer viewer) {
try {
StyledText text= viewer.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 (viewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) viewer;
return extension.widgetOffset2ModelOffset(widgetOffset);
} else {
return widgetOffset + viewer.getVisibleRegion().getOffset();
}
} catch (IllegalArgumentException e) {
return -1;
}
}
private void highlightRegion(ISourceViewer viewer, IRegion region) {
if (region.equals(fActiveRegion))
return;
repairRepresentation();
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
// highlight region
int offset= 0;
int length= 0;
if (viewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) viewer;
IRegion widgetRange= extension.modelRange2WidgetRange(region);
if (widgetRange == null)
return;
offset= widgetRange.getOffset();
length= widgetRange.getLength();
} else {
offset= region.getOffset() - viewer.getVisibleRegion().getOffset();
length= region.getLength();
}
StyleRange oldStyleRange= text.getStyleRangeAtOffset(offset);
Color foregroundColor= fColor;
Color backgroundColor= oldStyleRange == null ? text.getBackground() : oldStyleRange.background;
StyleRange styleRange= new StyleRange(offset, length, foregroundColor, backgroundColor);
text.setStyleRange(styleRange);
// underline
text.redrawRange(offset, length, true);
fActiveRegion= region;
}
private void activateCursor(ISourceViewer 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 void resetCursor(ISourceViewer viewer) {
StyledText text= viewer.getTextWidget();
if (text != null && !text.isDisposed())
text.setCursor(null);
if (fCursor != null) {
fCursor.dispose();
fCursor= null;
}
}
/*
* @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.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;
deactivate();
if (wasActive) {
IAction action= getAction("OpenEditor"); //$NON-NLS-1$
if (action != null)
action.run();
}
}
/*
* @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;
}
ISourceViewer viewer= getSourceViewer();
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= getCurrentTextRegion(viewer);
if (region == null || region.getLength() == 0) {
repairRepresentation();
return;
}
highlightRegion(viewer, region);
activateCursor(viewer);
}
/*
* @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();
}
/*
* @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 && !fRememberedPosition.isDeleted()) {
event.getDocument().removePosition(fRememberedPosition);
fActiveRegion= new Region(fRememberedPosition.getOffset(), fRememberedPosition.getLength());
}
fRememberedPosition= null;
ISourceViewer viewer= getSourceViewer();
if (viewer != null) {
StyledText widget= viewer.getTextWidget();
if (widget != null && !widget.isDisposed()) {
widget.getDisplay().asyncExec(new Runnable() {
public void run() {
deactivate();
}
});
}
}
}
/*
* @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);
}
/*
* @see PaintListener#paintControl(PaintEvent)
*/
public void paintControl(PaintEvent event) {
if (fActiveRegion == null)
return;
ISourceViewer viewer= getSourceViewer();
if (viewer == null)
return;
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
int offset= 0;
int length= 0;
if (viewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) viewer;
IRegion widgetRange= extension.modelRange2WidgetRange(new Region(offset, length));
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);
}
private boolean includes(IRegion region, IRegion position) {
return
position.getOffset() >= region.getOffset() &&
position.getOffset() + position.getLength() <= region.getOffset() + region.getLength();
}
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 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;
}
}
/**
* This action dispatches into two behaviours: If there is no current text
* hover, the javadoc is displayed using information presenter. If there is
* a current text hover, it is converted into a information presenter in
* order to make it sticky.
*/
class InformationDispatchAction extends TextEditorAction {
/** The wrapped text operation action. */
private final TextOperationAction fTextOperationAction;
/**
* Creates a dispatch action.
*/
public InformationDispatchAction(ResourceBundle resourceBundle, String prefix, final TextOperationAction textOperationAction) {
super(resourceBundle, prefix, JavaEditor.this);
if (textOperationAction == null)
throw new IllegalArgumentException();
fTextOperationAction= textOperationAction;
}
/*
* @see org.eclipse.jface.action.IAction#run()
*/
public void run() {
/**
* Information provider used to present the information.
*
* @since 3.0
*/
class InformationProvider implements IInformationProvider, IInformationProviderExtension2 {
private IRegion fHoverRegion;
private String fHoverInfo;
private IInformationControlCreator fControlCreator;
InformationProvider(IRegion hoverRegion, String hoverInfo, IInformationControlCreator controlCreator) {
fHoverRegion= hoverRegion;
fHoverInfo= hoverInfo;
fControlCreator= controlCreator;
}
/*
* @see org.eclipse.jface.text.information.IInformationProvider#getSubject(org.eclipse.jface.text.ITextViewer, int)
*/
public IRegion getSubject(ITextViewer textViewer, int invocationOffset) {
return fHoverRegion;
}
/*
* @see org.eclipse.jface.text.information.IInformationProvider#getInformation(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion)
*/
public String getInformation(ITextViewer textViewer, IRegion subject) {
return fHoverInfo;
}
/*
* @see org.eclipse.jface.text.information.IInformationProviderExtension2#getInformationPresenterControlCreator()
* @since 3.0
*/
public IInformationControlCreator getInformationPresenterControlCreator() {
return fControlCreator;
}
}
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null) {
fTextOperationAction.run();
return;
}
if (sourceViewer instanceof ITextViewerExtension4) {
ITextViewerExtension4 extension4= (ITextViewerExtension4) sourceViewer;
extension4.moveFocusToWidgetToken();
}
if (! (sourceViewer instanceof ITextViewerExtension2)) {
fTextOperationAction.run();
return;
}
ITextViewerExtension2 textViewerExtension2= (ITextViewerExtension2) sourceViewer;
// does a text hover exist?
ITextHover textHover= textViewerExtension2.getCurrentTextHover();
if (textHover == null) {
fTextOperationAction.run();
return;
}
Point hoverEventLocation= textViewerExtension2.getHoverEventLocation();
int offset= computeOffsetAtLocation(sourceViewer, hoverEventLocation.x, hoverEventLocation.y);
if (offset == -1) {
fTextOperationAction.run();
return;
}
try {
// get the text hover content
String contentType= TextUtilities.getContentType(sourceViewer.getDocument(), IJavaPartitions.JAVA_PARTITIONING, offset);
IRegion hoverRegion= textHover.getHoverRegion(sourceViewer, offset);
if (hoverRegion == null)
return;
String hoverInfo= textHover.getHoverInfo(sourceViewer, hoverRegion);
IInformationControlCreator controlCreator= null;
if (textHover instanceof IInformationProviderExtension2)
controlCreator= ((IInformationProviderExtension2)textHover).getInformationPresenterControlCreator();
IInformationProvider informationProvider= new InformationProvider(hoverRegion, hoverInfo, controlCreator);
fInformationPresenter.setOffset(offset);
fInformationPresenter.setInformationProvider(informationProvider, contentType);
fInformationPresenter.showInformation();
} catch (BadLocationException e) {
}
}
// modified version from TextViewer
private int computeOffsetAtLocation(ITextViewer textViewer, int x, int y) {
StyledText styledText= textViewer.getTextWidget();
IDocument document= textViewer.getDocument();
if (document == null)
return -1;
try {
int widgetLocation= styledText.getOffsetAtLocation(new Point(x, y));
if (textViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) textViewer;
return extension.widgetOffset2ModelOffset(widgetLocation);
} else {
IRegion visibleRegion= textViewer.getVisibleRegion();
return widgetLocation + visibleRegion.getOffset();
}
} catch (IllegalArgumentException e) {
return -1;
}
}
}
static protected class AnnotationAccess implements IAnnotationAccess {
/*
* @see org.eclipse.jface.text.source.IAnnotationAccess#getType(org.eclipse.jface.text.source.Annotation)
*/
public Object getType(Annotation annotation) {
if (annotation instanceof IJavaAnnotation) {
IJavaAnnotation javaAnnotation= (IJavaAnnotation) annotation;
if (javaAnnotation.isRelevant())
return javaAnnotation.getAnnotationType();
}
return null;
}
/*
* @see org.eclipse.jface.text.source.IAnnotationAccess#isMultiLine(org.eclipse.jface.text.source.Annotation)
*/
public boolean isMultiLine(Annotation annotation) {
return true;
}
/*
* @see org.eclipse.jface.text.source.IAnnotationAccess#isTemporary(org.eclipse.jface.text.source.Annotation)
*/
public boolean isTemporary(Annotation annotation) {
if (annotation instanceof IJavaAnnotation) {
IJavaAnnotation javaAnnotation= (IJavaAnnotation) annotation;
if (javaAnnotation.isRelevant())
return javaAnnotation.isTemporary();
}
return false;
}
}
private class PropertyChangeListener implements org.eclipse.core.runtime.Preferences.IPropertyChangeListener {
/*
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
handlePreferencePropertyChanged(event);
}
}
/** Preference key for the link color */
protected final static String LINK_COLOR= PreferenceConstants.EDITOR_LINK_COLOR;
/** Preference key for matching brackets */
protected final static String MATCHING_BRACKETS= PreferenceConstants.EDITOR_MATCHING_BRACKETS;
/** Preference key for matching brackets color */
protected final static String MATCHING_BRACKETS_COLOR= PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR;
/** Preference key for compiler task tags */
private final static String COMPILER_TASK_TAGS= JavaCore.COMPILER_TASK_TAGS;
/** Preference key for browser like links */
private final static String BROWSER_LIKE_LINKS= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS;
/** Preference key for key modifier of browser like links */
private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER;
/**
* Preference key for key modifier mask of browser like links.
* The value is only used if the value of <code>EDITOR_BROWSER_LIKE_LINKS</code>
* cannot be resolved to valid SWT modifier bits.
*
* @since 2.1.1
*/
private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK;
protected final static char[] BRACKETS= { '{', '}', '(', ')', '[', ']' };
/** The outline page */
protected JavaOutlinePage fOutlinePage;
/** Outliner context menu Id */
protected String fOutlinerContextMenuId;
/**
* The editor selection changed listener.
*
* @since 3.0
*/
private EditorSelectionChangedListener fEditorSelectionChangedListener;
/** The selection changed listener */
protected AbstractSelectionChangedListener fOutlineSelectionChangedListener= new OutlineSelectionChangedListener();
/** The editor's bracket matcher */
protected JavaPairMatcher fBracketMatcher= new JavaPairMatcher(BRACKETS);
/** The mouse listener */
private MouseClickListener fMouseListener;
/** The information presenter. */
private InformationPresenter fInformationPresenter;
/** History for structure select action */
private SelectionHistory fSelectionHistory;
/** The preference property change listener for java core. */
private org.eclipse.core.runtime.Preferences.IPropertyChangeListener fPropertyChangeListener= new PropertyChangeListener();
protected CompositeActionGroup fActionGroups;
private CompositeActionGroup fContextMenuGroup;
/**
* Returns the most narrow java element including the given offset.
*
* @param offset the offset inside of the requested element
* @return the most narrow java element
*/
abstract protected IJavaElement getElementAt(int offset);
/**
* Returns the java element of this editor's input corresponding to the given IJavaElement
*/
abstract protected IJavaElement getCorrespondingElement(IJavaElement element);
/**
* Sets the input of the editor's outline page.
*/
abstract protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input);
/**
* Default constructor.
*/
public JavaEditor() {
super();
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
setSourceViewerConfiguration(new JavaSourceViewerConfiguration(textTools, this, IJavaPartitions.JAVA_PARTITIONING));
setRangeIndicator(new DefaultRangeIndicator());
setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore());
setKeyBindingScopes(new String[] { "org.eclipse.jdt.ui.javaEditorScope" }); //$NON-NLS-1$
}
/*
* @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
*/
protected final ISourceViewer createSourceViewer(Composite parent, IVerticalRuler verticalRuler, int styles) {
ISourceViewer viewer= createJavaSourceViewer(parent, verticalRuler, getOverviewRuler(), isPrefOverviewRulerVisible(), styles);
StyledText text= viewer.getTextWidget();
text.addBidiSegmentListener(new BidiSegmentListener() {
public void lineGetSegments(BidiSegmentEvent event) {
event.segments= getBidiLineSegments(event.lineOffset, event.lineText);
}
});
JavaUIHelp.setHelp(this, text, IJavaHelpContextIds.JAVA_EDITOR);
// ensure source viewer decoration support has been created and configured
getSourceViewerDecorationSupport(viewer);
return viewer;
}
/*
* @see org.eclipse.ui.texteditor.ExtendedTextEditor#createAnnotationAccess()
*/
protected IAnnotationAccess createAnnotationAccess() {
return new AnnotationAccess();
}
public final ISourceViewer getViewer() {
return getSourceViewer();
}
/*
* @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
*/
protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean isOverviewRulerVisible, int styles) {
return new JavaSourceViewer(parent, verticalRuler, getOverviewRuler(), isPrefOverviewRulerVisible(), styles);
}
/*
* @see AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent)
*/
protected boolean affectsTextPresentation(PropertyChangeEvent event) {
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
return textTools.affectsBehavior(event);
}
/**
* Sets the outliner's context menu ID.
*/
protected void setOutlinerContextMenuId(String menuId) {
fOutlinerContextMenuId= menuId;
}
/**
* Returns the standard action group of this editor.
*/
protected ActionGroup getActionGroup() {
return fActionGroups;
}
/*
* @see AbstractTextEditor#editorContextMenuAboutToShow
*/
public void editorContextMenuAboutToShow(IMenuManager menu) {
super.editorContextMenuAboutToShow(menu);
menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, new Separator(IContextMenuConstants.GROUP_OPEN));
menu.insertAfter(IContextMenuConstants.GROUP_OPEN, new GroupMarker(IContextMenuConstants.GROUP_SHOW));
ActionContext context= new ActionContext(getSelectionProvider().getSelection());
fContextMenuGroup.setContext(context);
fContextMenuGroup.fillContextMenu(menu);
fContextMenuGroup.setContext(null);
}
/**
* Creates the outline page used with this editor.
*/
protected JavaOutlinePage createOutlinePage() {
JavaOutlinePage page= new JavaOutlinePage(fOutlinerContextMenuId, this);
fOutlineSelectionChangedListener.install(page);
setOutlinePageInput(page, getEditorInput());
return page;
}
/**
* Informs the editor that its outliner has been closed.
*/
public void outlinePageClosed() {
if (fOutlinePage != null) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage= null;
resetHighlightRange();
}
}
/**
* Synchronizes the outliner selection with the given element
* position in the editor.
*
* @param element the java element to select
*/
protected void synchronizeOutlinePage(ISourceReference element) {
synchronizeOutlinePage(element, true);
}
/**
* Synchronizes the outliner selection with the given element
* position in the editor.
*
* @param element the java element to select
* @param checkIfOutlinePageActive <code>true</code> if check for active outline page needs to be done
*/
protected void synchronizeOutlinePage(ISourceReference element, boolean checkIfOutlinePageActive) {
if (fOutlinePage != null && element != null && !(checkIfOutlinePageActive && isJavaOutlinePageActive())) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage.select(element);
fOutlineSelectionChangedListener.install(fOutlinePage);
}
}
/**
* Synchronizes the outliner selection with the actual cursor
* position in the editor.
*/
public void synchronizeOutlinePageSelection() {
synchronizeOutlinePage(computeHighlightRangeSourceReference());
}
/*
* Get the desktop's StatusLineManager
*/
protected IStatusLineManager getStatusLineManager() {
IEditorActionBarContributor contributor= getEditorSite().getActionBarContributor();
if (contributor instanceof EditorActionBarContributor) {
return ((EditorActionBarContributor) contributor).getActionBars().getStatusLineManager();
}
return null;
}
/*
* @see AbstractTextEditor#getAdapter(Class)
*/
public Object getAdapter(Class required) {
if (IContentOutlinePage.class.equals(required)) {
if (fOutlinePage == null)
fOutlinePage= createOutlinePage();
return fOutlinePage;
}
if (required == IShowInTargetList.class) {
return new IShowInTargetList() {
public String[] getShowInTargetIds() {
return new String[] { JavaUI.ID_PACKAGES, IPageLayout.ID_OUTLINE, IPageLayout.ID_RES_NAV };
}
};
}
return super.getAdapter(required);
}
protected void setSelection(ISourceReference reference, boolean moveCursor) {
ISelection selection= getSelectionProvider().getSelection();
if (selection instanceof TextSelection) {
TextSelection textSelection= (TextSelection) selection;
if (textSelection.getOffset() != 0 || textSelection.getLength() != 0)
markInNavigationHistory();
}
if (reference != null) {
StyledText textWidget= null;
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer != null)
textWidget= sourceViewer.getTextWidget();
if (textWidget == null)
return;
try {
ISourceRange range= reference.getSourceRange();
if (range == null)
return;
int offset= range.getOffset();
int length= range.getLength();
if (offset < 0 || length < 0)
return;
setHighlightRange(offset, length, moveCursor);
if (!moveCursor)
return;
offset= -1;
length= -1;
if (reference instanceof IMember) {
range= ((IMember) reference).getNameRange();
if (range != null) {
offset= range.getOffset();
length= range.getLength();
}
} else if (reference instanceof IImportDeclaration) {
String name= ((IImportDeclaration) reference).getElementName();
if (name != null && name.length() > 0) {
String content= reference.getSource();
if (content != null) {
offset= range.getOffset() + content.indexOf(name);
length= name.length();
}
}
} else if (reference instanceof IPackageDeclaration) {
String name= ((IPackageDeclaration) reference).getElementName();
if (name != null && name.length() > 0) {
String content= reference.getSource();
if (content != null) {
offset= range.getOffset() + content.indexOf(name);
length= name.length();
}
}
}
if (offset > -1 && length > 0) {
try {
textWidget.setRedraw(false);
sourceViewer.revealRange(offset, length);
sourceViewer.setSelectedRange(offset, length);
} finally {
textWidget.setRedraw(true);
}
markInNavigationHistory();
}
} catch (JavaModelException x) {
} catch (IllegalArgumentException x) {
}
} else if (moveCursor) {
resetHighlightRange();
markInNavigationHistory();
}
}
public void setSelection(IJavaElement element) {
if (element == null || element instanceof ICompilationUnit || element instanceof IClassFile) {
/*
* If the element is an ICompilationUnit this unit is either the input
* of this editor or not being displayed. In both cases, nothing should
* happened. (http://dev.eclipse.org/bugs/show_bug.cgi?id=5128)
*/
return;
}
IJavaElement corresponding= getCorrespondingElement(element);
if (corresponding instanceof ISourceReference) {
ISourceReference reference= (ISourceReference) corresponding;
// set hightlight range
setSelection(reference, true);
// set outliner selection
if (fOutlinePage != null) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage.select(reference);
fOutlineSelectionChangedListener.install(fOutlinePage);
}
}
}
protected void doSelectionChanged(SelectionChangedEvent event) {
ISourceReference reference= null;
ISelection selection= event.getSelection();
Iterator iter= ((IStructuredSelection) selection).iterator();
while (iter.hasNext()) {
Object o= iter.next();
if (o instanceof ISourceReference) {
reference= (ISourceReference) o;
break;
}
}
if (!isActivePart() && JavaPlugin.getActivePage() != null)
JavaPlugin.getActivePage().bringToTop(this);
setSelection(reference, !isActivePart());
}
/*
* @see AbstractTextEditor#adjustHighlightRange(int, int)
*/
protected void adjustHighlightRange(int offset, int length) {
try {
IJavaElement element= getElementAt(offset);
while (element instanceof ISourceReference) {
ISourceRange range= ((ISourceReference) element).getSourceRange();
if (offset < range.getOffset() + range.getLength() && range.getOffset() < offset + length) {
setHighlightRange(range.getOffset(), range.getLength(), true);
if (fOutlinePage != null) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage.select((ISourceReference) element);
fOutlineSelectionChangedListener.install(fOutlinePage);
}
return;
}
element= element.getParent();
}
} catch (JavaModelException x) {
JavaPlugin.log(x.getStatus());
}
resetHighlightRange();
}
protected boolean isActivePart() {
IWorkbenchPart part= getActivePart();
return part != null && part.equals(this);
}
private boolean isJavaOutlinePageActive() {
IWorkbenchPart part= getActivePart();
return part instanceof ContentOutline && ((ContentOutline)part).getCurrentPage() == fOutlinePage;
}
private IWorkbenchPart getActivePart() {
IWorkbenchWindow window= getSite().getWorkbenchWindow();
IPartService service= window.getPartService();
IWorkbenchPart part= service.getActivePart();
return part;
}
/*
* @see AbstractTextEditor#doSetInput
*/
protected void doSetInput(IEditorInput input) throws CoreException {
super.doSetInput(input);
setOutlinePageInput(fOutlinePage, input);
}
/*
* @see IWorkbenchPart#dispose()
*/
public void dispose() {
if (isBrowserLikeLinks())
disableBrowserLikeLinks();
if (fPropertyChangeListener != null) {
Preferences preferences= JavaCore.getPlugin().getPluginPreferences();
preferences.removePropertyChangeListener(fPropertyChangeListener);
fPropertyChangeListener= null;
}
if (fBracketMatcher != null) {
fBracketMatcher.dispose();
fBracketMatcher= null;
}
if (fSelectionHistory != null) {
fSelectionHistory.dispose();
fSelectionHistory= null;
}
if (fEditorSelectionChangedListener != null) {
fEditorSelectionChangedListener.uninstall(getSelectionProvider());
fEditorSelectionChangedListener= null;
}
super.dispose();
}
protected void createActions() {
super.createActions();
ResourceAction resAction= new AddTaskAction(JavaEditorMessages.getResourceBundle(), "AddTask.", this); //$NON-NLS-1$
resAction.setHelpContextId(IAbstractTextEditorHelpContextIds.ADD_TASK_ACTION);
resAction.setActionDefinitionId(ITextEditorActionDefinitionIds.ADD_TASK);
setAction(ITextEditorActionConstants.ADD_TASK, resAction);
ActionGroup oeg, ovg, jsg, sg;
fActionGroups= new CompositeActionGroup(new ActionGroup[] {
oeg= new OpenEditorActionGroup(this),
sg= new ShowActionGroup(this),
ovg= new OpenViewActionGroup(this),
jsg= new JavaSearchActionGroup(this)
});
fContextMenuGroup= new CompositeActionGroup(new ActionGroup[] {oeg, ovg, sg, jsg});
resAction= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc.", this, ISourceViewer.INFORMATION, true); //$NON-NLS-1$
resAction= new InformationDispatchAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc.", (TextOperationAction) resAction); //$NON-NLS-1$
resAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_JAVADOC);
setAction("ShowJavaDoc", resAction); //$NON-NLS-1$
WorkbenchHelp.setHelp(resAction, IJavaHelpContextIds.SHOW_JAVADOC_ACTION);
Action action= new GotoMatchingBracketAction(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_MATCHING_BRACKET);
setAction(GotoMatchingBracketAction.GOTO_MATCHING_BRACKET, action);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"ShowOutline.", this, JavaSourceViewer.SHOW_OUTLINE, true); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_OUTLINE);
setAction(IJavaEditorActionDefinitionIds.SHOW_OUTLINE, action);
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.SHOW_OUTLINE_ACTION);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"OpenStructure.", this, JavaSourceViewer.OPEN_STRUCTURE, true); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_STRUCTURE);
setAction(IJavaEditorActionDefinitionIds.OPEN_STRUCTURE, action);
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.OPEN_STRUCTURE_ACTION);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"OpenHierarchy.", this, JavaSourceViewer.SHOW_HIERARCHY, true); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_HIERARCHY);
setAction(IJavaEditorActionDefinitionIds.OPEN_HIERARCHY, action);
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.OPEN_HIERARCHY_ACTION);
fSelectionHistory= new SelectionHistory(this);
action= new StructureSelectEnclosingAction(this, fSelectionHistory);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_ENCLOSING);
setAction(StructureSelectionAction.ENCLOSING, action);
action= new StructureSelectNextAction(this, fSelectionHistory);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_NEXT);
setAction(StructureSelectionAction.NEXT, action);
action= new StructureSelectPreviousAction(this, fSelectionHistory);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_PREVIOUS);
setAction(StructureSelectionAction.PREVIOUS, action);
StructureSelectHistoryAction historyAction= new StructureSelectHistoryAction(this, fSelectionHistory);
historyAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_LAST);
setAction(StructureSelectionAction.HISTORY, historyAction);
fSelectionHistory.setHistoryAction(historyAction);
action= GoToNextPreviousMemberAction.newGoToNextMemberAction(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_NEXT_MEMBER);
setAction(GoToNextPreviousMemberAction.NEXT_MEMBER, action);
action= GoToNextPreviousMemberAction.newGoToPreviousMemberAction(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_PREVIOUS_MEMBER);
setAction(GoToNextPreviousMemberAction.PREVIOUS_MEMBER, action);
}
public void updatedTitleImage(Image image) {
setTitleImage(image);
}
/*
* @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
*/
protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
try {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
String property= event.getProperty();
if (PreferenceConstants.EDITOR_TAB_WIDTH.equals(property)) {
Object value= event.getNewValue();
if (value instanceof Integer) {
sourceViewer.getTextWidget().setTabs(((Integer) value).intValue());
} else if (value instanceof String) {
sourceViewer.getTextWidget().setTabs(Integer.parseInt((String) value));
}
return;
}
if (isJavaEditorHoverProperty(property))
updateHoverBehavior();
if (BROWSER_LIKE_LINKS.equals(property)) {
if (isBrowserLikeLinks())
enableBrowserLikeLinks();
else
disableBrowserLikeLinks();
return;
}
if (PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE.equals(property)) {
if ((event.getNewValue() instanceof Boolean) && ((Boolean)event.getNewValue()).booleanValue()) {
fEditorSelectionChangedListener= new EditorSelectionChangedListener();
fEditorSelectionChangedListener.install(getSelectionProvider());
fEditorSelectionChangedListener.selectionChanged();
} else {
fEditorSelectionChangedListener.uninstall(getSelectionProvider());
fEditorSelectionChangedListener= null;
}
return;
}
if (PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE.equals(property)) {
if (event.getNewValue() instanceof Boolean) {
Boolean disable= (Boolean) event.getNewValue();
configureInsertMode(OVERWRITE, !disable.booleanValue());
}
}
} finally {
super.handlePreferenceStoreChanged(event);
}
}
private boolean isJavaEditorHoverProperty(String property) {
return PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS.equals(property);
}
/**
* Return whether the browser like links should be enabled
* according to the preference store settings.
* @return <code>true</code> if the browser like links should be enabled
*/
private boolean isBrowserLikeLinks() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(BROWSER_LIKE_LINKS);
}
/**
* Enables browser like links.
*/
private void enableBrowserLikeLinks() {
if (fMouseListener == null) {
fMouseListener= new MouseClickListener();
fMouseListener.install();
}
}
/**
* Disables browser like links.
*/
private void disableBrowserLikeLinks() {
if (fMouseListener != null) {
fMouseListener.uninstall();
fMouseListener= null;
}
}
/**
* Handles a property change event describing a change
* of the java core's preferences and updates the preference
* related editor properties.
*
* @param event the property change event
*/
protected void handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
if (COMPILER_TASK_TAGS.equals(event.getProperty())) {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer != null && affectsTextPresentation(new PropertyChangeEvent(event.getSource(), event.getProperty(), event.getOldValue(), event.getNewValue())))
sourceViewer.invalidateTextPresentation();
}
}
/**
* Returns a segmentation of the line of the given viewer's input document appropriate for
* bidi rendering. The default implementation returns only the string literals of a java code
* line as segments.
*
* @param viewer the text viewer
* @param lineOffset the offset of the line
* @return the line's bidi segmentation
* @throws BadLocationException in case lineOffset is not valid in document
*/
public static int[] getBidiLineSegments(ITextViewer viewer, int lineOffset) throws BadLocationException {
IDocument document= viewer.getDocument();
if (document == null)
return null;
IRegion line= document.getLineInformationOfOffset(lineOffset);
ITypedRegion[] linePartitioning= TextUtilities.computePartitioning(document, IJavaPartitions.JAVA_PARTITIONING, lineOffset, line.getLength());
List segmentation= new ArrayList();
for (int i= 0; i < linePartitioning.length; i++) {
if (IJavaPartitions.JAVA_STRING.equals(linePartitioning[i].getType()))
segmentation.add(linePartitioning[i]);
}
if (segmentation.size() == 0)
return null;
int size= segmentation.size();
int[] segments= new int[size * 2 + 1];
int j= 0;
for (int i= 0; i < size; i++) {
ITypedRegion segment= (ITypedRegion) segmentation.get(i);
if (i == 0)
segments[j++]= 0;
int offset= segment.getOffset() - lineOffset;
if (offset > segments[j - 1])
segments[j++]= offset;
if (offset + segment.getLength() >= line.getLength())
break;
segments[j++]= offset + segment.getLength();
}
if (j < segments.length) {
int[] result= new int[j];
System.arraycopy(segments, 0, result, 0, j);
segments= result;
}
return segments;
}
/**
* Returns a segmentation of the given line appropriate for bidi rendering. The default
* implementation returns only the string literals of a java code line as segments.
*
* @param lineOffset the offset of the line
* @param line the content of the line
* @return the line's bidi segmentation
*/
protected int[] getBidiLineSegments(int widgetLineOffset, String line) {
if (line != null && line.length() > 0) {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer != null) {
int lineOffset;
if (sourceViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) sourceViewer;
lineOffset= extension.widgetOffset2ModelOffset(widgetLineOffset);
} else {
IRegion visible= sourceViewer.getVisibleRegion();
lineOffset= visible.getOffset() + widgetLineOffset;
}
try {
return getBidiLineSegments(sourceViewer, lineOffset);
} catch (BadLocationException x) {
// don't segment line in this case
}
}
}
return null;
}
/*
* 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);
}
}
/*
* @see org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput()
*/
public Object getViewPartInput() {
return getEditorInput().getAdapter(IJavaElement.class);
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#doSetSelection(ISelection)
*/
protected void doSetSelection(ISelection selection) {
super.doSetSelection(selection);
synchronizeOutlinePageSelection();
}
/*
* @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite)
*/
public void createPartControl(Composite parent) {
super.createPartControl(parent);
getSourceViewerDecorationSupport(getViewer()).install(getPreferenceStore());
Preferences preferences= JavaCore.getPlugin().getPluginPreferences();
preferences.addPropertyChangeListener(fPropertyChangeListener);
IInformationControlCreator informationControlCreator= new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell shell) {
boolean cutDown= false;
int style= cutDown ? SWT.NONE : (SWT.V_SCROLL | SWT.H_SCROLL);
return new DefaultInformationControl(shell, SWT.RESIZE, style, new HTMLTextPresenter(cutDown));
}
};
fInformationPresenter= new InformationPresenter(informationControlCreator);
fInformationPresenter.setSizeConstraints(60, 10, true, true);
fInformationPresenter.install(getSourceViewer());
if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE)) {
fEditorSelectionChangedListener= new EditorSelectionChangedListener();
fEditorSelectionChangedListener.install(getSelectionProvider());
}
if (isBrowserLikeLinks())
enableBrowserLikeLinks();
if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE))
configureInsertMode(OVERWRITE, false);
}
protected void configureSourceViewerDecorationSupport(SourceViewerDecorationSupport support) {
support.setCharacterPairMatcher(fBracketMatcher);
support.setMatchingCharacterPainterPreferenceKeys(MATCHING_BRACKETS, MATCHING_BRACKETS_COLOR);
super.configureSourceViewerDecorationSupport(support);
}
/**
* Jumps to the next enabled annotation according to the given direction.
* An annotation type is enabled if it is configured to be in the
* Next/Previous tool bar drop down menu and if it is checked.
*/
public void gotoAnnotation(boolean forward) {
ISelectionProvider provider= getSelectionProvider();
ITextSelection s= (ITextSelection) provider.getSelection();
Position annotationPosition= new Position(0, 0);
IJavaAnnotation nextAnnotation= getNextAnnotation(s.getOffset(), forward, annotationPosition);
setStatusLineErrorMessage(null);
if (nextAnnotation != null) {
IMarker marker= null;
if (nextAnnotation instanceof MarkerAnnotation)
marker= ((MarkerAnnotation) nextAnnotation).getMarker();
else {
Iterator e= nextAnnotation.getOverlaidIterator();
if (e != null) {
while (e.hasNext()) {
Object o= e.next();
if (o instanceof MarkerAnnotation) {
marker= ((MarkerAnnotation) o).getMarker();
break;
}
}
}
}
if (marker != null) {
IWorkbenchPage page= getSite().getPage();
IViewPart view= view= page.findView("org.eclipse.ui.views.TaskList"); //$NON-NLS-1$
if (view instanceof TaskList) {
StructuredSelection ss= new StructuredSelection(marker);
((TaskList) view).setSelection(ss, true);
}
}
selectAndReveal(annotationPosition.getOffset(), annotationPosition.getLength());
if (nextAnnotation.isProblem())
setStatusLineErrorMessage(nextAnnotation.getMessage());
}
}
/**
* Jumps to the matching bracket.
*/
public void gotoMatchingBracket() {
ISourceViewer sourceViewer= getSourceViewer();
IDocument document= sourceViewer.getDocument();
if (document == null)
return;
IRegion selection= getSignedSelection(sourceViewer);
int selectionLength= Math.abs(selection.getLength());
if (selectionLength > 1) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.invalidSelection")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
// #26314
int sourceCaretOffset= selection.getOffset() + selection.getLength();
if (isSurroundedByBrackets(document, sourceCaretOffset))
sourceCaretOffset -= selection.getLength();
IRegion region= fBracketMatcher.match(document, sourceCaretOffset);
if (region == null) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.noMatchingBracket")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
int offset= region.getOffset();
int length= region.getLength();
if (length < 1)
return;
int anchor= fBracketMatcher.getAnchor();
// http://dev.eclipse.org/bugs/show_bug.cgi?id=34195
int targetOffset= (JavaPairMatcher.RIGHT == anchor) ? offset + 1: offset + length;
boolean visible= false;
if (sourceViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) sourceViewer;
visible= (extension.modelOffset2WidgetOffset(targetOffset) > -1);
} else {
IRegion visibleRegion= sourceViewer.getVisibleRegion();
// http://dev.eclipse.org/bugs/show_bug.cgi?id=34195
visible= (targetOffset >= visibleRegion.getOffset() && targetOffset <= visibleRegion.getOffset() + visibleRegion.getLength());
}
if (!visible) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.bracketOutsideSelectedElement")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
if (selection.getLength() < 0)
targetOffset -= selection.getLength();
sourceViewer.setSelectedRange(targetOffset, selection.getLength());
sourceViewer.revealRange(targetOffset, selection.getLength());
}
/**
* Ses the given message as error message to this editor's status line.
* @param msg message to be set
*/
protected void setStatusLineErrorMessage(String msg) {
IEditorStatusLine statusLine= (IEditorStatusLine) getAdapter(IEditorStatusLine.class);
if (statusLine != null)
statusLine.setMessage(true, msg, null);
}
private static IRegion getSignedSelection(ITextViewer viewer) {
StyledText text= viewer.getTextWidget();
int caretOffset= text.getCaretOffset();
Point selection= text.getSelection();
// caret left
int offset, length;
if (caretOffset == selection.x) {
offset= selection.y;
length= selection.x - selection.y;
// caret right
} else {
offset= selection.x;
length= selection.y - selection.x;
}
return new Region(offset, length);
}
private static boolean isBracket(char character) {
for (int i= 0; i != BRACKETS.length; ++i)
if (character == BRACKETS[i])
return true;
return false;
}
private static boolean isSurroundedByBrackets(IDocument document, int offset) {
if (offset == 0 || offset == document.getLength())
return false;
try {
return
isBracket(document.getChar(offset - 1)) &&
isBracket(document.getChar(offset));
} catch (BadLocationException e) {
return false;
}
}
private IJavaAnnotation getNextAnnotation(int offset, boolean forward, Position annotationPosition) {
IJavaAnnotation nextAnnotation= null;
Position nextAnnotationPosition= null;
IDocument document= getDocumentProvider().getDocument(getEditorInput());
int endOfDocument= document.getLength();
int distance= 0;
IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput());
Iterator e= new JavaAnnotationIterator(model, true);
while (e.hasNext()) {
IJavaAnnotation a= (IJavaAnnotation) e.next();
Preferences workbenchTextEditorPrefStore= Platform.getPlugin("org.eclipse.ui.workbench.texteditor").getPluginPreferences(); //$NON-NLS-1$
Iterator iter= getAnnotationPreferences().getAnnotationPreferences().iterator();
boolean isNavigationTarget= false;
while (iter.hasNext()) {
AnnotationPreference annotationPref= (AnnotationPreference)iter.next();
if (annotationPref.getAnnotationType().equals(a.getAnnotationType())) {
String key;
if (forward)
key= annotationPref.getIsGoToNextNavigationTargetKey();
else
key= annotationPref.getIsGoToPreviousNavigationTargetKey();
if (key != null)
isNavigationTarget= workbenchTextEditorPrefStore.getBoolean(key);
break;
}
annotationPref= null;
}
if (a.hasOverlay() || !isNavigationTarget)
continue;
Position p= model.getPosition((Annotation) a);
if (!(p.includes(offset) || (p.getLength() == 0 && offset == p.offset))) {
int currentDistance= 0;
if (forward) {
currentDistance= p.getOffset() - offset;
if (currentDistance < 0)
currentDistance= endOfDocument - offset + p.getOffset();
} else {
currentDistance= offset - p.getOffset();
if (currentDistance < 0)
currentDistance= offset + endOfDocument - p.getOffset();
}
if (nextAnnotation == null || currentDistance < distance) {
distance= currentDistance;
nextAnnotation= a;
nextAnnotationPosition= p;
}
}
}
if (nextAnnotationPosition != null) {
annotationPosition.setOffset(nextAnnotationPosition.getOffset());
annotationPosition.setLength(nextAnnotationPosition.getLength());
}
return nextAnnotation;
}
/**
* Computes and returns the source reference that includes the caret and
* serves as provider for the outline page selection and the editor range
* indication.
*
* @return the computed source reference
* @since 3.0
*/
protected ISourceReference computeHighlightRangeSourceReference() {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return null;
StyledText styledText= sourceViewer.getTextWidget();
if (styledText == null)
return null;
int caret= 0;
if (sourceViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3)sourceViewer;
caret= extension.widgetOffset2ModelOffset(styledText.getCaretOffset());
} else {
int offset= sourceViewer.getVisibleRegion().getOffset();
caret= offset + styledText.getCaretOffset();
}
IJavaElement element= getElementAt(caret, false);
if ( !(element instanceof ISourceReference))
return null;
if (element.getElementType() == IJavaElement.IMPORT_DECLARATION) {
IImportDeclaration declaration= (IImportDeclaration) element;
IImportContainer container= (IImportContainer) declaration.getParent();
ISourceRange srcRange= null;
try {
srcRange= container.getSourceRange();
} catch (JavaModelException e) {
}
if (srcRange != null && srcRange.getOffset() == caret)
return container;
}
return (ISourceReference) element;
}
/**
* Returns the most narrow java element including the given offset.
*
* @param offset the offset inside of the requested element
* @param reconcile <code>true</code> if editor input should be reconciled in advance
* @return the most narrow java element
* @since 3.0
*/
protected IJavaElement getElementAt(int offset, boolean reconcile) {
return getElementAt(offset);
}
/*
* @see org.eclipse.ui.texteditor.ExtendedTextEditor#createChangeHover()
*/
protected LineChangeHover createChangeHover() {
return new JavaChangeHover(IJavaPartitions.JAVA_PARTITIONING);
}
protected boolean isPrefQuickDiffAlwaysOn() {
return false; // never show change ruler for the non-editable java editor. Overridden in subclasses like CompilationUnitEditor
}
}
|
41,688 |
Bug 41688 [misc] incorrect reconciling in Java Outline page
|
20030813 add this to a class open in an editor public int a, b; note that only 'b' is added to the outliner tree
|
resolved fixed
|
184aa2f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-19T16:16:05Z | 2003-08-19T13:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/JavaOutlinePage.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.javaeditor;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;
import java.util.Vector;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Item;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.Assert;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.ListenerList;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.IBaseLabelProvider;
import org.eclipse.jface.viewers.IPostSelectionProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProviderChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.internal.model.WorkbenchAdapter;
import org.eclipse.ui.model.IWorkbenchAdapter;
import org.eclipse.ui.part.IPageSite;
import org.eclipse.ui.part.IShowInSource;
import org.eclipse.ui.part.IShowInTarget;
import org.eclipse.ui.part.IShowInTargetList;
import org.eclipse.ui.part.Page;
import org.eclipse.ui.part.ShowInContext;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
import org.eclipse.ui.texteditor.IUpdate;
import org.eclipse.ui.texteditor.TextEditorAction;
import org.eclipse.ui.texteditor.TextOperationAction;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
import org.eclipse.jdt.core.ElementChangedEvent;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IElementChangedListener;
import org.eclipse.jdt.core.IInitializer;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaElementDelta;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IParent;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.ISourceReference;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.JavaElementSorter;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.ProblemsLabelDecorator.ProblemsLabelChangedEvent;
import org.eclipse.jdt.ui.actions.CCPActionGroup;
import org.eclipse.jdt.ui.actions.GenerateActionGroup;
import org.eclipse.jdt.ui.actions.JavaSearchActionGroup;
import org.eclipse.jdt.ui.actions.JdtActionConstants;
import org.eclipse.jdt.ui.actions.MemberFilterActionGroup;
import org.eclipse.jdt.ui.actions.OpenViewActionGroup;
import org.eclipse.jdt.ui.actions.RefactorActionGroup;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.actions.AbstractToggleLinkingAction;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.dnd.DelegatingDropAdapter;
import org.eclipse.jdt.internal.ui.dnd.JdtViewerDragAdapter;
import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer;
import org.eclipse.jdt.internal.ui.dnd.TransferDragSourceListener;
import org.eclipse.jdt.internal.ui.dnd.TransferDropTargetListener;
import org.eclipse.jdt.internal.ui.packageview.SelectionTransferDragAdapter;
import org.eclipse.jdt.internal.ui.packageview.SelectionTransferDropAdapter;
import org.eclipse.jdt.internal.ui.viewsupport.AppearanceAwareLabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.DecoratingJavaLabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater;
/**
* The content outline page of the Java editor. The viewer implements a proprietary
* update mechanism based on Java model deltas. It does not react on domain changes.
* It is specified to show the content of ICompilationUnits and IClassFiles.
* Pulishes its context menu under <code>JavaPlugin.getDefault().getPluginId() + ".outline"</code>.
*/
public class JavaOutlinePage extends Page implements IContentOutlinePage, IAdaptable , IPostSelectionProvider {
static Object[] NO_CHILDREN= new Object[0];
/**
* The element change listener of the java outline viewer.
* @see IElementChangedListener
*/
class ElementChangedListener implements IElementChangedListener {
public void elementChanged(final ElementChangedEvent e) {
if (getControl() == null)
return;
Display d= getControl().getDisplay();
if (d != null) {
d.asyncExec(new Runnable() {
public void run() {
ICompilationUnit cu= (ICompilationUnit) fInput;
IJavaElement base= cu;
if (fTopLevelTypeOnly) {
base= getMainType(cu);
if (base == null) {
if (fOutlineViewer != null)
fOutlineViewer.refresh(true);
return;
}
}
IJavaElementDelta delta= findElement(base, e.getDelta());
if (delta != null && fOutlineViewer != null) {
fOutlineViewer.reconcile(delta);
}
}
});
}
}
protected IJavaElementDelta findElement(IJavaElement unit, IJavaElementDelta delta) {
if (delta == null || unit == null)
return null;
IJavaElement element= delta.getElement();
if (unit.equals(element))
return delta;
if (element.getElementType() > IJavaElement.CLASS_FILE)
return null;
IJavaElementDelta[] children= delta.getAffectedChildren();
if (children == null || children.length == 0)
return null;
for (int i= 0; i < children.length; i++) {
IJavaElementDelta d= findElement(unit, children[i]);
if (d != null)
return d;
}
return null;
}
}
static class NoClassElement extends WorkbenchAdapter implements IAdaptable {
/*
* @see java.lang.Object#toString()
*/
public String toString() {
return JavaEditorMessages.getString("JavaOutlinePage.error.NoTopLevelType"); //$NON-NLS-1$
}
/*
* @see org.eclipse.core.runtime.IAdaptable#getAdapter(Class)
*/
public Object getAdapter(Class clas) {
if (clas == IWorkbenchAdapter.class)
return this;
return null;
}
}
/**
* Content provider for the children of an ICompilationUnit or
* an IClassFile
* @see ITreeContentProvider
*/
class ChildrenProvider implements ITreeContentProvider {
private Object[] NO_CLASS= new Object[] {new NoClassElement()};
private ElementChangedListener fListener;
protected boolean matches(IJavaElement element) {
if (element.getElementType() == IJavaElement.METHOD) {
String name= element.getElementName();
return (name != null && name.indexOf('<') >= 0);
}
return false;
}
protected IJavaElement[] filter(IJavaElement[] children) {
boolean initializers= false;
for (int i= 0; i < children.length; i++) {
if (matches(children[i])) {
initializers= true;
break;
}
}
if (!initializers)
return children;
Vector v= new Vector();
for (int i= 0; i < children.length; i++) {
if (matches(children[i]))
continue;
v.addElement(children[i]);
}
IJavaElement[] result= new IJavaElement[v.size()];
v.copyInto(result);
return result;
}
public Object[] getChildren(Object parent) {
if (parent instanceof IParent) {
IParent c= (IParent) parent;
try {
return filter(c.getChildren());
} catch (JavaModelException x) {
JavaPlugin.log(x);
}
}
return NO_CHILDREN;
}
public Object[] getElements(Object parent) {
if (fTopLevelTypeOnly) {
if (parent instanceof ICompilationUnit) {
try {
IType type= getMainType((ICompilationUnit) parent);
return type != null ? type.getChildren() : NO_CLASS;
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
} else if (parent instanceof IClassFile) {
try {
IType type= getMainType((IClassFile) parent);
return type != null ? type.getChildren() : NO_CLASS;
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
}
return getChildren(parent);
}
public Object getParent(Object child) {
if (child instanceof IJavaElement) {
IJavaElement e= (IJavaElement) child;
return e.getParent();
}
return null;
}
public boolean hasChildren(Object parent) {
if (parent instanceof IParent) {
IParent c= (IParent) parent;
try {
IJavaElement[] children= filter(c.getChildren());
return (children != null && children.length > 0);
} catch (JavaModelException x) {
JavaPlugin.log(x);
}
}
return false;
}
public boolean isDeleted(Object o) {
return false;
}
public void dispose() {
if (fListener != null) {
JavaCore.removeElementChangedListener(fListener);
fListener= null;
}
}
/*
* @see IContentProvider#inputChanged(Viewer, Object, Object)
*/
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
boolean isCU= (newInput instanceof ICompilationUnit);
if (isCU && fListener == null) {
fListener= new ElementChangedListener();
JavaCore.addElementChangedListener(fListener);
} else if (!isCU && fListener != null) {
JavaCore.removeElementChangedListener(fListener);
fListener= null;
}
}
}
class JavaOutlineViewer extends TreeViewer {
/**
* Indicates an item which has been reused. At the point of
* its reuse it has been expanded. This field is used to
* communicate between <code>internalExpandToLevel</code> and
* <code>reuseTreeItem</code>.
*/
private Item fReusedExpandedItem;
private boolean fReorderedMembers;
public JavaOutlineViewer(Tree tree) {
super(tree);
setAutoExpandLevel(ALL_LEVELS);
setUseHashlookup(true);
}
/**
* Investigates the given element change event and if affected incrementally
* updates the outline.
*/
public void reconcile(IJavaElementDelta delta) {
fReorderedMembers= false;
if (getSorter() == null) {
if (fTopLevelTypeOnly
&& delta.getElement() instanceof IType
&& (delta.getKind() & IJavaElementDelta.ADDED) != 0)
{
refresh(true);
} else {
Widget w= findItem(fInput);
if (w != null && !w.isDisposed())
update(w, delta);
if (fReorderedMembers) {
refresh(false);
fReorderedMembers= false;
}
}
} else {
// just for now
refresh(true);
}
}
/*
* @see TreeViewer#internalExpandToLevel
*/
protected void internalExpandToLevel(Widget node, int level) {
if (node instanceof Item) {
Item i= (Item) node;
if (i.getData() instanceof IJavaElement) {
IJavaElement je= (IJavaElement) i.getData();
if (je.getElementType() == IJavaElement.IMPORT_CONTAINER || isInnerType(je)) {
if (i != fReusedExpandedItem) {
setExpanded(i, false);
return;
}
}
}
}
super.internalExpandToLevel(node, level);
}
protected void reuseTreeItem(Item item, Object element) {
// remove children
Item[] c= getChildren(item);
if (c != null && c.length > 0) {
if (getExpanded(item))
fReusedExpandedItem= item;
for (int k= 0; k < c.length; k++) {
if (c[k].getData() != null)
disassociate(c[k]);
c[k].dispose();
}
}
updateItem(item, element);
updatePlus(item, element);
internalExpandToLevel(item, ALL_LEVELS);
fReusedExpandedItem= null;
}
protected boolean mustUpdateParent(IJavaElementDelta delta, IJavaElement element) {
if (element instanceof IMethod) {
if ((delta.getKind() & IJavaElementDelta.ADDED) != 0) {
try {
return ((IMethod)element).isMainMethod();
} catch (JavaModelException e) {
JavaPlugin.log(e.getStatus());
}
}
return "main".equals(element.getElementName()); //$NON-NLS-1$
}
return false;
}
protected ISourceRange getSourceRange(IJavaElement element) throws JavaModelException {
if (element instanceof ISourceReference)
return ((ISourceReference) element).getSourceRange();
if (element instanceof IMember && !(element instanceof IInitializer))
return ((IMember) element).getNameRange();
return null;
}
protected boolean overlaps(ISourceRange range, int start, int end) {
return start <= (range.getOffset() + range.getLength() - 1) && range.getOffset() <= end;
}
protected boolean filtered(IJavaElement parent, IJavaElement child) {
Object[] result= new Object[] { child };
ViewerFilter[] filters= getFilters();
for (int i= 0; i < filters.length; i++) {
result= filters[i].filter(this, parent, result);
if (result.length == 0)
return true;
}
return false;
}
protected void update(Widget w, IJavaElementDelta delta) {
Item item;
IJavaElement parent= delta.getElement();
IJavaElementDelta[] affected= delta.getAffectedChildren();
Item[] children= getChildren(w);
boolean doUpdateParent= false;
boolean doUpdateParentsPlus= false;
Vector deletions= new Vector();
Vector additions= new Vector();
for (int i= 0; i < affected.length; i++) {
IJavaElementDelta affectedDelta= affected[i];
IJavaElement affectedElement= affectedDelta.getElement();
int status= affected[i].getKind();
// find tree item with affected element
int j;
for (j= 0; j < children.length; j++)
if (affectedElement.equals(children[j].getData()))
break;
if (j == children.length) {
// remove from collapsed parent
if ((status & IJavaElementDelta.REMOVED) != 0) {
doUpdateParentsPlus= true;
continue;
}
// addition
if ((status & IJavaElementDelta.CHANGED) != 0 &&
(affectedDelta.getFlags() & IJavaElementDelta.F_MODIFIERS) != 0 &&
!filtered(parent, affectedElement))
{
additions.addElement(affectedDelta);
}
continue;
}
item= children[j];
// removed
if ((status & IJavaElementDelta.REMOVED) != 0) {
deletions.addElement(item);
doUpdateParent= doUpdateParent || mustUpdateParent(affectedDelta, affectedElement);
// changed
} else if ((status & IJavaElementDelta.CHANGED) != 0) {
int change= affectedDelta.getFlags();
doUpdateParent= doUpdateParent || mustUpdateParent(affectedDelta, affectedElement);
if ((change & IJavaElementDelta.F_MODIFIERS) != 0) {
if (filtered(parent, affectedElement))
deletions.addElement(item);
else
updateItem(item, affectedElement);
}
if ((change & IJavaElementDelta.F_CONTENT) != 0)
updateItem(item, affectedElement);
if ((change & IJavaElementDelta.F_CHILDREN) != 0)
update(item, affectedDelta);
if ((change & IJavaElementDelta.F_REORDER) != 0)
fReorderedMembers= true;
}
}
// find all elements to add
IJavaElementDelta[] add= delta.getAddedChildren();
if (additions.size() > 0) {
IJavaElementDelta[] tmp= new IJavaElementDelta[add.length + additions.size()];
System.arraycopy(add, 0, tmp, 0, add.length);
for (int i= 0; i < additions.size(); i++)
tmp[i + add.length]= (IJavaElementDelta) additions.elementAt(i);
add= tmp;
}
// add at the right position
go2: for (int i= 0; i < add.length; i++) {
try {
IJavaElement e= add[i].getElement();
if (filtered(parent, e))
continue go2;
doUpdateParent= doUpdateParent || mustUpdateParent(add[i], e);
ISourceRange rng= getSourceRange(e);
int start= rng.getOffset();
int end= start + rng.getLength() - 1;
Item last= null;
item= null;
children= getChildren(w);
for (int j= 0; j < children.length; j++) {
item= children[j];
IJavaElement r= (IJavaElement) item.getData();
if (r == null) {
// parent node collapsed and not be opened before -> do nothing
continue go2;
}
try {
rng= getSourceRange(r);
if (overlaps(rng, start, end)) {
// be tolerant if the delta is not correct, or if
// the tree has been updated other than by a delta
reuseTreeItem(item, e);
continue go2;
} else if (rng.getOffset() > start) {
if (last != null && deletions.contains(last)) {
// reuse item
deletions.removeElement(last);
reuseTreeItem(last, e);
} else {
// nothing to reuse
createTreeItem(w, e, j);
}
continue go2;
}
} catch (JavaModelException x) {
// stumbled over deleted element
}
last= item;
}
// add at the end of the list
if (last != null && deletions.contains(last)) {
// reuse item
deletions.removeElement(last);
reuseTreeItem(last, e);
} else {
// nothing to reuse
createTreeItem(w, e, -1);
}
} catch (JavaModelException x) {
// the element to be added is not present -> don't add it
}
}
// remove items which haven't been reused
Enumeration e= deletions.elements();
while (e.hasMoreElements()) {
item= (Item) e.nextElement();
disassociate(item);
item.dispose();
}
if (doUpdateParent)
updateItem(w, delta.getElement());
if (!doUpdateParent && doUpdateParentsPlus && w instanceof Item)
updatePlus((Item)w, delta.getElement());
}
/*
* @see ContentViewer#handleLabelProviderChanged(LabelProviderChangedEvent)
*/
protected void handleLabelProviderChanged(LabelProviderChangedEvent event) {
Object input= getInput();
if (event instanceof ProblemsLabelChangedEvent) {
ProblemsLabelChangedEvent e= (ProblemsLabelChangedEvent) event;
if (e.isMarkerChange() && input instanceof ICompilationUnit) {
return; // marker changes can be ignored
}
}
// look if the underlying resource changed
Object[] changed= event.getElements();
if (changed != null) {
IResource resource= getUnderlyingResource();
if (resource != null) {
for (int i= 0; i < changed.length; i++) {
if (changed[i] != null && changed[i].equals(resource)) {
// change event to a full refresh
event= new LabelProviderChangedEvent((IBaseLabelProvider) event.getSource());
break;
}
}
}
}
super.handleLabelProviderChanged(event);
}
private IResource getUnderlyingResource() {
Object input= getInput();
if (input instanceof ICompilationUnit) {
ICompilationUnit cu= (ICompilationUnit) input;
cu= JavaModelUtil.toOriginal(cu);
return cu.getResource();
} else if (input instanceof IClassFile) {
return ((IClassFile) input).getResource();
}
return null;
}
}
class LexicalSortingAction extends Action {
private JavaElementSorter fSorter= new JavaElementSorter();
public LexicalSortingAction() {
super();
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.LEXICAL_SORTING_OUTLINE_ACTION);
setText(JavaEditorMessages.getString("JavaOutlinePage.Sort.label")); //$NON-NLS-1$
JavaPluginImages.setLocalImageDescriptors(this, "alphab_sort_co.gif"); //$NON-NLS-1$
setToolTipText(JavaEditorMessages.getString("JavaOutlinePage.Sort.tooltip")); //$NON-NLS-1$
setDescription(JavaEditorMessages.getString("JavaOutlinePage.Sort.description")); //$NON-NLS-1$
boolean checked= JavaPlugin.getDefault().getPreferenceStore().getBoolean("LexicalSortingAction.isChecked"); //$NON-NLS-1$
valueChanged(checked, false);
}
public void run() {
valueChanged(isChecked(), true);
}
private void valueChanged(final boolean on, boolean store) {
setChecked(on);
BusyIndicator.showWhile(fOutlineViewer.getControl().getDisplay(), new Runnable() {
public void run() {
fOutlineViewer.setSorter(on ? fSorter : null); }
});
if (store)
JavaPlugin.getDefault().getPreferenceStore().setValue("LexicalSortingAction.isChecked", on); //$NON-NLS-1$
}
}
class ClassOnlyAction extends Action {
public ClassOnlyAction() {
super();
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.GO_INTO_TOP_LEVEL_TYPE_ACTION);
setText(JavaEditorMessages.getString("JavaOutlinePage.GoIntoTopLevelType.label")); //$NON-NLS-1$
setToolTipText(JavaEditorMessages.getString("JavaOutlinePage.GoIntoTopLevelType.tooltip")); //$NON-NLS-1$
setDescription(JavaEditorMessages.getString("JavaOutlinePage.GoIntoTopLevelType.description")); //$NON-NLS-1$
JavaPluginImages.setLocalImageDescriptors(this, "gointo_toplevel_type.gif"); //$NON-NLS-1$
IPreferenceStore preferenceStore= JavaPlugin.getDefault().getPreferenceStore();
boolean showclass= preferenceStore.getBoolean("GoIntoTopLevelTypeAction.isChecked"); //$NON-NLS-1$
setTopLevelTypeOnly(showclass);
}
/*
* @see org.eclipse.jface.action.Action#run()
*/
public void run() {
setTopLevelTypeOnly(!fTopLevelTypeOnly);
}
private void setTopLevelTypeOnly(boolean show) {
fTopLevelTypeOnly= show;
setChecked(show);
fOutlineViewer.refresh(false);
IPreferenceStore preferenceStore= JavaPlugin.getDefault().getPreferenceStore();
preferenceStore.setValue("GoIntoTopLevelTypeAction.isChecked", show); //$NON-NLS-1$
}
}
/**
* This action toggles whether this Java Outline page links
* its selection to the active editor.
*
* @since 3.0
*/
public class ToggleLinkingAction extends AbstractToggleLinkingAction {
JavaOutlinePage fJavaOutlinePage;
/**
* Constructs a new action.
*/
public ToggleLinkingAction(JavaOutlinePage outlinePage) {
boolean isLinkingEnabled= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE);
setChecked(isLinkingEnabled);
fJavaOutlinePage= outlinePage;
}
/**
* Runs the action.
*/
public void run() {
PreferenceConstants.getPreferenceStore().setValue(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE, isChecked());
if (isChecked() && fEditor != null)
fEditor.synchronizeOutlinePage(fEditor.computeHighlightRangeSourceReference(), false);
}
}
/** A flag to show contents of top level type only */
private boolean fTopLevelTypeOnly;
private IJavaElement fInput;
private String fContextMenuID;
private Menu fMenu;
private JavaOutlineViewer fOutlineViewer;
private JavaEditor fEditor;
private MemberFilterActionGroup fMemberFilterActionGroup;
private ListenerList fSelectionChangedListeners= new ListenerList();
private ListenerList fPostSelectionChangedListeners= new ListenerList();
private Hashtable fActions= new Hashtable();
private TogglePresentationAction fTogglePresentation;
private GotoAnnotationAction fPreviousAnnotation;
private GotoAnnotationAction fNextAnnotation;
private TextEditorAction fShowJavadoc;
private TextOperationAction fUndo;
private TextOperationAction fRedo;
private ToggleLinkingAction fToggleLinkingAction;
private CompositeActionGroup fActionGroups;
private CCPActionGroup fCCPActionGroup;
private IPropertyChangeListener fPropertyChangeListener;
public JavaOutlinePage(String contextMenuID, JavaEditor editor) {
super();
Assert.isNotNull(editor);
fContextMenuID= contextMenuID;
fEditor= editor;
fTogglePresentation= new TogglePresentationAction();
fPreviousAnnotation= new GotoAnnotationAction("PreviousAnnotation.", false); //$NON-NLS-1$
fNextAnnotation= new GotoAnnotationAction("NextAnnotation.", true); //$NON-NLS-1$
fShowJavadoc= (TextEditorAction) fEditor.getAction("ShowJavaDoc"); //$NON-NLS-1$
fUndo= (TextOperationAction) fEditor.getAction(ITextEditorActionConstants.UNDO);
fRedo= (TextOperationAction) fEditor.getAction(ITextEditorActionConstants.REDO);
fTogglePresentation.setEditor(editor);
fPreviousAnnotation.setEditor(editor);
fNextAnnotation.setEditor(editor);
fPropertyChangeListener= new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
doPropertyChange(event);
}
};
JavaPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(fPropertyChangeListener);
}
/**
* Returns the primary type of a compilation unit (has the same
* name as the compilation unit).
*
* @param compilationUnit the compilation unit
* @return returns the primary type of the compilation unit, or
* <code>null</code> if is does not have one
*/
protected IType getMainType(ICompilationUnit compilationUnit) {
if (compilationUnit == null)
return null;
String name= compilationUnit.getElementName();
int index= name.indexOf('.');
if (index != -1)
name= name.substring(0, index);
IType type= compilationUnit.getType(name);
return type.exists() ? type : null;
}
/**
* Returns the primary type of a class file.
*
* @param classFile the class file
* @return returns the primary type of the class file, or <code>null</code>
* if is does not have one
*/
protected IType getMainType(IClassFile classFile) {
try {
IType type= classFile.getType();
return type != null && type.exists() ? type : null;
} catch (JavaModelException e) {
return null;
}
}
/* (non-Javadoc)
* Method declared on Page
*/
public void init(IPageSite pageSite) {
super.init(pageSite);
}
private void doPropertyChange(PropertyChangeEvent event) {
if (fOutlineViewer != null) {
if (PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER.equals(event.getProperty())) {
fOutlineViewer.refresh(false);
}
}
}
/*
* @see ISelectionProvider#addSelectionChangedListener(ISelectionChangedListener)
*/
public void addSelectionChangedListener(ISelectionChangedListener listener) {
if (fOutlineViewer != null)
fOutlineViewer.addSelectionChangedListener(listener);
else
fSelectionChangedListeners.add(listener);
}
/*
* @see ISelectionProvider#removeSelectionChangedListener(ISelectionChangedListener)
*/
public void removeSelectionChangedListener(ISelectionChangedListener listener) {
if (fOutlineViewer != null)
fOutlineViewer.removeSelectionChangedListener(listener);
else
fSelectionChangedListeners.remove(listener);
}
/*
* @see ISelectionProvider#setSelection(ISelection)
*/
public void setSelection(ISelection selection) {
if (fOutlineViewer != null)
fOutlineViewer.setSelection(selection);
}
/*
* @see ISelectionProvider#getSelection()
*/
public ISelection getSelection() {
if (fOutlineViewer == null)
return StructuredSelection.EMPTY;
return fOutlineViewer.getSelection();
}
/*
* @see org.eclipse.jface.text.IPostSelectionProvider#addPostSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener)
*/
public void addPostSelectionChangedListener(ISelectionChangedListener listener) {
if (fOutlineViewer != null)
fOutlineViewer.addPostSelectionChangedListener(listener);
else
fPostSelectionChangedListeners.add(listener);
}
/*
* @see org.eclipse.jface.text.IPostSelectionProvider#removePostSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener)
*/
public void removePostSelectionChangedListener(ISelectionChangedListener listener) {
if (fOutlineViewer != null)
fOutlineViewer.removePostSelectionChangedListener(listener);
else
fPostSelectionChangedListeners.remove(listener);
}
private void registerToolbarActions() {
IToolBarManager toolBarManager= getSite().getActionBars().getToolBarManager();
if (toolBarManager != null) {
toolBarManager.add(new ClassOnlyAction());
toolBarManager.add(new LexicalSortingAction());
fMemberFilterActionGroup= new MemberFilterActionGroup(fOutlineViewer, "JavaOutlineViewer"); //$NON-NLS-1$
fMemberFilterActionGroup.contributeToToolBar(toolBarManager);
fToggleLinkingAction= new ToggleLinkingAction(this);
toolBarManager.add(fToggleLinkingAction);
}
}
/*
* @see IPage#createControl
*/
public void createControl(Composite parent) {
Tree tree= new Tree(parent, SWT.MULTI);
AppearanceAwareLabelProvider lprovider= new AppearanceAwareLabelProvider(
AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS | JavaElementLabels.F_APP_TYPE_SIGNATURE,
AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS
);
fOutlineViewer= new JavaOutlineViewer(tree);
initDragAndDrop();
fOutlineViewer.setContentProvider(new ChildrenProvider());
fOutlineViewer.setLabelProvider(new DecoratingJavaLabelProvider(lprovider));
Object[] listeners= fSelectionChangedListeners.getListeners();
for (int i= 0; i < listeners.length; i++) {
fSelectionChangedListeners.remove(listeners[i]);
fOutlineViewer.addSelectionChangedListener((ISelectionChangedListener) listeners[i]);
}
listeners= fPostSelectionChangedListeners.getListeners();
for (int i= 0; i < listeners.length; i++) {
fPostSelectionChangedListeners.remove(listeners[i]);
fOutlineViewer.addPostSelectionChangedListener((ISelectionChangedListener) listeners[i]);
}
MenuManager manager= new MenuManager(fContextMenuID, fContextMenuID);
manager.setRemoveAllWhenShown(true);
manager.addMenuListener(new IMenuListener() {
public void menuAboutToShow(IMenuManager m) {
contextMenuAboutToShow(m);
}
});
fMenu= manager.createContextMenu(tree);
tree.setMenu(fMenu);
IPageSite site= getSite();
site.registerContextMenu(JavaPlugin.getPluginId() + ".outline", manager, fOutlineViewer); //$NON-NLS-1$
site.setSelectionProvider(fOutlineViewer);
// we must create the groups after we have set the selection provider to the site
fActionGroups= new CompositeActionGroup(new ActionGroup[] {
new OpenViewActionGroup(this),
fCCPActionGroup= new CCPActionGroup(this),
new GenerateActionGroup(this),
new RefactorActionGroup(this),
new JavaSearchActionGroup(this)});
// register global actions
IActionBars bars= site.getActionBars();
bars.setGlobalActionHandler(ITextEditorActionConstants.UNDO, fUndo);
bars.setGlobalActionHandler(ITextEditorActionConstants.REDO, fRedo);
bars.setGlobalActionHandler(ITextEditorActionConstants.PREVIOUS, fPreviousAnnotation);
bars.setGlobalActionHandler(ITextEditorActionConstants.NEXT, fNextAnnotation);
bars.setGlobalActionHandler(JdtActionConstants.SHOW_JAVA_DOC, fShowJavadoc);
bars.setGlobalActionHandler(ITextEditorActionDefinitionIds.TOGGLE_SHOW_SELECTED_ELEMENT_ONLY, fTogglePresentation);
bars.setGlobalActionHandler(ITextEditorActionDefinitionIds.GOTO_NEXT_ANNOTATION, fNextAnnotation);
bars.setGlobalActionHandler(ITextEditorActionDefinitionIds.GOTO_PREVIOUS_ANNOTATION, fPreviousAnnotation);
fActionGroups.fillActionBars(bars);
IStatusLineManager statusLineManager= bars.getStatusLineManager();
if (statusLineManager != null) {
StatusBarUpdater updater= new StatusBarUpdater(statusLineManager);
fOutlineViewer.addPostSelectionChangedListener(updater);
}
registerToolbarActions();
fOutlineViewer.setInput(fInput);
fOutlineViewer.getControl().addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
handleKeyReleased(e);
}
});
}
public void dispose() {
if (fEditor == null)
return;
if (fMemberFilterActionGroup != null) {
fMemberFilterActionGroup.dispose();
fMemberFilterActionGroup= null;
}
fEditor.outlinePageClosed();
fEditor= null;
fSelectionChangedListeners.clear();
fSelectionChangedListeners= null;
fPostSelectionChangedListeners.clear();
fPostSelectionChangedListeners= null;
if (fPropertyChangeListener != null) {
JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(fPropertyChangeListener);
fPropertyChangeListener= null;
}
if (fMenu != null && !fMenu.isDisposed()) {
fMenu.dispose();
fMenu= null;
}
if (fActionGroups != null)
fActionGroups.dispose();
fTogglePresentation.setEditor(null);
fPreviousAnnotation.setEditor(null);
fNextAnnotation.setEditor(null);
fOutlineViewer= null;
super.dispose();
}
public Control getControl() {
if (fOutlineViewer != null)
return fOutlineViewer.getControl();
return null;
}
public void setInput(IJavaElement inputElement) {
fInput= inputElement;
if (fOutlineViewer != null)
fOutlineViewer.setInput(fInput);
}
public void select(ISourceReference reference) {
if (fOutlineViewer != null) {
ISelection s= fOutlineViewer.getSelection();
if (s instanceof IStructuredSelection) {
IStructuredSelection ss= (IStructuredSelection) s;
List elements= ss.toList();
if (!elements.contains(reference)) {
s= (reference == null ? StructuredSelection.EMPTY : new StructuredSelection(reference));
fOutlineViewer.setSelection(s, true);
}
}
}
}
public void setAction(String actionID, IAction action) {
Assert.isNotNull(actionID);
if (action == null)
fActions.remove(actionID);
else
fActions.put(actionID, action);
}
public IAction getAction(String actionID) {
Assert.isNotNull(actionID);
return (IAction) fActions.get(actionID);
}
/**
* Answer the property defined by key.
*/
public Object getAdapter(Class key) {
if (key == IShowInSource.class) {
return getShowInSource();
}
if (key == IShowInTargetList.class) {
return new IShowInTargetList() {
public String[] getShowInTargetIds() {
return new String[] { JavaUI.ID_PACKAGES };
}
};
}
if (key == IShowInTarget.class) {
return getShowInTarget();
}
return null;
}
/**
* Convenience method to add the action installed under the given actionID to the
* specified group of the menu.
*/
protected void addAction(IMenuManager menu, String group, String actionID) {
IAction action= getAction(actionID);
if (action != null) {
if (action instanceof IUpdate)
((IUpdate) action).update();
if (action.isEnabled()) {
IMenuManager subMenu= menu.findMenuUsingPath(group);
if (subMenu != null)
subMenu.add(action);
else
menu.appendToGroup(group, action);
}
}
}
protected void contextMenuAboutToShow(IMenuManager menu) {
JavaPlugin.createStandardGroups(menu);
IStructuredSelection selection= (IStructuredSelection)getSelection();
fActionGroups.setContext(new ActionContext(selection));
fActionGroups.fillContextMenu(menu);
}
/*
* @see Page#setFocus()
*/
public void setFocus() {
if (fOutlineViewer != null)
fOutlineViewer.getControl().setFocus();
}
/**
* Checkes whether a given Java element is an inner type.
*/
private boolean isInnerType(IJavaElement element) {
if (element != null && element.getElementType() == IJavaElement.TYPE) {
IType type= (IType)element;
try {
return type.isMember();
} catch (JavaModelException e) {
IJavaElement parent= type.getParent();
if (parent != null) {
int parentElementType= parent.getElementType();
return (parentElementType != IJavaElement.COMPILATION_UNIT && parentElementType != IJavaElement.CLASS_FILE);
}
}
}
return false;
}
/**
* Handles key events in viewer.
*/
private void handleKeyReleased(KeyEvent event) {
if (event.stateMask != 0)
return;
IAction action= null;
if (event.character == SWT.DEL) {
action= fCCPActionGroup.getDeleteAction();
}
if (action != null && action.isEnabled())
action.run();
}
/**
* Returns the <code>IShowInSource</code> for this view.
*/
protected IShowInSource getShowInSource() {
return new IShowInSource() {
public ShowInContext getShowInContext() {
return new ShowInContext(
null,
getSite().getSelectionProvider().getSelection());
}
};
}
/**
* Returns the <code>IShowInTarget</code> for this view.
*/
protected IShowInTarget getShowInTarget() {
return new IShowInTarget() {
public boolean show(ShowInContext context) {
ISelection sel= context.getSelection();
if (sel instanceof ITextSelection) {
ITextSelection tsel= (ITextSelection) sel;
int offset= tsel.getOffset();
IJavaElement element= fEditor.getElementAt(offset);
if (element != null) {
setSelection(new StructuredSelection(element));
return true;
}
}
return false;
}
};
}
private void initDragAndDrop() {
int ops= DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK;
Transfer[] transfers= new Transfer[] {
LocalSelectionTransfer.getInstance()
};
// Drop Adapter
TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] {
new SelectionTransferDropAdapter(fOutlineViewer)
};
fOutlineViewer.addDropSupport(ops | DND.DROP_DEFAULT, transfers, new DelegatingDropAdapter(dropListeners));
// Drag Adapter
TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] {
new SelectionTransferDragAdapter(fOutlineViewer)
};
fOutlineViewer.addDragSupport(ops, transfers, new JdtViewerDragAdapter(fOutlineViewer, dragListeners));
}
}
|
41,692 |
Bug 41692 Pressing Enter at last caret position does not work
|
I20030819 This is in .log: org.eclipse.jdt.internal.corext.Assert$AssertionFailedException: assertion failed; at org.eclipse.jdt.internal.corext.Assert.isTrue(Assert.java:136) at org.eclipse.jdt.internal.corext.Assert.isTrue(Assert.java:121) at org.eclipse.jdt.internal.ui.text.java.JavaAutoIndentStrategy.firstNonWhitespaceBackward(JavaAutoIndentStrategy.java:501) at org.eclipse.jdt.internal.ui.text.java.JavaAutoIndentStrategy.isBracelessBlockStart(JavaAutoIndentStrategy.java:359) at org.eclipse.jdt.internal.ui.text.java.JavaAutoIndentStrategy.smartIndentAfterNewLine(JavaAutoIndentStrategy.java:330) at org.eclipse.jdt.internal.ui.text.java.JavaAutoIndentStrategy.customizeDocumentCommand(JavaAutoIndentStrategy.java:1187) at org.eclipse.jface.text.TextViewer.customizeDocumentCommand(TextViewer.java:3080) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor$AdaptedSourceViewer.customizeDocumentCommand(CompilationUnitEditor.java:214) at org.eclipse.jface.text.TextViewer.handleVerifyEvent(TextViewer.java:3099) at org.eclipse.jface.text.TextViewer$TextVerifyListener.verifyText(TextViewer.java:318) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:189) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:848) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:872) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:857) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:665) at org.eclipse.swt.custom.StyledText.modifyContent(StyledText.java:5808) at org.eclipse.swt.custom.StyledText.sendKeyEvent(StyledText.java:6794) at org.eclipse.swt.custom.StyledText.doContent(StyledText.java:2546) at org.eclipse.swt.custom.StyledText.handleKey(StyledText.java:5187) at org.eclipse.swt.custom.StyledText.handleKeyDown(StyledText.java:5210) at org.eclipse.swt.custom.StyledText$8.handleEvent(StyledText.java:4957) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:848) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:872) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:857) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1688) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1684) at org.eclipse.swt.widgets.Control.WM_CHAR(Control.java:3013) at org.eclipse.swt.widgets.Control.windowProc(Control.java:2892) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2713) at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:1338) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1876) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1676) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1659) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:291) at org.eclipse.core.launcher.Main.run(Main.java:747) at org.eclipse.core.launcher.Main.main(Main.java:583)
|
resolved fixed
|
72d4ade
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-19T16:35:40Z | 2003-08-19T16:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/JavaAutoIndentStrategy.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Nikolay Metchev - Fixed bug 29909
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text.java;
import java.util.Arrays;
import java.util.Iterator;
import java.util.NoSuchElementException;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DefaultAutoIndentStrategy;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.DocumentCommand;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.TextUtilities;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.texteditor.ITextEditorExtension3;
import org.eclipse.jdt.core.ToolFactory;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.core.compiler.IScanner;
import org.eclipse.jdt.core.compiler.ITerminalSymbols;
import org.eclipse.jdt.core.compiler.InvalidInputException;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.DoStatement;
import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.ForStatement;
import org.eclipse.jdt.core.dom.IfStatement;
import org.eclipse.jdt.core.dom.Statement;
import org.eclipse.jdt.core.dom.WhileStatement;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.corext.Assert;
import org.eclipse.jdt.internal.corext.dom.NodeFinder;
import org.eclipse.jdt.internal.corext.util.CodeFormatterUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.IJavaPartitions;
/**
* Auto indent strategy sensitive to brackets.
*/
public class JavaAutoIndentStrategy extends DefaultAutoIndentStrategy {
/**
* Internal line interator working on <code>IDocument</code>.
*/
private static final class LineIterator implements Iterator {
/** The document to iterator over. */
private final IDocument fDocument;
/** The line index. */
private int fLineIndex;
/**
* Creates a line iterator.
*/
public LineIterator(String string) {
fDocument= new Document(string);
}
/*
* @see java.util.Iterator#hasNext()
*/
public boolean hasNext() {
return fLineIndex != fDocument.getNumberOfLines();
}
/*
* @see java.util.Iterator#next()
*/
public Object next() {
try {
IRegion region= fDocument.getLineInformation(fLineIndex++);
return fDocument.get(region.getOffset(), region.getLength());
} catch (BadLocationException e) {
JavaPlugin.log(e);
throw new NoSuchElementException();
}
}
/*
* @see java.util.Iterator#remove()
*/
public void remove() {
throw new UnsupportedOperationException();
}
}
private static class CompilationUnitInfo {
public char[] buffer;
public int delta;
public CompilationUnitInfo(char[] buffer, int delta) {
this.buffer= buffer;
this.delta= delta;
}
}
private final static String COMMENT= "//"; //$NON-NLS-1$
private int fTabWidth;
private boolean fUseSpaces;
private boolean fCloseBrace;
private boolean fIsSmartMode;
private boolean fHasTypedBrace;
private String fPartitioning;
/**
* Creates a new Java auto indent strategy for the given document partitioning.
*
* @param partitioning the document partitioning
*/
public JavaAutoIndentStrategy(String partitioning) {
fPartitioning= partitioning;
}
/**
* Evaluates the given line for the opening bracket that matches the closing bracket on the given line.
*/
private int findMatchingOpenBracket(IDocument d, int lineNumber, int endOffset, int closingBracketIncrease) throws BadLocationException {
int startOffset= d.getLineOffset(lineNumber);
int bracketCount= getBracketCount(d, startOffset, endOffset, false) - closingBracketIncrease;
// sum up the brackets counts of each line (closing brackets count negative,
// opening positive) until we find a line the brings the count to zero
while (bracketCount < 0) {
--lineNumber;
if (lineNumber < 0)
return -1;
startOffset= d.getLineOffset(lineNumber);
endOffset= startOffset + d.getLineLength(lineNumber) - 1;
bracketCount += getBracketCount(d, startOffset, endOffset, false);
}
return lineNumber;
}
private int getBracketCount(IDocument d, int startOffset, int endOffset, boolean ignoreCloseBrackets) throws BadLocationException {
int bracketCount= 0;
while (startOffset < endOffset) {
char curr= d.getChar(startOffset);
startOffset++;
switch (curr) {
case '/' :
if (startOffset < endOffset) {
char next= d.getChar(startOffset);
if (next == '*') {
// a comment starts, advance to the comment end
startOffset= getCommentEnd(d, startOffset + 1, endOffset);
} else if (next == '/') {
// '//'-comment: nothing to do anymore on this line
startOffset= endOffset;
}
}
break;
case '*' :
if (startOffset < endOffset) {
char next= d.getChar(startOffset);
if (next == '/') {
// we have been in a comment: forget what we read before
bracketCount= 0;
startOffset++;
}
}
break;
case '{' :
bracketCount++;
ignoreCloseBrackets= false;
break;
case '}' :
if (!ignoreCloseBrackets) {
bracketCount--;
}
break;
case '"' :
case '\'' :
startOffset= getStringEnd(d, startOffset, endOffset, curr);
break;
default :
}
}
return bracketCount;
}
// ----------- bracket counting ------------------------------------------------------
private int getCommentEnd(IDocument d, int offset, int endOffset) throws BadLocationException {
while (offset < endOffset) {
char curr= d.getChar(offset);
offset++;
if (curr == '*') {
if (offset < endOffset && d.getChar(offset) == '/') {
return offset + 1;
}
}
}
return endOffset;
}
private String getIndentOfLine(IDocument d, int line) throws BadLocationException {
if (line > -1) {
int start= d.getLineOffset(line);
int end= start + d.getLineLength(line) - 1;
int whiteEnd= findEndOfWhiteSpace(d, start, end);
return d.get(start, whiteEnd - start);
} else {
return ""; //$NON-NLS-1$
}
}
private int getStringEnd(IDocument d, int offset, int endOffset, char ch) throws BadLocationException {
while (offset < endOffset) {
char curr= d.getChar(offset);
offset++;
if (curr == '\\') {
// ignore escaped characters
offset++;
} else if (curr == ch) {
return offset;
}
}
return endOffset;
}
private void smartInsertAfterBracket(IDocument d, DocumentCommand c) {
if (c.offset == -1 || d.getLength() == 0)
return;
try {
int p= (c.offset == d.getLength() ? c.offset - 1 : c.offset);
int line= d.getLineOfOffset(p);
int start= d.getLineOffset(line);
int whiteend= findEndOfWhiteSpace(d, start, c.offset);
// shift only when line does not contain any text up to the closing bracket
if (whiteend == c.offset) {
// evaluate the line with the opening bracket that matches out closing bracket
int indLine= findMatchingOpenBracket(d, line, c.offset, 1);
if (indLine != -1 && indLine != line) {
// take the indent of the found line
StringBuffer replaceText= new StringBuffer(getIndentOfLine(d, indLine));
// add the rest of the current line including the just added close bracket
replaceText.append(d.get(whiteend, c.offset - whiteend));
replaceText.append(c.text);
// modify document command
c.length += c.offset - start;
c.offset= start;
c.text= replaceText.toString();
}
}
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
}
private void smartIndentAfterNewLine(IDocument d, DocumentCommand c) {
int docLength= d.getLength();
if (c.offset == -1 || docLength == 0)
return;
try {
int p= (c.offset == docLength ? c.offset - 1 : c.offset);
int line= d.getLineOfOffset(p);
StringBuffer buf= new StringBuffer(c.text);
if (c.offset < docLength && d.getChar(c.offset) == '}') {
int indLine= findMatchingOpenBracket(d, line, c.offset, 0);
if (indLine == -1) {
indLine= line;
}
buf.append(getIndentOfLine(d, indLine));
} else {
int start= d.getLineOffset(line);
ITypedRegion region= TextUtilities.getPartition(d, fPartitioning, start);
if (region != null && IJavaPartitions.JAVA_DOC.equals(region.getType()))
start= d.getLineInformationOfOffset(region.getOffset()).getOffset();
int whiteend= findEndOfWhiteSpace(d, start, c.offset);
int length= whiteend - start;
buf.append(d.get(start, length));
if (getBracketCount(d, start, c.offset, true) > 0) {
buf.append(createIndent(1, useSpaces()));
if (fHasTypedBrace && closeBrace() && !isClosed(d, c.offset, c.length)) {
c.caretOffset= c.offset + buf.length();
c.shiftsCaret= false;
// copy old content of line behind insertion point to new line
// unless we think we are inserting an anonymous type definition
IRegion reg= d.getLineInformation(line);
int lineEnd= reg.getOffset() + reg.getLength();
if (!(computeAnonymousPosition(d, c.offset - 1, fPartitioning, lineEnd) != -1)) {
int contentStart= findEndOfWhiteSpace(d, c.offset, lineEnd);
if (lineEnd - contentStart > 0) {
c.length= lineEnd - c.offset;
buf.append(d.get(contentStart, lineEnd - contentStart).toCharArray());
}
}
buf.append(getLineDelimiter(d));
buf.append(d.get(start, length));
buf.append('}');
}
} else if (isBracelessBlockStart(d, c.offset, start)) {
buf.append(createIndent(1, useSpaces()));
}
}
c.text= buf.toString();
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
}
/**
* Checks if the line seems to be an open condition not followed by a block (i.e. an if, while,
* or for statement with just one following statement, see example below).
*
* <pre>
* if (condition)
* doStuff();
* </pre>
*
* <p>Algorithm: if the last non-WS, non-Comment code on the line is an if (condition), while (condition),
* for( expression), do, else, and there is no statement after that </p>
*
* @param document the document worked on
* @param position the insert position of the new character
* @param bound the lowest position to consider
* @return <code>true</code> if the code is a conditional statement or loop without a block, <code>false</code> otherwise
*/
private boolean isBracelessBlockStart(IDocument document, int position, int bound) {
position= firstNonWhitespaceBackward(document, position, fPartitioning, bound);
if (position < 1)
return false;
// new line after do, else without brace
if (looksLike(document, position, "do") //$NON-NLS-1$
|| looksLike(document, position, "else")) //$NON-NLS-1$
return true;
try {
// new line after if,while,for + expression
if (")".equals(document.get(position, 1))) { //$NON-NLS-1$
position= findOpeningParenMatch(document, position, fPartitioning);
if (position > 0) {
position= firstNonWhitespaceBackward(document, position - 1, fPartitioning, -1);
if (position != -1) {
if (looksLike(document, position, "if") //$NON-NLS-1$
|| looksLike(document, position, "for") //$NON-NLS-1$
|| looksLike(document, position, "while")) //$NON-NLS-1$
return true;
}
}
}
} catch (BadLocationException e) {
// ignore and return false
}
return false;
}
/**
* Checks whether code>document</code> contains the <code>String</code> <code>like</code> such
* that its last character is at <code>position</code>. If <code>like</code> starts with a
* identifier part (as determined by {@link Character.isJavaIdentifier(char)}), it is also made
* sure that <code>like</code> is preceded by some non-identifier character or stands at the
* document start.
*
* @param document the document being modified
* @param position the first character position in <code>document</code> to be considered
* @param like the <code>String</code> to look for.
* @return <code>true</code> if <code>document</code> contains <code>like</code> such that it ends at <code>position</code>, <code>false</code> otherwise
*/
private static boolean looksLike(IDocument document, int position, String like) {
int length= like.length();
if (position < length - 1)
return false;
try {
if (!like.equals(document.get(position - length + 1, length)))
return false;
if (position >= length && Character.isJavaIdentifierPart(like.charAt(0)) && Character.isJavaIdentifierPart(document.getChar(position - length)))
return false;
} catch (BadLocationException e) {
return false;
}
return true;
}
/**
* Computes an insert position for an opening brace if <code>offset</code> maps to a position in
* <code>document</code> with a expression in parenthesis that will take a block after the closing parenthesis.
*
* @param document the document being modified
* @param offset the offset of the caret position, relative to the line start.
* @param partitioning the document partitioning
* @param max the max position
* @return an insert position relative to the line start if <code>line</code> contains a parenthesized expression that can be followed by a block, -1 otherwise
*/
private static int computeAnonymousPosition(IDocument document, int offset, String partitioning, int max) {
// find the opening parenthesis for every closing parenthesis on the current line after offset
// return the position behind the closing parenthesis if it looks like a method declaration
// or an expression for an if, while, for, catch statement
int pos= offset;
int length= max;
int scanTo= scanForward(document, pos, partitioning, length, '}');
if (scanTo == -1)
scanTo= length;
int closingParen= findClosingParenToLeft(document, pos, partitioning) - 1;
while (true) {
int startScan= closingParen + 1;
closingParen= scanForward(document, startScan, partitioning, scanTo, ')');
if (closingParen == -1)
break;
int openingParen= findOpeningParenMatch(document, closingParen, partitioning);
// no way an expression at the beginning of the document can mean anything
if (openingParen < 1)
break;
// only select insert positions for parenthesis currently embracing the caret
if (openingParen > pos)
continue;
if (looksLikeAnonymousClassDef(document, openingParen - 1, partitioning))
return closingParen + 1;
}
return -1;
}
/**
* Finds a closing parenthesis to the left of <code>position</code> in document, where that parenthesis is only
* separated by whitespace from <code>position</code>. If no such parenthesis can be found, <code>position</code> is returned.
*
* @param document the document being modified
* @param position the first character position in <code>document</code> to be considered
* @param partitioning the document partitioning
* @return the position of a closing parenthesis left to <code>position</code> separated only by whitespace, or <code>position</code> if no parenthesis can be found
*/
private static int findClosingParenToLeft(IDocument document, int position, String partitioning) {
final char CLOSING_PAREN= ')';
try {
if (position < 1)
return position;
int nonWS= firstNonWhitespaceBackward(document, position - 1, partitioning, -1);
if (nonWS != -1 && document.getChar(nonWS) == CLOSING_PAREN)
return nonWS;
} catch (BadLocationException e1) {
}
return position;
}
/**
* Finds the highest position in <code>document</code> such that the position is <= <code>position</code>
* and > <code>bound</code> and <code>Character.isWhitespace(document.getChar(pos))</code> evaluates to <code>false</code>
* and the position is in the default partition.
*
* @param document the document being modified
* @param position the first character position in <code>document</code> to be considered
* @param partitioning the document partitioning
* @param bound the first position in <code>document</code> to not consider any more, with <code>bound</code> > <code>position</code>
* @return the highest position of one element in <code>chars</code> in [<code>position</code>, <code>scanTo</code>) that resides in a Java partition, or <code>-1</code> if none can be found
*/
private static int firstNonWhitespaceBackward(IDocument document, int position, String partitioning, int bound) {
Assert.isTrue(position < document.getLength());
Assert.isTrue(bound >= -1);
try {
while (position > bound) {
char ch= document.getChar(position);
if (!Character.isWhitespace(ch) && isDefaultPartition(document, position, partitioning))
return position;
position--;
}
} catch (BadLocationException e) {
}
return -1;
}
/**
* Finds the lowest position in <code>document</code> such that the position is >= <code>position</code>
* and < <code>bound</code> and <code>document.getChar(position) == ch</code> evaluates to <code>true</code> for at least one
* ch in <code>chars</code> and the position is in the default partition.
*
* @param document the document being modified
* @param position the first character position in <code>document</code> to be considered
* @param partitioning the document partitioning
* @param bound the first position in <code>document</code> to not consider any more, with <code>scanTo</code> > <code>position</code>
* @param chars an array of <code>char</code> to search for
* @return the lowest position of one element in <code>chars</code> in [<code>position</code>, <code>bound</code>) that resides in a Java partition, or <code>-1</code> if none can be found
*/
private static int scanForward(IDocument document, int position, String partitioning, int bound, char[] chars) {
Assert.isTrue(position >= 0);
Assert.isTrue(bound <= document.getLength());
Arrays.sort(chars);
try {
while (position < bound) {
if (Arrays.binarySearch(chars, document.getChar(position)) >= 0 && isDefaultPartition(document, position, partitioning))
return position;
position++;
}
} catch (BadLocationException e) {
}
return -1;
}
/**
* Finds the lowest position in <code>document</code> such that the position is >= <code>position</code>
* and < <code>bound</code> and <code>document.getChar(position) == ch</code> evaluates to <code>true</code>
* and the position is in the default partition.
*
* @param document the document being modified
* @param position the first character position in <code>document</code> to be considered
* @param partitioning the document partitioning
* @param bound the first position in <code>document</code> to not consider any more, with <code>scanTo</code> > <code>position</code>
* @param ch the <code>char</code> to search for
* @return the lowest position of <code>ch</code> in (<code>bound</code>, <code>position</code>] that resides in a Java partition, or <code>-1</code> if none can be found
*/
private static int scanForward(IDocument document, int position, String partitioning, int bound, char ch) {
return scanForward(document, position, partitioning, bound, new char[] {ch});
}
/**
* Checks whether the content of <code>document</code> in the range (<code>offset</code>, <code>length</code>)
* contains the <code>new</code> keyword.
*
* @param document the document being modified
* @param offset the first character position in <code>document</code> to be considered
* @param length the length of the character range to be considered
* @param partitioning the document partitioning
* @return <code>true</code> if the specified character range contains a <code>new</code> keyword, <code>false</code> otherwise.
*/
private static boolean isNewMatch(IDocument document, int offset, int length, String partitioning) {
Assert.isTrue(length >= 0);
Assert.isTrue(offset >= 0);
Assert.isTrue(offset + length < document.getLength() + 1);
try {
String text= document.get(offset, length);
int pos= text.indexOf("new"); //$NON-NLS-1$
while (pos != -1 && !isDefaultPartition(document, pos + offset, partitioning))
pos= text.indexOf("new", pos + 2); //$NON-NLS-1$
if (pos < 0)
return false;
if (pos != 0 && Character.isJavaIdentifierPart(document.getChar(pos - 1)))
return false;
if (pos + 3 < length && Character.isJavaIdentifierPart(document.getChar(pos + 3)))
return false;
return true;
} catch (BadLocationException e) {
}
return false;
}
/**
* Checks whether the content of <code>document</code> at <code>position</code> looks like an
* anonymous class definition. <code>position</code> must be to the left of the opening
* parenthesis of the definition's parameter list.
*
* @param document the document being modified
* @param position the first character position in <code>document</code> to be considered
* @param partitioning the document partitioning
* @return <code>true</code> if the content of <code>document</code> looks like an anonymous class definition, <code>false</code> otherwise
*/
private static boolean looksLikeAnonymousClassDef(IDocument document, int position, String partitioning) {
int previousCommaOrParen= scanBackward(document, position - 1, partitioning, -1, new char[] {',', '('});
if (previousCommaOrParen == -1 || position < previousCommaOrParen + 5) // 2 for borders, 3 for "new"
return false;
if (isNewMatch(document, previousCommaOrParen + 1, position - previousCommaOrParen - 2, partitioning))
return true;
return false;
}
/**
* Checks whether <code>position</code> resides in a default (Java) partition of <code>document</code>.
*
* @param document the document being modified
* @param position the position to be checked
* @param partitioning the document partitioning
* @return <code>true</code> if <code>position</code> is in the default partition of <code>document</code>, <code>false</code> otherwise
*/
private static boolean isDefaultPartition(IDocument document, int position, String partitioning) {
Assert.isTrue(position >= 0);
Assert.isTrue(position <= document.getLength());
try {
ITypedRegion region= TextUtilities.getPartition(document, partitioning, position);
return region != null && region.getType().equals(IDocument.DEFAULT_CONTENT_TYPE);
} catch (BadLocationException e) {
}
return false;
}
/**
* Finds the position of the parenthesis matching the closing parenthesis at <code>position</code>.
*
* @param document the document being modified
* @param position the position in <code>document</code> of a closing parenthesis
* @param partitioning the document partitioning
* @return the position in <code>document</code> of the matching parenthesis, or -1 if none can be found
*/
private static int findOpeningParenMatch(IDocument document, int position, String partitioning) {
final char CLOSING_PAREN= ')';
final char OPENING_PAREN= '(';
Assert.isTrue(position < document.getLength());
Assert.isTrue(position >= 0);
Assert.isTrue(isDefaultPartition(document, position, partitioning));
try {
Assert.isTrue(document.getChar(position) == CLOSING_PAREN);
int depth= 1;
while (true) {
position= scanBackward(document, position - 1, partitioning, -1, new char[] {CLOSING_PAREN, OPENING_PAREN});
if (position == -1)
return -1;
if (document.getChar(position) == CLOSING_PAREN)
depth++;
else
depth--;
if (depth == 0)
return position;
}
} catch (BadLocationException e) {
return -1;
}
}
/**
* Finds the highest position in <code>document</code> such that the position is <= <code>position</code>
* and > <code>bound</code> and <code>document.getChar(position) == ch</code> evaluates to <code>true</code> for at least one
* ch in <code>chars</code> and the position is in the default partition.
*
* @param document the document being modified
* @param position the first character position in <code>document</code> to be considered
* @param partitioning the document partitioning
* @param bound the first position in <code>document</code> to not consider any more, with <code>scanTo</code> > <code>position</code>
* @param chars an array of <code>char</code> to search for
* @return the highest position of one element in <code>chars</code> in [<code>position</code>, <code>scanTo</code>) that resides in a Java partition, or <code>-1</code> if none can be found
*/
private static int scanBackward(IDocument document, int position, String partitioning, int bound, char[] chars) {
Assert.isTrue(bound >= -1);
Assert.isTrue(position < document.getLength() );
Arrays.sort(chars);
try {
while (position > bound) {
if (Arrays.binarySearch(chars, document.getChar(position)) >= 0 && isDefaultPartition(document, position, partitioning))
return position;
position--;
}
} catch (BadLocationException e) {
}
return -1;
}
private boolean isClosed(IDocument document, int offset, int length) {
CompilationUnitInfo info= getCompilationUnitForMethod(document, offset, fPartitioning);
if (info == null)
return false;
CompilationUnit compilationUnit= null;
try {
compilationUnit= AST.parseCompilationUnit(info.buffer);
} catch (ArrayIndexOutOfBoundsException x) {
// work around for parser problem
return false;
}
IProblem[] problems= compilationUnit.getProblems();
for (int i= 0; i != problems.length; ++i) {
if (problems[i].getID() == IProblem.UnmatchedBracket)
return true;
}
final int relativeOffset= offset - info.delta;
ASTNode node= NodeFinder.perform(compilationUnit, relativeOffset, length);
if (node == null)
return false;
if (length == 0) {
while (node != null && (relativeOffset == node.getStartPosition() || relativeOffset == node.getStartPosition() + node.getLength()))
node= node.getParent();
}
switch (node.getNodeType()) {
case ASTNode.BLOCK:
return areBlocksConsistent(document, offset, fPartitioning);
case ASTNode.IF_STATEMENT:
{
IfStatement ifStatement= (IfStatement) node;
Expression expression= ifStatement.getExpression();
IRegion expressionRegion= createRegion(expression, info.delta);
Statement thenStatement= ifStatement.getThenStatement();
IRegion thenRegion= createRegion(thenStatement, info.delta);
// between expression and then statement
if (expressionRegion.getOffset() + expressionRegion.getLength() <= offset && offset + length <= thenRegion.getOffset())
return thenStatement != null;
Statement elseStatement= ifStatement.getElseStatement();
IRegion elseRegion= createRegion(elseStatement, info.delta);
IRegion elseToken= null;
if (elseStatement != null) {
int sourceOffset= thenRegion.getOffset() + thenRegion.getLength();
int sourceLength= elseRegion.getOffset() - sourceOffset;
elseToken= getToken(document, new Region(sourceOffset, sourceLength), ITerminalSymbols.TokenNameelse);
}
// between 'else' keyword and else statement
if (elseToken.getOffset() + elseToken.getLength() <= offset && offset + length < elseRegion.getOffset())
return elseStatement != null;
}
break;
case ASTNode.WHILE_STATEMENT:
case ASTNode.FOR_STATEMENT:
{
Expression expression= node.getNodeType() == ASTNode.WHILE_STATEMENT ? ((WhileStatement) node).getExpression() : ((ForStatement) node).getExpression();
IRegion expressionRegion= createRegion(expression, info.delta);
Statement body= node.getNodeType() == ASTNode.WHILE_STATEMENT ? ((WhileStatement) node).getBody() : ((ForStatement) node).getBody();
IRegion bodyRegion= createRegion(body, info.delta);
// between expression and body statement
if (expressionRegion.getOffset() + expressionRegion.getLength() <= offset && offset + length <= bodyRegion.getOffset())
return body != null;
}
break;
case ASTNode.DO_STATEMENT:
{
DoStatement doStatement= (DoStatement) node;
IRegion doRegion= createRegion(doStatement, info.delta);
Statement body= doStatement.getBody();
IRegion bodyRegion= createRegion(body, info.delta);
if (doRegion.getOffset() + doRegion.getLength() <= offset && offset + length <= bodyRegion.getOffset())
return body != null;
}
break;
}
return true;
}
private static String getLineDelimiter(IDocument document) {
try {
if (document.getNumberOfLines() > 1)
return document.getLineDelimiter(0);
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
return System.getProperty("line.separator"); //$NON-NLS-1$
}
private static boolean startsWithClosingBrace(String string) {
final int length= string.length();
int i= 0;
while (i != length && Character.isWhitespace(string.charAt(i)))
++i;
if (i == length)
return false;
return string.charAt(i) == '}';
}
private void smartPaste(IDocument document, DocumentCommand command) {
String lineDelimiter= getLineDelimiter(document);
try {
String pastedText= command.text;
Assert.isNotNull(pastedText);
Assert.isTrue(pastedText.length() > 1);
// extend selection begin if only whitespaces
int selectionStart= command.offset;
IRegion region= document.getLineInformationOfOffset(selectionStart);
String notSelected= document.get(region.getOffset(), selectionStart - region.getOffset());
String selected= document.get(selectionStart, region.getOffset() + region.getLength() - selectionStart);
if (notSelected.trim().length() == 0 && selected.trim().length() != 0) {
pastedText= notSelected + pastedText;
command.length += notSelected.length();
command.offset= region.getOffset();
}
// choose smaller indent of block and preceeding non-empty line
String blockIndent= getBlockIndent(document, command);
String insideBlockIndent= blockIndent == null ? "" : blockIndent + createIndent(1, useSpaces()); //$NON-NLS-1$ // add one indent level
int insideBlockIndentSize= calculateDisplayedWidth(insideBlockIndent, getTabWidth());
int previousIndentSize= getIndentSize(document, command);
int newIndentSize= insideBlockIndentSize < previousIndentSize ? insideBlockIndentSize : previousIndentSize;
// indent is different if block starts with '}'
if (startsWithClosingBrace(pastedText)) {
int outsideBlockIndentSize= blockIndent == null ? 0 : calculateDisplayedWidth(blockIndent, getTabWidth());
newIndentSize = outsideBlockIndentSize;
}
// check selection
int offset= command.offset;
int line= document.getLineOfOffset(offset);
int lineOffset= document.getLineOffset(line);
String prefix= document.get(lineOffset, offset - lineOffset);
boolean formatFirstLine= prefix.trim().length() == 0;
String formattedParagraph= format(pastedText, newIndentSize, lineDelimiter, formatFirstLine);
// paste
if (formatFirstLine) {
int end= command.offset + command.length;
command.offset= lineOffset;
command.length= end - command.offset;
}
command.text= formattedParagraph;
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
}
private static String getIndentOfLine(String line) {
int i= 0;
for (; i < line.length(); i++) {
if (! Character.isWhitespace(line.charAt(i)))
break;
}
return line.substring(0, i);
}
/**
* Returns the indent of the first non empty line.
* A line is considered empty if it only consists of whitespaces or if it
* begins with a single line comment followed by whitespaces only.
*/
private static int getIndentSizeOfFirstLine(String paragraph, boolean includeFirstLine, int tabWidth) {
for (final Iterator iterator= new LineIterator(paragraph); iterator.hasNext();) {
final String line= (String) iterator.next();
if (!includeFirstLine) {
includeFirstLine= true;
continue;
}
String indent= null;
if (line.startsWith(COMMENT)) {
String commentedLine= line.substring(2);
// line is empty
if (commentedLine.trim().length() == 0)
continue;
indent= COMMENT + getIndentOfLine(commentedLine);
} else {
// line is empty
if (line.trim().length() == 0)
continue;
indent= getIndentOfLine(line);
}
return calculateDisplayedWidth(indent, tabWidth);
}
return 0;
}
/**
* Returns the minimal indent size of all non empty lines;
*/
private static int getMinimalIndentSize(String paragraph, boolean includeFirstLine, int tabWidth) {
int minIndentSize= Integer.MAX_VALUE;
for (final Iterator iterator= new LineIterator(paragraph); iterator.hasNext();) {
final String line= (String) iterator.next();
if (!includeFirstLine) {
includeFirstLine= true;
continue;
}
String indent= null;
if (line.startsWith(COMMENT)) {
String commentedLine= line.substring(2);
// line is empty
if (commentedLine.trim().length() == 0)
continue;
indent= COMMENT + getIndentOfLine(commentedLine);
} else {
// line is empty
if (line.trim().length() == 0)
continue;
indent=getIndentOfLine(line);
}
final int indentSize= calculateDisplayedWidth(indent, tabWidth);
if (indentSize < minIndentSize)
minIndentSize= indentSize;
}
return minIndentSize == Integer.MAX_VALUE ? 0 : minIndentSize;
}
/**
* Returns the displayed width of a string, taking in account the displayed tab width.
* The result can be compared against the print margin.
*/
private static int calculateDisplayedWidth(String string, int tabWidth) {
int column= 0;
for (int i= 0; i < string.length(); i++)
if ('\t' == string.charAt(i))
column += tabWidth - (column % tabWidth);
else
column++;
return column;
}
private static boolean isLineEmpty(IDocument document, int line) throws BadLocationException {
IRegion region= document.getLineInformation(line);
String string= document.get(region.getOffset(), region.getLength());
return string.trim().length() == 0;
}
private int getIndentSize(IDocument document, DocumentCommand command) {
StringBuffer buffer= new StringBuffer();
int docLength= document.getLength();
if (command.offset == -1 || docLength == 0)
return 0;
try {
int p= (command.offset == docLength ? command.offset - 1 : command.offset);
int line= document.getLineOfOffset(p);
IRegion region= document.getLineInformation(line);
String string= document.get(region.getOffset(), command.offset - region.getOffset());
if (line != 0 && string.trim().length() == 0)
--line;
while (line != 0 && isLineEmpty(document, line))
--line;
int start= document.getLineOffset(line);
// if line is at end of a javadoc comment, take the indent from the comment's begin line
ITypedRegion typedRegion= TextUtilities.getPartition(document, fPartitioning, start);
if (typedRegion != null) {
if (IJavaPartitions.JAVA_DOC.equals(typedRegion.getType())) {
start= document.getLineInformationOfOffset(typedRegion.getOffset()).getOffset();
} else if (IJavaPartitions.JAVA_SINGLE_LINE_COMMENT.equals(typedRegion.getType())) {
buffer.append(COMMENT);
start += 2;
}
}
int whiteend= findEndOfWhiteSpace(document, start, command.offset);
buffer.append(document.get(start, whiteend - start));
if (getBracketCount(document, start, command.offset, true) > 0) {
buffer.append(createIndent(1, useSpaces()));
}
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
return calculateDisplayedWidth(buffer.toString(), getTabWidth());
}
private String getBlockIndent(IDocument d, DocumentCommand c) {
if (c.offset < 0 || d.getLength() == 0)
return null;
try {
int p= (c.offset == d.getLength() ? c.offset - 1 : c.offset);
int line= d.getLineOfOffset(p);
// evaluate the line with the opening bracket that matches out closing bracket
int indLine= findMatchingOpenBracket(d, line, c.offset, 1);
if (indLine != -1)
// take the indent of the found line
return getIndentOfLine(d, indLine);
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
return null;
}
private String createIndent(int level, boolean useSpaces) {
StringBuffer buffer= new StringBuffer();
if (useSpaces) {
// Fix for bug 29909 contributed by Nikolay Metchev
int width= level * getTabWidth();
for (int i= 0; i != width; ++i)
buffer.append(' ');
} else {
for (int i= 0; i != level; ++i)
buffer.append('\t');
}
return buffer.toString();
}
/**
* Extends the string to match displayed width.
* String is either the empty string or "//" and should not contain whites.
*/
private static String changePrefix(String string, int displayedWidth, boolean useSpaces, int tabWidth) {
// assumption: string contains no whitespace
final StringBuffer buffer= new StringBuffer(string);
int column= calculateDisplayedWidth(buffer.toString(), tabWidth);
if (column > displayedWidth)
return string;
if (useSpaces) {
while (column != displayedWidth) {
buffer.append(' ');
++column;
}
} else {
while (column != displayedWidth) {
if (column + tabWidth - (column % tabWidth) <= displayedWidth) {
buffer.append('\t');
column += tabWidth - (column % tabWidth);
} else {
buffer.append(' ');
++column;
}
}
}
return buffer.toString();
}
/**
* Formats a paragraph such that the first non-empty line of the paragraph
* will have an indent of size newIndentSize.
*/
private String format(String paragraph, int newIndentSize, String lineDelimiter, boolean indentFirstLine) {
final int tabWidth= getTabWidth();
final int firstLineIndentSize= getIndentSizeOfFirstLine(paragraph, indentFirstLine, tabWidth);
final int minIndentSize= getMinimalIndentSize(paragraph, indentFirstLine, tabWidth);
if (newIndentSize < firstLineIndentSize - minIndentSize)
newIndentSize= firstLineIndentSize - minIndentSize;
final StringBuffer buffer= new StringBuffer();
for (final Iterator iterator= new LineIterator(paragraph); iterator.hasNext();) {
String line= (String) iterator.next();
if (indentFirstLine) {
String lineIndent= null;
if (line.startsWith(COMMENT))
lineIndent= COMMENT + getIndentOfLine(line.substring(2));
else
lineIndent= getIndentOfLine(line);
String lineContent= line.substring(lineIndent.length());
if (lineContent.length() == 0) {
// line was empty; insert as is
buffer.append(line);
} else {
int indentSize= calculateDisplayedWidth(lineIndent, tabWidth);
int deltaSize= newIndentSize - firstLineIndentSize;
lineIndent= changePrefix(lineIndent.trim(), indentSize + deltaSize, useSpaces(), tabWidth);
buffer.append(lineIndent);
buffer.append(lineContent);
}
} else {
indentFirstLine= true;
buffer.append(line);
}
if (iterator.hasNext())
buffer.append(lineDelimiter);
}
return buffer.toString();
}
private boolean isLineDelimiter(IDocument document, String text) {
String[] delimiters= document.getLegalLineDelimiters();
if (delimiters != null)
return TextUtilities.equals(delimiters, text) > -1;
return false;
}
private void smartIndentAfterBlockDelimiter(IDocument document, DocumentCommand command) {
if (command.text.charAt(0) == '}')
smartInsertAfterBracket(document, command);
}
/*
* @see org.eclipse.jface.text.IAutoIndentStrategy#customizeDocumentCommand(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.DocumentCommand)
*/
public void customizeDocumentCommand(IDocument d, DocumentCommand c) {
clearCachedValues();
if (!isSmartMode())
return;
if (c.length == 0 && c.text != null && isLineDelimiter(d, c.text))
smartIndentAfterNewLine(d, c);
else if (c.text.length() == 1)
smartIndentAfterBlockDelimiter(d, c);
else if (c.text.length() > 1 && getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SMART_PASTE))
smartPaste(d, c);
fHasTypedBrace= false;
if (c.text.length() > 0) {
if (c.text.charAt(c.text.length() - 1) == '{')
fHasTypedBrace= true;
}
}
private static IPreferenceStore getPreferenceStore() {
return JavaPlugin.getDefault().getPreferenceStore();
}
private boolean useSpaces() {
return fUseSpaces;
}
private boolean closeBrace() {
return fCloseBrace;
}
private int getTabWidth() {
return fTabWidth;
}
private boolean isSmartMode() {
return fIsSmartMode;
}
private void clearCachedValues() {
// Fix for bug 29909 contributed by Nikolay Metchev
fTabWidth= CodeFormatterUtil.getTabWidth();
IPreferenceStore preferenceStore= getPreferenceStore();
fUseSpaces= preferenceStore.getBoolean(PreferenceConstants.EDITOR_SPACES_FOR_TABS);
fCloseBrace= preferenceStore.getBoolean(PreferenceConstants.EDITOR_CLOSE_BRACES);
fIsSmartMode= computeSmartMode();
}
private boolean computeSmartMode() {
IWorkbenchPage page= JavaPlugin.getActivePage();
if (page != null) {
IEditorPart part= page.getActiveEditor();
if (part instanceof ITextEditorExtension3) {
ITextEditorExtension3 extension= (ITextEditorExtension3) part;
return extension.getInsertMode() == ITextEditorExtension3.SMART_INSERT;
}
}
return false;
}
private static int searchForClosingPeer(IDocument document, int position, String partitioning, final char openingPeer, final char closingPeer) {
Assert.isTrue(position >= 0);
try {
int length= document.getLength();
int depth= 1;
position -= 1;
while (true) {
position= scanForward(document, position + 1, partitioning, length, new char[] {openingPeer, closingPeer});
if (position == -1)
return -1;
if (document.getChar(position) == openingPeer)
depth++;
else
depth--;
if (depth == 0)
return position;
}
} catch (BadLocationException e) {
return -1;
}
}
private static int searchForOpeningPeer(IDocument document, int position, String partitioning, final char openingPeer, final char closingPeer) {
Assert.isTrue(position < document.getLength());
try {
int depth= 1;
position += 1;
while (true) {
position= scanBackward(document, position - 1, partitioning, -1, new char[] {openingPeer, closingPeer});
if (position == -1)
return -1;
if (document.getChar(position) == closingPeer)
depth++;
else
depth--;
if (depth == 0)
return position;
}
} catch (BadLocationException e) {
return -1;
}
}
private static IRegion getSurroundingBlock(IDocument document, int offset, String partitioning) {
if (offset < 1 || offset >= document.getLength())
return null;
int begin= searchForOpeningPeer(document, offset - 1, partitioning, '{', '}');
int end= searchForClosingPeer(document, offset, partitioning, '{', '}');
if (begin == -1 || end == -1)
return null;
return new Region(begin, end + 1 - begin);
}
private static CompilationUnitInfo getCompilationUnitForMethod(IDocument document, int offset, String partitioning) {
try {
IRegion sourceRange= getSurroundingBlock(document, offset, partitioning);
if (sourceRange == null)
return null;
String source= document.get(sourceRange.getOffset(), sourceRange.getLength());
StringBuffer contents= new StringBuffer();
contents.append("class ____C{void ____m()"); //$NON-NLS-1$
final int methodOffset= contents.length();
contents.append(source);
contents.append('}');
char[] buffer= contents.toString().toCharArray();
return new CompilationUnitInfo(buffer, sourceRange.getOffset() - methodOffset);
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
return null;
}
private static boolean areBlocksConsistent(IDocument document, int offset, String partitioning) {
if (offset < 1 || offset >= document.getLength())
return false;
int begin= offset;
int end= offset - 1;
while (true) {
begin= searchForOpeningPeer(document, begin - 1, partitioning, '{', '}');
end= searchForClosingPeer(document, end + 1, partitioning, '{', '}');
if (begin == -1 && end == -1)
return true;
if (begin == -1 || end == -1)
return false;
}
}
private static IRegion createRegion(ASTNode node, int delta) {
return node == null ? null : new Region(node.getStartPosition() + delta, node.getLength());
}
private static IRegion getToken(IDocument document, IRegion scanRegion, int tokenId) {
try {
final String source= document.get(scanRegion.getOffset(), scanRegion.getLength());
IScanner scanner= ToolFactory.createScanner(false, false, false, false);
scanner.setSource(source.toCharArray());
int id= scanner.getNextToken();
while (id != ITerminalSymbols.TokenNameEOF && id != tokenId)
id= scanner.getNextToken();
if (id == ITerminalSymbols.TokenNameEOF)
return null;
int tokenOffset= scanner.getCurrentTokenStartPosition();
int tokenLength= scanner.getCurrentTokenEndPosition() + 1 - tokenOffset; // inclusive end
return new Region(tokenOffset + scanRegion.getOffset(), tokenLength);
} catch (InvalidInputException x) {
return null;
} catch (BadLocationException x) {
return null;
}
}
}
|
41,701 |
Bug 41701 Cannot open AntEditor due to NPE in ExtendedTextEditor
|
in 20030819: java.lang.NullPointerException at java.lang.Throwable.<init>(Throwable.java) at java.lang.Throwable.<init>(Throwable.java) at java.lang.NullPointerException.<init>(NullPointerException.java:63) at org.eclipse.ui.texteditor.ExtendedTextEditor.initializeChangeRulerColumn(ExtendedTextEditor.java:509) at org.eclipse.ui.texteditor.ExtendedTextEditor.createChangeRulerColumn(ExtendedTextEditor.java:595) at org.eclipse.ui.texteditor.ExtendedTextEditor.createCompositeRuler(ExtendedTextEditor.java:619) at org.eclipse.ui.texteditor.ExtendedTextEditor.createVerticalRuler(ExtendedTextEditor.java:603) at org.eclipse.ui.texteditor.AbstractTextEditor.createPartControl(AbstractTextEditor.java:2047) at org.eclipse.ui.texteditor.StatusTextEditor.createPartControl(StatusTextEditor.java:53) at org.eclipse.ui.texteditor.ExtendedTextEditor.createPartControl(ExtendedTextEditor.java:259) at org.eclipse.ui.internal.PartPane$4.run(PartPane.java:141) at org.eclipse.core.internal.runtime.InternalPlatform.run(InternalPlatform.java) at org.eclipse.core.runtime.Platform.run(Platform.java) at org.eclipse.ui.internal.PartPane.createChildControl(PartPane.java:137) at org.eclipse.ui.internal.PartPane.createControl(PartPane.java:186) at org.eclipse.ui.internal.EditorWorkbook.createPage(EditorWorkbook.java:404) at org.eclipse.ui.internal.EditorWorkbook.add(EditorWorkbook.java:123) at org.eclipse.ui.internal.EditorArea.addEditor(EditorArea.java:55) at org.eclipse.ui.internal.EditorPresentation.openEditor(EditorPresentation.java:351) at org.eclipse.ui.internal.EditorManager$2.run(EditorManager.java:585) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java) at org.eclipse.ui.internal.EditorManager.createEditorTab(EditorManager.java:574) at org.eclipse.ui.internal.EditorManager.openInternalEditor(EditorManager.java:668) at org.eclipse.ui.internal.EditorManager.openEditorFromDescriptor(EditorManager.java:459) at org.eclipse.ui.internal.EditorManager.openEditor(EditorManager.java:431) at org.eclipse.ui.internal.WorkbenchPage.busyOpenEditor(WorkbenchPage.java:2069) at org.eclipse.ui.internal.WorkbenchPage.access$6(WorkbenchPage.java:2019) at org.eclipse.ui.internal.WorkbenchPage$9.run(WorkbenchPage.java:2006) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java) at org.eclipse.ui.internal.WorkbenchPage.openEditor(WorkbenchPage.java:2001) at org.eclipse.ui.internal.WorkbenchPage.openEditor(WorkbenchPage.java:1894) at org.eclipse.ui.actions.OpenWithMenu.openEditor(OpenWithMenu.java:237) at org.eclipse.ui.actions.OpenWithMenu.access$0(OpenWithMenu.java:231) at org.eclipse.ui.actions.OpenWithMenu$2.handleEvent(OpenWithMenu.java:155) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1676) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1659) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at java.lang.reflect.AccessibleObject.invokeL(AccessibleObject.java:207) at java.lang.reflect.Method.invoke(Method.java:271) at org.eclipse.core.launcher.Main.basicRun(Main.java:291) at org.eclipse.core.launcher.Main.run(Main.java:747) at org.eclipse.core.launcher.Main.main(Main.java:583)
|
resolved fixed
|
e3a8118
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-20T09:02:03Z | 2003-08-19T16:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/JavaEditor.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.javaeditor;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ResourceBundle;
import java.util.StringTokenizer;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Preferences;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BidiSegmentEvent;
import org.eclipse.swt.custom.BidiSegmentListener;
import org.eclipse.swt.custom.StyleRange;
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.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
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.Separator;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.IPostSelectionProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.text.BadLocationException;
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.ITextInputListener;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.ITextViewerExtension2;
import org.eclipse.jface.text.ITextViewerExtension3;
import org.eclipse.jface.text.ITextViewerExtension4;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.text.TextUtilities;
import org.eclipse.jface.text.information.IInformationProvider;
import org.eclipse.jface.text.information.IInformationProviderExtension2;
import org.eclipse.jface.text.information.InformationPresenter;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.IAnnotationAccess;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.IOverviewRuler;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.IVerticalRuler;
import org.eclipse.jface.text.source.LineChangeHover;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
import org.eclipse.ui.IEditorActionBarContributor;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPartService;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.EditorActionBarContributor;
import org.eclipse.ui.part.IShowInTargetList;
import org.eclipse.ui.texteditor.AddTaskAction;
import org.eclipse.ui.texteditor.AnnotationPreference;
import org.eclipse.ui.texteditor.DefaultRangeIndicator;
import org.eclipse.ui.texteditor.ExtendedTextEditor;
import org.eclipse.ui.texteditor.IAbstractTextEditorHelpContextIds;
import org.eclipse.ui.texteditor.IEditorStatusLine;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
import org.eclipse.ui.texteditor.MarkerAnnotation;
import org.eclipse.ui.texteditor.ResourceAction;
import org.eclipse.ui.texteditor.SourceViewerDecorationSupport;
import org.eclipse.ui.texteditor.TextEditorAction;
import org.eclipse.ui.texteditor.TextOperationAction;
import org.eclipse.ui.views.contentoutline.ContentOutline;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
import org.eclipse.ui.views.tasklist.TaskList;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICodeAssist;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IImportContainer;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IPackageDeclaration;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.ISourceReference;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.actions.IJavaEditorActionDefinitionIds;
import org.eclipse.jdt.ui.actions.JavaSearchActionGroup;
import org.eclipse.jdt.ui.actions.OpenEditorActionGroup;
import org.eclipse.jdt.ui.actions.OpenViewActionGroup;
import org.eclipse.jdt.ui.actions.ShowActionGroup;
import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.GoToNextPreviousMemberAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.SelectionHistory;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectEnclosingAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectHistoryAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectNextAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectPreviousAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectionAction;
import org.eclipse.jdt.internal.ui.text.HTMLTextPresenter;
import org.eclipse.jdt.internal.ui.text.IJavaPartitions;
import org.eclipse.jdt.internal.ui.text.JavaChangeHover;
import org.eclipse.jdt.internal.ui.text.JavaPairMatcher;
import org.eclipse.jdt.internal.ui.util.JavaUIHelp;
import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider;
/**
* Java specific text editor.
*/
public abstract class JavaEditor extends ExtendedTextEditor implements IViewPartInputProvider {
/**
* Internal implementation class for a change listener.
* @since 3.0
*/
protected abstract class AbstractSelectionChangedListener implements ISelectionChangedListener {
/**
* Installs this selection changed listener with the given selection provider. If
* the selection provider is a post selection provider, post selection changed
* events are the preferred choice, otherwise normal selection changed events
* are requested.
*
* @param selectionProvider
*/
public void install(ISelectionProvider selectionProvider) {
if (selectionProvider == null)
return;
if (selectionProvider instanceof IPostSelectionProvider) {
IPostSelectionProvider provider= (IPostSelectionProvider) selectionProvider;
provider.addPostSelectionChangedListener(this);
} else {
selectionProvider.addSelectionChangedListener(this);
}
}
/**
* Removes this selection changed listener from the given selection provider.
*
* @param selectionProvider
*/
public void uninstall(ISelectionProvider selectionProvider) {
if (selectionProvider == null)
return;
if (selectionProvider instanceof IPostSelectionProvider) {
IPostSelectionProvider provider= (IPostSelectionProvider) selectionProvider;
provider.removePostSelectionChangedListener(this);
} else {
selectionProvider.removeSelectionChangedListener(this);
}
}
}
/**
* Updates the Java outline page selection and this editor's range indicator.
*
* @since 3.0
*/
private class EditorSelectionChangedListener extends AbstractSelectionChangedListener {
/*
* @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent)
*/
public void selectionChanged(SelectionChangedEvent event) {
selectionChanged();
}
public void selectionChanged() {
ISourceReference element= computeHighlightRangeSourceReference();
synchronizeOutlinePage(element);
setSelection(element, false);
}
}
/**
* Updates the selection in the editor's widget with the selection of the outline page.
*/
class OutlineSelectionChangedListener extends AbstractSelectionChangedListener {
public void selectionChanged(SelectionChangedEvent event) {
doSelectionChanged(event);
}
}
/*
* Link mode.
*/
class MouseClickListener implements KeyListener, MouseListener, MouseMoveListener,
FocusListener, PaintListener, IPropertyChangeListener, IDocumentListener, ITextInputListener {
/** The session is active. */
private boolean fActive;
/** The currently active style range. */
private IRegion fActiveRegion;
/** The currently active style range as position. */
private Position fRememberedPosition;
/** The hand cursor. */
private Cursor fCursor;
/** The link color. */
private Color fColor;
/** The key modifier mask. */
private int fKeyModifierMask;
public void deactivate() {
deactivate(false);
}
public void deactivate(boolean redrawAll) {
if (!fActive)
return;
repairRepresentation(redrawAll);
fActive= false;
}
public void install() {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
StyledText text= sourceViewer.getTextWidget();
if (text == null || text.isDisposed())
return;
updateColor(sourceViewer);
sourceViewer.addTextInputListener(this);
IDocument document= sourceViewer.getDocument();
if (document != null)
document.addDocumentListener(this);
text.addKeyListener(this);
text.addMouseListener(this);
text.addMouseMoveListener(this);
text.addFocusListener(this);
text.addPaintListener(this);
updateKeyModifierMask();
IPreferenceStore preferenceStore= getPreferenceStore();
preferenceStore.addPropertyChangeListener(this);
}
private void updateKeyModifierMask() {
String modifiers= getPreferenceStore().getString(BROWSER_LIKE_LINKS_KEY_MODIFIER);
fKeyModifierMask= computeStateMask(modifiers);
if (fKeyModifierMask == -1) {
// Fallback to stored state mask
fKeyModifierMask= getPreferenceStore().getInt(BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK);
}
}
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;
}
public void uninstall() {
if (fColor != null) {
fColor.dispose();
fColor= null;
}
if (fCursor != null) {
fCursor.dispose();
fCursor= null;
}
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
sourceViewer.removeTextInputListener(this);
IDocument document= sourceViewer.getDocument();
if (document != null)
document.removeDocumentListener(this);
IPreferenceStore preferenceStore= getPreferenceStore();
if (preferenceStore != null)
preferenceStore.removePropertyChangeListener(this);
StyledText text= sourceViewer.getTextWidget();
if (text == null || text.isDisposed())
return;
text.removeKeyListener(this);
text.removeMouseListener(this);
text.removeMouseMoveListener(this);
text.removeFocusListener(this);
text.removePaintListener(this);
}
/*
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
if (event.getProperty().equals(JavaEditor.LINK_COLOR)) {
ISourceViewer viewer= getSourceViewer();
if (viewer != null)
updateColor(viewer);
} else if (event.getProperty().equals(BROWSER_LIKE_LINKS_KEY_MODIFIER)) {
updateKeyModifierMask();
}
}
private void updateColor(ISourceViewer viewer) {
if (fColor != null)
fColor.dispose();
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
Display display= text.getDisplay();
fColor= createColor(getPreferenceStore(), JavaEditor.LINK_COLOR, display);
}
/**
* 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);
if (rgb != null)
return new Color(display, rgb);
}
return null;
}
private void repairRepresentation() {
repairRepresentation(false);
}
private void repairRepresentation(boolean redrawAll) {
if (fActiveRegion == null)
return;
ISourceViewer viewer= getSourceViewer();
if (viewer != null) {
resetCursor(viewer);
int offset= fActiveRegion.getOffset();
int length= fActiveRegion.getLength();
// remove style
if (!redrawAll && viewer instanceof ITextViewerExtension2)
((ITextViewerExtension2) viewer).invalidateTextPresentation(offset, length);
else
viewer.invalidateTextPresentation();
// remove underline
if (viewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) viewer;
offset= extension.modelOffset2WidgetOffset(offset);
} else {
offset -= viewer.getVisibleRegion().getOffset();
}
StyledText text= viewer.getTextWidget();
try {
text.redrawRange(offset, length, true);
} catch (IllegalArgumentException x) {
JavaPlugin.log(x);
}
}
fActiveRegion= null;
}
// will eventually be replaced by a method provided by jdt.core
private IRegion selectWord(IDocument document, int anchor) {
try {
int offset= anchor;
char c;
while (offset >= 0) {
c= document.getChar(offset);
if (!Character.isJavaIdentifierPart(c))
break;
--offset;
}
int start= offset;
offset= anchor;
int length= document.getLength();
while (offset < length) {
c= document.getChar(offset);
if (!Character.isJavaIdentifierPart(c))
break;
++offset;
}
int end= offset;
if (start == end)
return new Region(start, 0);
else
return new Region(start + 1, end - start - 1);
} catch (BadLocationException x) {
return null;
}
}
IRegion getCurrentTextRegion(ISourceViewer viewer) {
int offset= getCurrentTextOffset(viewer);
if (offset == -1)
return null;
IJavaElement input= SelectionConverter.getInput(JavaEditor.this);
if (input == null)
return null;
try {
IJavaElement[] elements= null;
synchronized (input) {
elements= ((ICodeAssist) input).codeSelect(offset, 0);
}
if (elements == null || elements.length == 0)
return null;
return selectWord(viewer.getDocument(), offset);
} catch (JavaModelException e) {
return null;
}
}
private int getCurrentTextOffset(ISourceViewer viewer) {
try {
StyledText text= viewer.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 (viewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) viewer;
return extension.widgetOffset2ModelOffset(widgetOffset);
} else {
return widgetOffset + viewer.getVisibleRegion().getOffset();
}
} catch (IllegalArgumentException e) {
return -1;
}
}
private void highlightRegion(ISourceViewer viewer, IRegion region) {
if (region.equals(fActiveRegion))
return;
repairRepresentation();
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
// highlight region
int offset= 0;
int length= 0;
if (viewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) viewer;
IRegion widgetRange= extension.modelRange2WidgetRange(region);
if (widgetRange == null)
return;
offset= widgetRange.getOffset();
length= widgetRange.getLength();
} else {
offset= region.getOffset() - viewer.getVisibleRegion().getOffset();
length= region.getLength();
}
StyleRange oldStyleRange= text.getStyleRangeAtOffset(offset);
Color foregroundColor= fColor;
Color backgroundColor= oldStyleRange == null ? text.getBackground() : oldStyleRange.background;
StyleRange styleRange= new StyleRange(offset, length, foregroundColor, backgroundColor);
text.setStyleRange(styleRange);
// underline
text.redrawRange(offset, length, true);
fActiveRegion= region;
}
private void activateCursor(ISourceViewer 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 void resetCursor(ISourceViewer viewer) {
StyledText text= viewer.getTextWidget();
if (text != null && !text.isDisposed())
text.setCursor(null);
if (fCursor != null) {
fCursor.dispose();
fCursor= null;
}
}
/*
* @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.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;
deactivate();
if (wasActive) {
IAction action= getAction("OpenEditor"); //$NON-NLS-1$
if (action != null)
action.run();
}
}
/*
* @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;
}
ISourceViewer viewer= getSourceViewer();
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= getCurrentTextRegion(viewer);
if (region == null || region.getLength() == 0) {
repairRepresentation();
return;
}
highlightRegion(viewer, region);
activateCursor(viewer);
}
/*
* @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();
}
/*
* @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 && !fRememberedPosition.isDeleted()) {
event.getDocument().removePosition(fRememberedPosition);
fActiveRegion= new Region(fRememberedPosition.getOffset(), fRememberedPosition.getLength());
}
fRememberedPosition= null;
ISourceViewer viewer= getSourceViewer();
if (viewer != null) {
StyledText widget= viewer.getTextWidget();
if (widget != null && !widget.isDisposed()) {
widget.getDisplay().asyncExec(new Runnable() {
public void run() {
deactivate();
}
});
}
}
}
/*
* @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);
}
/*
* @see PaintListener#paintControl(PaintEvent)
*/
public void paintControl(PaintEvent event) {
if (fActiveRegion == null)
return;
ISourceViewer viewer= getSourceViewer();
if (viewer == null)
return;
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
int offset= 0;
int length= 0;
if (viewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) viewer;
IRegion widgetRange= extension.modelRange2WidgetRange(new Region(offset, length));
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);
}
private boolean includes(IRegion region, IRegion position) {
return
position.getOffset() >= region.getOffset() &&
position.getOffset() + position.getLength() <= region.getOffset() + region.getLength();
}
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 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;
}
}
/**
* This action dispatches into two behaviours: If there is no current text
* hover, the javadoc is displayed using information presenter. If there is
* a current text hover, it is converted into a information presenter in
* order to make it sticky.
*/
class InformationDispatchAction extends TextEditorAction {
/** The wrapped text operation action. */
private final TextOperationAction fTextOperationAction;
/**
* Creates a dispatch action.
*/
public InformationDispatchAction(ResourceBundle resourceBundle, String prefix, final TextOperationAction textOperationAction) {
super(resourceBundle, prefix, JavaEditor.this);
if (textOperationAction == null)
throw new IllegalArgumentException();
fTextOperationAction= textOperationAction;
}
/*
* @see org.eclipse.jface.action.IAction#run()
*/
public void run() {
/**
* Information provider used to present the information.
*
* @since 3.0
*/
class InformationProvider implements IInformationProvider, IInformationProviderExtension2 {
private IRegion fHoverRegion;
private String fHoverInfo;
private IInformationControlCreator fControlCreator;
InformationProvider(IRegion hoverRegion, String hoverInfo, IInformationControlCreator controlCreator) {
fHoverRegion= hoverRegion;
fHoverInfo= hoverInfo;
fControlCreator= controlCreator;
}
/*
* @see org.eclipse.jface.text.information.IInformationProvider#getSubject(org.eclipse.jface.text.ITextViewer, int)
*/
public IRegion getSubject(ITextViewer textViewer, int invocationOffset) {
return fHoverRegion;
}
/*
* @see org.eclipse.jface.text.information.IInformationProvider#getInformation(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion)
*/
public String getInformation(ITextViewer textViewer, IRegion subject) {
return fHoverInfo;
}
/*
* @see org.eclipse.jface.text.information.IInformationProviderExtension2#getInformationPresenterControlCreator()
* @since 3.0
*/
public IInformationControlCreator getInformationPresenterControlCreator() {
return fControlCreator;
}
}
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null) {
fTextOperationAction.run();
return;
}
if (sourceViewer instanceof ITextViewerExtension4) {
ITextViewerExtension4 extension4= (ITextViewerExtension4) sourceViewer;
extension4.moveFocusToWidgetToken();
}
if (! (sourceViewer instanceof ITextViewerExtension2)) {
fTextOperationAction.run();
return;
}
ITextViewerExtension2 textViewerExtension2= (ITextViewerExtension2) sourceViewer;
// does a text hover exist?
ITextHover textHover= textViewerExtension2.getCurrentTextHover();
if (textHover == null) {
fTextOperationAction.run();
return;
}
Point hoverEventLocation= textViewerExtension2.getHoverEventLocation();
int offset= computeOffsetAtLocation(sourceViewer, hoverEventLocation.x, hoverEventLocation.y);
if (offset == -1) {
fTextOperationAction.run();
return;
}
try {
// get the text hover content
String contentType= TextUtilities.getContentType(sourceViewer.getDocument(), IJavaPartitions.JAVA_PARTITIONING, offset);
IRegion hoverRegion= textHover.getHoverRegion(sourceViewer, offset);
if (hoverRegion == null)
return;
String hoverInfo= textHover.getHoverInfo(sourceViewer, hoverRegion);
IInformationControlCreator controlCreator= null;
if (textHover instanceof IInformationProviderExtension2)
controlCreator= ((IInformationProviderExtension2)textHover).getInformationPresenterControlCreator();
IInformationProvider informationProvider= new InformationProvider(hoverRegion, hoverInfo, controlCreator);
fInformationPresenter.setOffset(offset);
fInformationPresenter.setInformationProvider(informationProvider, contentType);
fInformationPresenter.showInformation();
} catch (BadLocationException e) {
}
}
// modified version from TextViewer
private int computeOffsetAtLocation(ITextViewer textViewer, int x, int y) {
StyledText styledText= textViewer.getTextWidget();
IDocument document= textViewer.getDocument();
if (document == null)
return -1;
try {
int widgetLocation= styledText.getOffsetAtLocation(new Point(x, y));
if (textViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) textViewer;
return extension.widgetOffset2ModelOffset(widgetLocation);
} else {
IRegion visibleRegion= textViewer.getVisibleRegion();
return widgetLocation + visibleRegion.getOffset();
}
} catch (IllegalArgumentException e) {
return -1;
}
}
}
static protected class AnnotationAccess implements IAnnotationAccess {
/*
* @see org.eclipse.jface.text.source.IAnnotationAccess#getType(org.eclipse.jface.text.source.Annotation)
*/
public Object getType(Annotation annotation) {
if (annotation instanceof IJavaAnnotation) {
IJavaAnnotation javaAnnotation= (IJavaAnnotation) annotation;
if (javaAnnotation.isRelevant())
return javaAnnotation.getAnnotationType();
}
return null;
}
/*
* @see org.eclipse.jface.text.source.IAnnotationAccess#isMultiLine(org.eclipse.jface.text.source.Annotation)
*/
public boolean isMultiLine(Annotation annotation) {
return true;
}
/*
* @see org.eclipse.jface.text.source.IAnnotationAccess#isTemporary(org.eclipse.jface.text.source.Annotation)
*/
public boolean isTemporary(Annotation annotation) {
if (annotation instanceof IJavaAnnotation) {
IJavaAnnotation javaAnnotation= (IJavaAnnotation) annotation;
if (javaAnnotation.isRelevant())
return javaAnnotation.isTemporary();
}
return false;
}
}
private class PropertyChangeListener implements org.eclipse.core.runtime.Preferences.IPropertyChangeListener {
/*
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
handlePreferencePropertyChanged(event);
}
}
/** Preference key for the link color */
protected final static String LINK_COLOR= PreferenceConstants.EDITOR_LINK_COLOR;
/** Preference key for matching brackets */
protected final static String MATCHING_BRACKETS= PreferenceConstants.EDITOR_MATCHING_BRACKETS;
/** Preference key for matching brackets color */
protected final static String MATCHING_BRACKETS_COLOR= PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR;
/** Preference key for compiler task tags */
private final static String COMPILER_TASK_TAGS= JavaCore.COMPILER_TASK_TAGS;
/** Preference key for browser like links */
private final static String BROWSER_LIKE_LINKS= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS;
/** Preference key for key modifier of browser like links */
private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER;
/**
* Preference key for key modifier mask of browser like links.
* The value is only used if the value of <code>EDITOR_BROWSER_LIKE_LINKS</code>
* cannot be resolved to valid SWT modifier bits.
*
* @since 2.1.1
*/
private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK;
protected final static char[] BRACKETS= { '{', '}', '(', ')', '[', ']' };
/** The outline page */
protected JavaOutlinePage fOutlinePage;
/** Outliner context menu Id */
protected String fOutlinerContextMenuId;
/**
* The editor selection changed listener.
*
* @since 3.0
*/
private EditorSelectionChangedListener fEditorSelectionChangedListener;
/** The selection changed listener */
protected AbstractSelectionChangedListener fOutlineSelectionChangedListener= new OutlineSelectionChangedListener();
/** The editor's bracket matcher */
protected JavaPairMatcher fBracketMatcher= new JavaPairMatcher(BRACKETS);
/** The mouse listener */
private MouseClickListener fMouseListener;
/** The information presenter. */
private InformationPresenter fInformationPresenter;
/** History for structure select action */
private SelectionHistory fSelectionHistory;
/** The preference property change listener for java core. */
private org.eclipse.core.runtime.Preferences.IPropertyChangeListener fPropertyChangeListener= new PropertyChangeListener();
protected CompositeActionGroup fActionGroups;
private CompositeActionGroup fContextMenuGroup;
/**
* Returns the most narrow java element including the given offset.
*
* @param offset the offset inside of the requested element
* @return the most narrow java element
*/
abstract protected IJavaElement getElementAt(int offset);
/**
* Returns the java element of this editor's input corresponding to the given IJavaElement
*/
abstract protected IJavaElement getCorrespondingElement(IJavaElement element);
/**
* Sets the input of the editor's outline page.
*/
abstract protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input);
/**
* Default constructor.
*/
public JavaEditor() {
super();
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
setSourceViewerConfiguration(new JavaSourceViewerConfiguration(textTools, this, IJavaPartitions.JAVA_PARTITIONING));
setRangeIndicator(new DefaultRangeIndicator());
setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore());
setKeyBindingScopes(new String[] { "org.eclipse.jdt.ui.javaEditorScope" }); //$NON-NLS-1$
}
/*
* @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
*/
protected final ISourceViewer createSourceViewer(Composite parent, IVerticalRuler verticalRuler, int styles) {
ISourceViewer viewer= createJavaSourceViewer(parent, verticalRuler, getOverviewRuler(), isPrefOverviewRulerVisible(), styles);
StyledText text= viewer.getTextWidget();
text.addBidiSegmentListener(new BidiSegmentListener() {
public void lineGetSegments(BidiSegmentEvent event) {
event.segments= getBidiLineSegments(event.lineOffset, event.lineText);
}
});
JavaUIHelp.setHelp(this, text, IJavaHelpContextIds.JAVA_EDITOR);
// ensure source viewer decoration support has been created and configured
getSourceViewerDecorationSupport(viewer);
return viewer;
}
/*
* @see org.eclipse.ui.texteditor.ExtendedTextEditor#createAnnotationAccess()
*/
protected IAnnotationAccess createAnnotationAccess() {
return new AnnotationAccess();
}
public final ISourceViewer getViewer() {
return getSourceViewer();
}
/*
* @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
*/
protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean isOverviewRulerVisible, int styles) {
return new JavaSourceViewer(parent, verticalRuler, getOverviewRuler(), isPrefOverviewRulerVisible(), styles);
}
/*
* @see AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent)
*/
protected boolean affectsTextPresentation(PropertyChangeEvent event) {
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
return textTools.affectsBehavior(event);
}
/**
* Sets the outliner's context menu ID.
*/
protected void setOutlinerContextMenuId(String menuId) {
fOutlinerContextMenuId= menuId;
}
/**
* Returns the standard action group of this editor.
*/
protected ActionGroup getActionGroup() {
return fActionGroups;
}
/*
* @see AbstractTextEditor#editorContextMenuAboutToShow
*/
public void editorContextMenuAboutToShow(IMenuManager menu) {
super.editorContextMenuAboutToShow(menu);
menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, new Separator(IContextMenuConstants.GROUP_OPEN));
menu.insertAfter(IContextMenuConstants.GROUP_OPEN, new GroupMarker(IContextMenuConstants.GROUP_SHOW));
ActionContext context= new ActionContext(getSelectionProvider().getSelection());
fContextMenuGroup.setContext(context);
fContextMenuGroup.fillContextMenu(menu);
fContextMenuGroup.setContext(null);
}
/**
* Creates the outline page used with this editor.
*/
protected JavaOutlinePage createOutlinePage() {
JavaOutlinePage page= new JavaOutlinePage(fOutlinerContextMenuId, this);
fOutlineSelectionChangedListener.install(page);
setOutlinePageInput(page, getEditorInput());
return page;
}
/**
* Informs the editor that its outliner has been closed.
*/
public void outlinePageClosed() {
if (fOutlinePage != null) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage= null;
resetHighlightRange();
}
}
/**
* Synchronizes the outliner selection with the given element
* position in the editor.
*
* @param element the java element to select
*/
protected void synchronizeOutlinePage(ISourceReference element) {
synchronizeOutlinePage(element, true);
}
/**
* Synchronizes the outliner selection with the given element
* position in the editor.
*
* @param element the java element to select
* @param checkIfOutlinePageActive <code>true</code> if check for active outline page needs to be done
*/
protected void synchronizeOutlinePage(ISourceReference element, boolean checkIfOutlinePageActive) {
if (fOutlinePage != null && element != null && !(checkIfOutlinePageActive && isJavaOutlinePageActive())) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage.select(element);
fOutlineSelectionChangedListener.install(fOutlinePage);
}
}
/**
* Synchronizes the outliner selection with the actual cursor
* position in the editor.
*/
public void synchronizeOutlinePageSelection() {
synchronizeOutlinePage(computeHighlightRangeSourceReference());
}
/*
* Get the desktop's StatusLineManager
*/
protected IStatusLineManager getStatusLineManager() {
IEditorActionBarContributor contributor= getEditorSite().getActionBarContributor();
if (contributor instanceof EditorActionBarContributor) {
return ((EditorActionBarContributor) contributor).getActionBars().getStatusLineManager();
}
return null;
}
/*
* @see AbstractTextEditor#getAdapter(Class)
*/
public Object getAdapter(Class required) {
if (IContentOutlinePage.class.equals(required)) {
if (fOutlinePage == null)
fOutlinePage= createOutlinePage();
return fOutlinePage;
}
if (required == IShowInTargetList.class) {
return new IShowInTargetList() {
public String[] getShowInTargetIds() {
return new String[] { JavaUI.ID_PACKAGES, IPageLayout.ID_OUTLINE, IPageLayout.ID_RES_NAV };
}
};
}
return super.getAdapter(required);
}
protected void setSelection(ISourceReference reference, boolean moveCursor) {
ISelection selection= getSelectionProvider().getSelection();
if (selection instanceof TextSelection) {
TextSelection textSelection= (TextSelection) selection;
if (textSelection.getOffset() != 0 || textSelection.getLength() != 0)
markInNavigationHistory();
}
if (reference != null) {
StyledText textWidget= null;
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer != null)
textWidget= sourceViewer.getTextWidget();
if (textWidget == null)
return;
try {
ISourceRange range= reference.getSourceRange();
if (range == null)
return;
int offset= range.getOffset();
int length= range.getLength();
if (offset < 0 || length < 0)
return;
setHighlightRange(offset, length, moveCursor);
if (!moveCursor)
return;
offset= -1;
length= -1;
if (reference instanceof IMember) {
range= ((IMember) reference).getNameRange();
if (range != null) {
offset= range.getOffset();
length= range.getLength();
}
} else if (reference instanceof IImportDeclaration) {
String name= ((IImportDeclaration) reference).getElementName();
if (name != null && name.length() > 0) {
String content= reference.getSource();
if (content != null) {
offset= range.getOffset() + content.indexOf(name);
length= name.length();
}
}
} else if (reference instanceof IPackageDeclaration) {
String name= ((IPackageDeclaration) reference).getElementName();
if (name != null && name.length() > 0) {
String content= reference.getSource();
if (content != null) {
offset= range.getOffset() + content.indexOf(name);
length= name.length();
}
}
}
if (offset > -1 && length > 0) {
try {
textWidget.setRedraw(false);
sourceViewer.revealRange(offset, length);
sourceViewer.setSelectedRange(offset, length);
} finally {
textWidget.setRedraw(true);
}
markInNavigationHistory();
}
} catch (JavaModelException x) {
} catch (IllegalArgumentException x) {
}
} else if (moveCursor) {
resetHighlightRange();
markInNavigationHistory();
}
}
public void setSelection(IJavaElement element) {
if (element == null || element instanceof ICompilationUnit || element instanceof IClassFile) {
/*
* If the element is an ICompilationUnit this unit is either the input
* of this editor or not being displayed. In both cases, nothing should
* happened. (http://dev.eclipse.org/bugs/show_bug.cgi?id=5128)
*/
return;
}
IJavaElement corresponding= getCorrespondingElement(element);
if (corresponding instanceof ISourceReference) {
ISourceReference reference= (ISourceReference) corresponding;
// set hightlight range
setSelection(reference, true);
// set outliner selection
if (fOutlinePage != null) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage.select(reference);
fOutlineSelectionChangedListener.install(fOutlinePage);
}
}
}
protected void doSelectionChanged(SelectionChangedEvent event) {
ISourceReference reference= null;
ISelection selection= event.getSelection();
Iterator iter= ((IStructuredSelection) selection).iterator();
while (iter.hasNext()) {
Object o= iter.next();
if (o instanceof ISourceReference) {
reference= (ISourceReference) o;
break;
}
}
if (!isActivePart() && JavaPlugin.getActivePage() != null)
JavaPlugin.getActivePage().bringToTop(this);
setSelection(reference, !isActivePart());
}
/*
* @see AbstractTextEditor#adjustHighlightRange(int, int)
*/
protected void adjustHighlightRange(int offset, int length) {
try {
IJavaElement element= getElementAt(offset);
while (element instanceof ISourceReference) {
ISourceRange range= ((ISourceReference) element).getSourceRange();
if (offset < range.getOffset() + range.getLength() && range.getOffset() < offset + length) {
setHighlightRange(range.getOffset(), range.getLength(), true);
if (fOutlinePage != null) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage.select((ISourceReference) element);
fOutlineSelectionChangedListener.install(fOutlinePage);
}
return;
}
element= element.getParent();
}
} catch (JavaModelException x) {
JavaPlugin.log(x.getStatus());
}
resetHighlightRange();
}
protected boolean isActivePart() {
IWorkbenchPart part= getActivePart();
return part != null && part.equals(this);
}
private boolean isJavaOutlinePageActive() {
IWorkbenchPart part= getActivePart();
return part instanceof ContentOutline && ((ContentOutline)part).getCurrentPage() == fOutlinePage;
}
private IWorkbenchPart getActivePart() {
IWorkbenchWindow window= getSite().getWorkbenchWindow();
IPartService service= window.getPartService();
IWorkbenchPart part= service.getActivePart();
return part;
}
/*
* @see AbstractTextEditor#doSetInput
*/
protected void doSetInput(IEditorInput input) throws CoreException {
super.doSetInput(input);
setOutlinePageInput(fOutlinePage, input);
}
/*
* @see IWorkbenchPart#dispose()
*/
public void dispose() {
if (isBrowserLikeLinks())
disableBrowserLikeLinks();
if (fPropertyChangeListener != null) {
Preferences preferences= JavaCore.getPlugin().getPluginPreferences();
preferences.removePropertyChangeListener(fPropertyChangeListener);
fPropertyChangeListener= null;
}
if (fBracketMatcher != null) {
fBracketMatcher.dispose();
fBracketMatcher= null;
}
if (fSelectionHistory != null) {
fSelectionHistory.dispose();
fSelectionHistory= null;
}
if (fEditorSelectionChangedListener != null) {
fEditorSelectionChangedListener.uninstall(getSelectionProvider());
fEditorSelectionChangedListener= null;
}
super.dispose();
}
protected void createActions() {
super.createActions();
ResourceAction resAction= new AddTaskAction(JavaEditorMessages.getResourceBundle(), "AddTask.", this); //$NON-NLS-1$
resAction.setHelpContextId(IAbstractTextEditorHelpContextIds.ADD_TASK_ACTION);
resAction.setActionDefinitionId(ITextEditorActionDefinitionIds.ADD_TASK);
setAction(ITextEditorActionConstants.ADD_TASK, resAction);
ActionGroup oeg, ovg, jsg, sg;
fActionGroups= new CompositeActionGroup(new ActionGroup[] {
oeg= new OpenEditorActionGroup(this),
sg= new ShowActionGroup(this),
ovg= new OpenViewActionGroup(this),
jsg= new JavaSearchActionGroup(this)
});
fContextMenuGroup= new CompositeActionGroup(new ActionGroup[] {oeg, ovg, sg, jsg});
resAction= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc.", this, ISourceViewer.INFORMATION, true); //$NON-NLS-1$
resAction= new InformationDispatchAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc.", (TextOperationAction) resAction); //$NON-NLS-1$
resAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_JAVADOC);
setAction("ShowJavaDoc", resAction); //$NON-NLS-1$
WorkbenchHelp.setHelp(resAction, IJavaHelpContextIds.SHOW_JAVADOC_ACTION);
Action action= new GotoMatchingBracketAction(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_MATCHING_BRACKET);
setAction(GotoMatchingBracketAction.GOTO_MATCHING_BRACKET, action);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"ShowOutline.", this, JavaSourceViewer.SHOW_OUTLINE, true); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_OUTLINE);
setAction(IJavaEditorActionDefinitionIds.SHOW_OUTLINE, action);
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.SHOW_OUTLINE_ACTION);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"OpenStructure.", this, JavaSourceViewer.OPEN_STRUCTURE, true); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_STRUCTURE);
setAction(IJavaEditorActionDefinitionIds.OPEN_STRUCTURE, action);
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.OPEN_STRUCTURE_ACTION);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"OpenHierarchy.", this, JavaSourceViewer.SHOW_HIERARCHY, true); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_HIERARCHY);
setAction(IJavaEditorActionDefinitionIds.OPEN_HIERARCHY, action);
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.OPEN_HIERARCHY_ACTION);
fSelectionHistory= new SelectionHistory(this);
action= new StructureSelectEnclosingAction(this, fSelectionHistory);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_ENCLOSING);
setAction(StructureSelectionAction.ENCLOSING, action);
action= new StructureSelectNextAction(this, fSelectionHistory);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_NEXT);
setAction(StructureSelectionAction.NEXT, action);
action= new StructureSelectPreviousAction(this, fSelectionHistory);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_PREVIOUS);
setAction(StructureSelectionAction.PREVIOUS, action);
StructureSelectHistoryAction historyAction= new StructureSelectHistoryAction(this, fSelectionHistory);
historyAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_LAST);
setAction(StructureSelectionAction.HISTORY, historyAction);
fSelectionHistory.setHistoryAction(historyAction);
action= GoToNextPreviousMemberAction.newGoToNextMemberAction(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_NEXT_MEMBER);
setAction(GoToNextPreviousMemberAction.NEXT_MEMBER, action);
action= GoToNextPreviousMemberAction.newGoToPreviousMemberAction(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_PREVIOUS_MEMBER);
setAction(GoToNextPreviousMemberAction.PREVIOUS_MEMBER, action);
}
public void updatedTitleImage(Image image) {
setTitleImage(image);
}
/*
* @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
*/
protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
try {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
String property= event.getProperty();
if (PreferenceConstants.EDITOR_TAB_WIDTH.equals(property)) {
Object value= event.getNewValue();
if (value instanceof Integer) {
sourceViewer.getTextWidget().setTabs(((Integer) value).intValue());
} else if (value instanceof String) {
sourceViewer.getTextWidget().setTabs(Integer.parseInt((String) value));
}
return;
}
if (isJavaEditorHoverProperty(property))
updateHoverBehavior();
if (BROWSER_LIKE_LINKS.equals(property)) {
if (isBrowserLikeLinks())
enableBrowserLikeLinks();
else
disableBrowserLikeLinks();
return;
}
if (PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE.equals(property)) {
if ((event.getNewValue() instanceof Boolean) && ((Boolean)event.getNewValue()).booleanValue()) {
fEditorSelectionChangedListener= new EditorSelectionChangedListener();
fEditorSelectionChangedListener.install(getSelectionProvider());
fEditorSelectionChangedListener.selectionChanged();
} else {
fEditorSelectionChangedListener.uninstall(getSelectionProvider());
fEditorSelectionChangedListener= null;
}
return;
}
if (PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE.equals(property)) {
if (event.getNewValue() instanceof Boolean) {
Boolean disable= (Boolean) event.getNewValue();
configureInsertMode(OVERWRITE, !disable.booleanValue());
}
}
} finally {
super.handlePreferenceStoreChanged(event);
}
}
private boolean isJavaEditorHoverProperty(String property) {
return PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS.equals(property);
}
/**
* Return whether the browser like links should be enabled
* according to the preference store settings.
* @return <code>true</code> if the browser like links should be enabled
*/
private boolean isBrowserLikeLinks() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(BROWSER_LIKE_LINKS);
}
/**
* Enables browser like links.
*/
private void enableBrowserLikeLinks() {
if (fMouseListener == null) {
fMouseListener= new MouseClickListener();
fMouseListener.install();
}
}
/**
* Disables browser like links.
*/
private void disableBrowserLikeLinks() {
if (fMouseListener != null) {
fMouseListener.uninstall();
fMouseListener= null;
}
}
/**
* Handles a property change event describing a change
* of the java core's preferences and updates the preference
* related editor properties.
*
* @param event the property change event
*/
protected void handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
if (COMPILER_TASK_TAGS.equals(event.getProperty())) {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer != null && affectsTextPresentation(new PropertyChangeEvent(event.getSource(), event.getProperty(), event.getOldValue(), event.getNewValue())))
sourceViewer.invalidateTextPresentation();
}
}
/**
* Returns a segmentation of the line of the given viewer's input document appropriate for
* bidi rendering. The default implementation returns only the string literals of a java code
* line as segments.
*
* @param viewer the text viewer
* @param lineOffset the offset of the line
* @return the line's bidi segmentation
* @throws BadLocationException in case lineOffset is not valid in document
*/
public static int[] getBidiLineSegments(ITextViewer viewer, int lineOffset) throws BadLocationException {
IDocument document= viewer.getDocument();
if (document == null)
return null;
IRegion line= document.getLineInformationOfOffset(lineOffset);
ITypedRegion[] linePartitioning= TextUtilities.computePartitioning(document, IJavaPartitions.JAVA_PARTITIONING, lineOffset, line.getLength());
List segmentation= new ArrayList();
for (int i= 0; i < linePartitioning.length; i++) {
if (IJavaPartitions.JAVA_STRING.equals(linePartitioning[i].getType()))
segmentation.add(linePartitioning[i]);
}
if (segmentation.size() == 0)
return null;
int size= segmentation.size();
int[] segments= new int[size * 2 + 1];
int j= 0;
for (int i= 0; i < size; i++) {
ITypedRegion segment= (ITypedRegion) segmentation.get(i);
if (i == 0)
segments[j++]= 0;
int offset= segment.getOffset() - lineOffset;
if (offset > segments[j - 1])
segments[j++]= offset;
if (offset + segment.getLength() >= line.getLength())
break;
segments[j++]= offset + segment.getLength();
}
if (j < segments.length) {
int[] result= new int[j];
System.arraycopy(segments, 0, result, 0, j);
segments= result;
}
return segments;
}
/**
* Returns a segmentation of the given line appropriate for bidi rendering. The default
* implementation returns only the string literals of a java code line as segments.
*
* @param lineOffset the offset of the line
* @param line the content of the line
* @return the line's bidi segmentation
*/
protected int[] getBidiLineSegments(int widgetLineOffset, String line) {
if (line != null && line.length() > 0) {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer != null) {
int lineOffset;
if (sourceViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) sourceViewer;
lineOffset= extension.widgetOffset2ModelOffset(widgetLineOffset);
} else {
IRegion visible= sourceViewer.getVisibleRegion();
lineOffset= visible.getOffset() + widgetLineOffset;
}
try {
return getBidiLineSegments(sourceViewer, lineOffset);
} catch (BadLocationException x) {
// don't segment line in this case
}
}
}
return null;
}
/*
* 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);
}
}
/*
* @see org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput()
*/
public Object getViewPartInput() {
return getEditorInput().getAdapter(IJavaElement.class);
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#doSetSelection(ISelection)
*/
protected void doSetSelection(ISelection selection) {
super.doSetSelection(selection);
synchronizeOutlinePageSelection();
}
/*
* @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite)
*/
public void createPartControl(Composite parent) {
super.createPartControl(parent);
getSourceViewerDecorationSupport(getViewer()).install(getPreferenceStore());
Preferences preferences= JavaCore.getPlugin().getPluginPreferences();
preferences.addPropertyChangeListener(fPropertyChangeListener);
IInformationControlCreator informationControlCreator= new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell shell) {
boolean cutDown= false;
int style= cutDown ? SWT.NONE : (SWT.V_SCROLL | SWT.H_SCROLL);
return new DefaultInformationControl(shell, SWT.RESIZE, style, new HTMLTextPresenter(cutDown));
}
};
fInformationPresenter= new InformationPresenter(informationControlCreator);
fInformationPresenter.setSizeConstraints(60, 10, true, true);
fInformationPresenter.install(getSourceViewer());
if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE)) {
fEditorSelectionChangedListener= new EditorSelectionChangedListener();
fEditorSelectionChangedListener.install(getSelectionProvider());
}
if (isBrowserLikeLinks())
enableBrowserLikeLinks();
if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE))
configureInsertMode(OVERWRITE, false);
}
protected void configureSourceViewerDecorationSupport(SourceViewerDecorationSupport support) {
support.setCharacterPairMatcher(fBracketMatcher);
support.setMatchingCharacterPainterPreferenceKeys(MATCHING_BRACKETS, MATCHING_BRACKETS_COLOR);
super.configureSourceViewerDecorationSupport(support);
}
/**
* Jumps to the next enabled annotation according to the given direction.
* An annotation type is enabled if it is configured to be in the
* Next/Previous tool bar drop down menu and if it is checked.
*/
public void gotoAnnotation(boolean forward) {
ISelectionProvider provider= getSelectionProvider();
ITextSelection s= (ITextSelection) provider.getSelection();
Position annotationPosition= new Position(0, 0);
IJavaAnnotation nextAnnotation= getNextAnnotation(s.getOffset(), s.getLength(),forward, annotationPosition);
setStatusLineErrorMessage(null);
if (nextAnnotation != null) {
IMarker marker= null;
if (nextAnnotation instanceof MarkerAnnotation)
marker= ((MarkerAnnotation) nextAnnotation).getMarker();
else {
Iterator e= nextAnnotation.getOverlaidIterator();
if (e != null) {
while (e.hasNext()) {
Object o= e.next();
if (o instanceof MarkerAnnotation) {
marker= ((MarkerAnnotation) o).getMarker();
break;
}
}
}
}
if (marker != null) {
IWorkbenchPage page= getSite().getPage();
IViewPart view= view= page.findView("org.eclipse.ui.views.TaskList"); //$NON-NLS-1$
if (view instanceof TaskList) {
StructuredSelection ss= new StructuredSelection(marker);
((TaskList) view).setSelection(ss, true);
}
}
selectAndReveal(annotationPosition.getOffset(), annotationPosition.getLength());
if (nextAnnotation.isProblem())
setStatusLineErrorMessage(nextAnnotation.getMessage());
}
}
/**
* Jumps to the matching bracket.
*/
public void gotoMatchingBracket() {
ISourceViewer sourceViewer= getSourceViewer();
IDocument document= sourceViewer.getDocument();
if (document == null)
return;
IRegion selection= getSignedSelection(sourceViewer);
int selectionLength= Math.abs(selection.getLength());
if (selectionLength > 1) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.invalidSelection")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
// #26314
int sourceCaretOffset= selection.getOffset() + selection.getLength();
if (isSurroundedByBrackets(document, sourceCaretOffset))
sourceCaretOffset -= selection.getLength();
IRegion region= fBracketMatcher.match(document, sourceCaretOffset);
if (region == null) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.noMatchingBracket")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
int offset= region.getOffset();
int length= region.getLength();
if (length < 1)
return;
int anchor= fBracketMatcher.getAnchor();
// http://dev.eclipse.org/bugs/show_bug.cgi?id=34195
int targetOffset= (JavaPairMatcher.RIGHT == anchor) ? offset + 1: offset + length;
boolean visible= false;
if (sourceViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) sourceViewer;
visible= (extension.modelOffset2WidgetOffset(targetOffset) > -1);
} else {
IRegion visibleRegion= sourceViewer.getVisibleRegion();
// http://dev.eclipse.org/bugs/show_bug.cgi?id=34195
visible= (targetOffset >= visibleRegion.getOffset() && targetOffset <= visibleRegion.getOffset() + visibleRegion.getLength());
}
if (!visible) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.bracketOutsideSelectedElement")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
if (selection.getLength() < 0)
targetOffset -= selection.getLength();
sourceViewer.setSelectedRange(targetOffset, selection.getLength());
sourceViewer.revealRange(targetOffset, selection.getLength());
}
/**
* Ses the given message as error message to this editor's status line.
* @param msg message to be set
*/
protected void setStatusLineErrorMessage(String msg) {
IEditorStatusLine statusLine= (IEditorStatusLine) getAdapter(IEditorStatusLine.class);
if (statusLine != null)
statusLine.setMessage(true, msg, null);
}
private static IRegion getSignedSelection(ITextViewer viewer) {
StyledText text= viewer.getTextWidget();
int caretOffset= text.getCaretOffset();
Point selection= text.getSelection();
// caret left
int offset, length;
if (caretOffset == selection.x) {
offset= selection.y;
length= selection.x - selection.y;
// caret right
} else {
offset= selection.x;
length= selection.y - selection.x;
}
return new Region(offset, length);
}
private static boolean isBracket(char character) {
for (int i= 0; i != BRACKETS.length; ++i)
if (character == BRACKETS[i])
return true;
return false;
}
private static boolean isSurroundedByBrackets(IDocument document, int offset) {
if (offset == 0 || offset == document.getLength())
return false;
try {
return
isBracket(document.getChar(offset - 1)) &&
isBracket(document.getChar(offset));
} catch (BadLocationException e) {
return false;
}
}
private IJavaAnnotation getNextAnnotation(int offset, int length, boolean forward, Position annotationPosition) {
IJavaAnnotation nextAnnotation= null;
Position nextAnnotationPosition= null;
IJavaAnnotation containingAnnotation= null;
Position containingAnnotationPosition= null;
boolean currentAnnotation= false;
IDocument document= getDocumentProvider().getDocument(getEditorInput());
int endOfDocument= document.getLength();
int distance= 0;
IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput());
Iterator e= new JavaAnnotationIterator(model, true);
while (e.hasNext()) {
IJavaAnnotation a= (IJavaAnnotation) e.next();
Preferences workbenchTextEditorPrefStore= Platform.getPlugin("org.eclipse.ui.workbench.texteditor").getPluginPreferences(); //$NON-NLS-1$
Iterator iter= getAnnotationPreferences().getAnnotationPreferences().iterator();
boolean isNavigationTarget= false;
while (iter.hasNext()) {
AnnotationPreference annotationPref= (AnnotationPreference)iter.next();
if (annotationPref.getAnnotationType().equals(a.getAnnotationType())) {
String key;
if (forward)
key= annotationPref.getIsGoToNextNavigationTargetKey();
else
key= annotationPref.getIsGoToPreviousNavigationTargetKey();
if (key != null)
isNavigationTarget= workbenchTextEditorPrefStore.getBoolean(key);
break;
}
annotationPref= null;
}
if (a.hasOverlay() || !isNavigationTarget)
continue;
Position p= model.getPosition((Annotation) a);
if (!(p.includes(offset) || (p.getLength() == 0 && offset == p.offset))) {
int currentDistance= 0;
if (forward) {
currentDistance= p.getOffset() - offset;
if (currentDistance < 0)
currentDistance= endOfDocument - offset + p.getOffset();
} else {
currentDistance= offset - p.getOffset();
if (currentDistance < 0)
currentDistance= offset + endOfDocument - p.getOffset();
}
if (nextAnnotation == null || currentDistance < distance) {
distance= currentDistance;
nextAnnotation= a;
nextAnnotationPosition= p;
}
} else {
if (containingAnnotationPosition == null || containingAnnotationPosition.length > p.length) {
containingAnnotation= a;
containingAnnotationPosition= p;
if (length == p.length)
currentAnnotation= true;
}
}
}
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;
}
/**
* Computes and returns the source reference that includes the caret and
* serves as provider for the outline page selection and the editor range
* indication.
*
* @return the computed source reference
* @since 3.0
*/
protected ISourceReference computeHighlightRangeSourceReference() {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return null;
StyledText styledText= sourceViewer.getTextWidget();
if (styledText == null)
return null;
int caret= 0;
if (sourceViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3)sourceViewer;
caret= extension.widgetOffset2ModelOffset(styledText.getCaretOffset());
} else {
int offset= sourceViewer.getVisibleRegion().getOffset();
caret= offset + styledText.getCaretOffset();
}
IJavaElement element= getElementAt(caret, false);
if ( !(element instanceof ISourceReference))
return null;
if (element.getElementType() == IJavaElement.IMPORT_DECLARATION) {
IImportDeclaration declaration= (IImportDeclaration) element;
IImportContainer container= (IImportContainer) declaration.getParent();
ISourceRange srcRange= null;
try {
srcRange= container.getSourceRange();
} catch (JavaModelException e) {
}
if (srcRange != null && srcRange.getOffset() == caret)
return container;
}
return (ISourceReference) element;
}
/**
* Returns the most narrow java element including the given offset.
*
* @param offset the offset inside of the requested element
* @param reconcile <code>true</code> if editor input should be reconciled in advance
* @return the most narrow java element
* @since 3.0
*/
protected IJavaElement getElementAt(int offset, boolean reconcile) {
return getElementAt(offset);
}
/*
* @see org.eclipse.ui.texteditor.ExtendedTextEditor#createChangeHover()
*/
protected LineChangeHover createChangeHover() {
return new JavaChangeHover(IJavaPartitions.JAVA_PARTITIONING);
}
protected boolean isPrefQuickDiffAlwaysOn() {
return false; // never show change ruler for the non-editable java editor. Overridden in subclasses like CompilationUnitEditor
}
}
|
12,192 |
Bug 12192 Rename method complains if the new name is overloaded [refactoring]
|
Build: 20020321 Description: I have two methods that are supposed to have the same name: public Word computeSuccessorTo(Word word) public Word computerSuccessorTo(ILetterNode letterNode) I noticed that I had misspelt the name of the second method (there shouldn't be an r after compute) so I tried to use the rename function in the refactor menu. It complained that my class already had a method named computeSuccessorTo with the same number of parameters. The complaint is correct, but it isn't a problem since the arguments are of different types. If I ignore the errors and press Finish, the results are correct.
|
resolved fixed
|
9a53957
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-20T10:41:39Z | 2002-03-24T06:06:40Z |
org.eclipse.jdt.ui/core
| |
12,192 |
Bug 12192 Rename method complains if the new name is overloaded [refactoring]
|
Build: 20020321 Description: I have two methods that are supposed to have the same name: public Word computeSuccessorTo(Word word) public Word computerSuccessorTo(ILetterNode letterNode) I noticed that I had misspelt the name of the second method (there shouldn't be an r after compute) so I tried to use the rename function in the refactor menu. It complained that my class already had a method named computeSuccessorTo with the same number of parameters. The complaint is correct, but it isn't a problem since the arguments are of different types. If I ignore the errors and press Finish, the results are correct.
|
resolved fixed
|
9a53957
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-20T10:41:39Z | 2002-03-24T06:06:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/rename/RenameMethodProcessor.java
| |
12,192 |
Bug 12192 Rename method complains if the new name is overloaded [refactoring]
|
Build: 20020321 Description: I have two methods that are supposed to have the same name: public Word computeSuccessorTo(Word word) public Word computerSuccessorTo(ILetterNode letterNode) I noticed that I had misspelt the name of the second method (there shouldn't be an r after compute) so I tried to use the rename function in the refactor menu. It complained that my class already had a method named computeSuccessorTo with the same number of parameters. The complaint is correct, but it isn't a problem since the arguments are of different types. If I ignore the errors and press Finish, the results are correct.
|
resolved fixed
|
9a53957
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-20T10:41:39Z | 2002-03-24T06:06:40Z |
org.eclipse.jdt.ui/core
| |
12,192 |
Bug 12192 Rename method complains if the new name is overloaded [refactoring]
|
Build: 20020321 Description: I have two methods that are supposed to have the same name: public Word computeSuccessorTo(Word word) public Word computerSuccessorTo(ILetterNode letterNode) I noticed that I had misspelt the name of the second method (there shouldn't be an r after compute) so I tried to use the rename function in the refactor menu. It complained that my class already had a method named computeSuccessorTo with the same number of parameters. The complaint is correct, but it isn't a problem since the arguments are of different types. If I ignore the errors and press Finish, the results are correct.
|
resolved fixed
|
9a53957
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-20T10:41:39Z | 2002-03-24T06:06:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/rename/RenameNonVirtualMethodProcessor.java
| |
12,192 |
Bug 12192 Rename method complains if the new name is overloaded [refactoring]
|
Build: 20020321 Description: I have two methods that are supposed to have the same name: public Word computeSuccessorTo(Word word) public Word computerSuccessorTo(ILetterNode letterNode) I noticed that I had misspelt the name of the second method (there shouldn't be an r after compute) so I tried to use the rename function in the refactor menu. It complained that my class already had a method named computeSuccessorTo with the same number of parameters. The complaint is correct, but it isn't a problem since the arguments are of different types. If I ignore the errors and press Finish, the results are correct.
|
resolved fixed
|
9a53957
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-20T10:41:39Z | 2002-03-24T06:06:40Z |
org.eclipse.jdt.ui/core
| |
12,192 |
Bug 12192 Rename method complains if the new name is overloaded [refactoring]
|
Build: 20020321 Description: I have two methods that are supposed to have the same name: public Word computeSuccessorTo(Word word) public Word computerSuccessorTo(ILetterNode letterNode) I noticed that I had misspelt the name of the second method (there shouldn't be an r after compute) so I tried to use the rename function in the refactor menu. It complained that my class already had a method named computeSuccessorTo with the same number of parameters. The complaint is correct, but it isn't a problem since the arguments are of different types. If I ignore the errors and press Finish, the results are correct.
|
resolved fixed
|
9a53957
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-20T10:41:39Z | 2002-03-24T06:06:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/rename/RenameVirtualMethodProcessor.java
| |
40,047 |
Bug 40047 Inline Method should work for empty selection [refactoring]
|
I20030710 Inline method should work for the case below as well. public class Test { private int foo() { return 0; } private int bar() { return f<CURSOR>oo(); } }
|
resolved fixed
|
b7d0508
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-20T13:58:37Z | 2003-07-14T19:13:20Z |
org.eclipse.jdt.ui/core
| |
40,047 |
Bug 40047 Inline Method should work for empty selection [refactoring]
|
I20030710 Inline method should work for the case below as well. public class Test { private int foo() { return 0; } private int bar() { return f<CURSOR>oo(); } }
|
resolved fixed
|
b7d0508
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-20T13:58:37Z | 2003-07-14T19:13:20Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/InlineMethodRefactoring.java
| |
41,727 |
Bug 41727 paste after cut pastes too many empty lines
|
20030819 cut and paste a method - 1 line is inserted above
|
resolved fixed
|
d4a8b8e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-20T14:20:13Z | 2003-08-20T09:00:00Z |
org.eclipse.jdt.ui/ui
| |
41,727 |
Bug 41727 paste after cut pastes too many empty lines
|
20030819 cut and paste a method - 1 line is inserted above
|
resolved fixed
|
d4a8b8e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-20T14:20:13Z | 2003-08-20T09:00:00Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/reorg/TypedSource.java
| |
40,360 |
Bug 40360 inline method into another class forgets to qualify field access [refactoring]
|
class A { void f(B b) { System.out.println(b.getName()); } } class B { String fName; public String getName() { return fName; } } - In A::f, try to inline method b.getName() - The result should be System.out.println(b.fName), but it is only System.out.println(fName) .
|
resolved fixed
|
75efb60
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-20T15:46:51Z | 2003-07-17T13:53:20Z |
org.eclipse.jdt.ui.tests.refactoring/resources/InlineMethodWorkspace/TestCases/cast_in/TestNoCast.java
| |
40,360 |
Bug 40360 inline method into another class forgets to qualify field access [refactoring]
|
class A { void f(B b) { System.out.println(b.getName()); } } class B { String fName; public String getName() { return fName; } } - In A::f, try to inline method b.getName() - The result should be System.out.println(b.fName), but it is only System.out.println(fName) .
|
resolved fixed
|
75efb60
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-20T15:46:51Z | 2003-07-17T13:53:20Z |
org.eclipse.jdt.ui.tests.refactoring/resources/InlineMethodWorkspace/TestCases/cast_out/TestNoCast.java
| |
40,360 |
Bug 40360 inline method into another class forgets to qualify field access [refactoring]
|
class A { void f(B b) { System.out.println(b.getName()); } } class B { String fName; public String getName() { return fName; } } - In A::f, try to inline method b.getName() - The result should be System.out.println(b.fName), but it is only System.out.println(fName) .
|
resolved fixed
|
75efb60
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-20T15:46:51Z | 2003-07-17T13:53:20Z |
org.eclipse.jdt.ui.tests.refactoring/test
| |
40,360 |
Bug 40360 inline method into another class forgets to qualify field access [refactoring]
|
class A { void f(B b) { System.out.println(b.getName()); } } class B { String fName; public String getName() { return fName; } } - In A::f, try to inline method b.getName() - The result should be System.out.println(b.fName), but it is only System.out.println(fName) .
|
resolved fixed
|
75efb60
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-20T15:46:51Z | 2003-07-17T13:53:20Z |
cases/org/eclipse/jdt/ui/tests/refactoring/InlineMethodTests.java
| |
40,360 |
Bug 40360 inline method into another class forgets to qualify field access [refactoring]
|
class A { void f(B b) { System.out.println(b.getName()); } } class B { String fName; public String getName() { return fName; } } - In A::f, try to inline method b.getName() - The result should be System.out.println(b.fName), but it is only System.out.println(fName) .
|
resolved fixed
|
75efb60
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-20T15:46:51Z | 2003-07-17T13:53:20Z |
org.eclipse.jdt.ui/core
| |
40,360 |
Bug 40360 inline method into another class forgets to qualify field access [refactoring]
|
class A { void f(B b) { System.out.println(b.getName()); } } class B { String fName; public String getName() { return fName; } } - In A::f, try to inline method b.getName() - The result should be System.out.println(b.fName), but it is only System.out.println(fName) .
|
resolved fixed
|
75efb60
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-20T15:46:51Z | 2003-07-17T13:53:20Z |
extension/org/eclipse/jdt/internal/corext/dom/ASTNodes.java
| |
40,360 |
Bug 40360 inline method into another class forgets to qualify field access [refactoring]
|
class A { void f(B b) { System.out.println(b.getName()); } } class B { String fName; public String getName() { return fName; } } - In A::f, try to inline method b.getName() - The result should be System.out.println(b.fName), but it is only System.out.println(fName) .
|
resolved fixed
|
75efb60
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-20T15:46:51Z | 2003-07-17T13:53:20Z |
org.eclipse.jdt.ui/core
| |
40,360 |
Bug 40360 inline method into another class forgets to qualify field access [refactoring]
|
class A { void f(B b) { System.out.println(b.getName()); } } class B { String fName; public String getName() { return fName; } } - In A::f, try to inline method b.getName() - The result should be System.out.println(b.fName), but it is only System.out.println(fName) .
|
resolved fixed
|
75efb60
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-20T15:46:51Z | 2003-07-17T13:53:20Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/CallInliner.java
| |
40,360 |
Bug 40360 inline method into another class forgets to qualify field access [refactoring]
|
class A { void f(B b) { System.out.println(b.getName()); } } class B { String fName; public String getName() { return fName; } } - In A::f, try to inline method b.getName() - The result should be System.out.println(b.fName), but it is only System.out.println(fName) .
|
resolved fixed
|
75efb60
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-20T15:46:51Z | 2003-07-17T13:53:20Z |
org.eclipse.jdt.ui/core
| |
40,360 |
Bug 40360 inline method into another class forgets to qualify field access [refactoring]
|
class A { void f(B b) { System.out.println(b.getName()); } } class B { String fName; public String getName() { return fName; } } - In A::f, try to inline method b.getName() - The result should be System.out.println(b.fName), but it is only System.out.println(fName) .
|
resolved fixed
|
75efb60
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-20T15:46:51Z | 2003-07-17T13:53:20Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/InlineMethodRefactoring.java
| |
40,360 |
Bug 40360 inline method into another class forgets to qualify field access [refactoring]
|
class A { void f(B b) { System.out.println(b.getName()); } } class B { String fName; public String getName() { return fName; } } - In A::f, try to inline method b.getName() - The result should be System.out.println(b.fName), but it is only System.out.println(fName) .
|
resolved fixed
|
75efb60
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-20T15:46:51Z | 2003-07-17T13:53:20Z |
org.eclipse.jdt.ui/core
| |
40,360 |
Bug 40360 inline method into another class forgets to qualify field access [refactoring]
|
class A { void f(B b) { System.out.println(b.getName()); } } class B { String fName; public String getName() { return fName; } } - In A::f, try to inline method b.getName() - The result should be System.out.println(b.fName), but it is only System.out.println(fName) .
|
resolved fixed
|
75efb60
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-20T15:46:51Z | 2003-07-17T13:53:20Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/SourceProvider.java
| |
40,360 |
Bug 40360 inline method into another class forgets to qualify field access [refactoring]
|
class A { void f(B b) { System.out.println(b.getName()); } } class B { String fName; public String getName() { return fName; } } - In A::f, try to inline method b.getName() - The result should be System.out.println(b.fName), but it is only System.out.println(fName) .
|
resolved fixed
|
75efb60
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-20T15:46:51Z | 2003-07-17T13:53:20Z |
org.eclipse.jdt.ui/core
| |
40,360 |
Bug 40360 inline method into another class forgets to qualify field access [refactoring]
|
class A { void f(B b) { System.out.println(b.getName()); } } class B { String fName; public String getName() { return fName; } } - In A::f, try to inline method b.getName() - The result should be System.out.println(b.fName), but it is only System.out.println(fName) .
|
resolved fixed
|
75efb60
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-20T15:46:51Z | 2003-07-17T13:53:20Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/TargetProvider.java
| |
41,148 |
Bug 41148 Extract Method doesn't check for null type [refactoring]
|
public class Q { void f() { String str= (null); str= (true ? null : null); } } - Select "(null)" - Choose menu Refactor > Extract Method... -> Exception below is thrown. The problem here is that ExtractMethodAnalyzer::checkExpression doesn't look inside parenthesized expressions and excludes only plain NullLiterals. The patch I will attach solves the problem for all expressions of null type. It makes the special handling of NullLiterals in ExtractMethodAnalyzer::checkExpression superfluous. java.lang.IllegalArgumentException at org.eclipse.jdt.core.dom.SimpleName.setIdentifier(SimpleName.java:125) at org.eclipse.jdt.core.dom.AST.newSimpleName(AST.java:1129) at org.eclipse.jdt.core.dom.AST.newName(AST.java:1177) at org.eclipse.jdt.internal.corext.dom.ASTNodeFactory.newType(ASTNodeFactory.java:92) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractMethodAnalyzer.initReturnType(ExtractMethodAnalyzer.java:213) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractMethodAnalyzer.checkActivation(ExtractMethodAnalyzer.java:181) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractMethodRefactoring.checkActivation(ExtractMethodRefactoring.java:177) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run(CheckConditionsOperation.java:63) at org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext$BusyRunnable.internalRun(BusyIndicatorRunnableContext.java:113) at org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext$BusyRunnable.run(BusyIndicatorRunnableContext.java:80) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:84) at org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext.run(BusyIndicatorRunnableContext.java:126) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.checkActivation(RefactoringStarter.java:66) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate(RefactoringStarter.java:46) at org.eclipse.jdt.ui.actions.ExtractMethodAction.run(ExtractMethodAction.java:70) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun(SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run(SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.ui.actions.RetargetAction.runWithEvent(RetargetAction.java:187) at org.eclipse.ui.internal.WWinPluginAction.runWithEvent(WWinPluginAction.java:212) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:542) at org.eclipse.jface.action.ActionContributionItem.access$4(ActionContributionItem.java:496) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent(ActionContributionItem.java:468) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:848) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2188) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1878) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1680) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1663) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:291) at org.eclipse.core.launcher.Main.run(Main.java:747) at org.eclipse.core.launcher.Main.main(Main.java:583)
|
resolved fixed
|
099b903
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-20T17:33:56Z | 2003-08-05T16:13:20Z |
org.eclipse.jdt.ui/core
| |
41,148 |
Bug 41148 Extract Method doesn't check for null type [refactoring]
|
public class Q { void f() { String str= (null); str= (true ? null : null); } } - Select "(null)" - Choose menu Refactor > Extract Method... -> Exception below is thrown. The problem here is that ExtractMethodAnalyzer::checkExpression doesn't look inside parenthesized expressions and excludes only plain NullLiterals. The patch I will attach solves the problem for all expressions of null type. It makes the special handling of NullLiterals in ExtractMethodAnalyzer::checkExpression superfluous. java.lang.IllegalArgumentException at org.eclipse.jdt.core.dom.SimpleName.setIdentifier(SimpleName.java:125) at org.eclipse.jdt.core.dom.AST.newSimpleName(AST.java:1129) at org.eclipse.jdt.core.dom.AST.newName(AST.java:1177) at org.eclipse.jdt.internal.corext.dom.ASTNodeFactory.newType(ASTNodeFactory.java:92) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractMethodAnalyzer.initReturnType(ExtractMethodAnalyzer.java:213) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractMethodAnalyzer.checkActivation(ExtractMethodAnalyzer.java:181) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractMethodRefactoring.checkActivation(ExtractMethodRefactoring.java:177) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run(CheckConditionsOperation.java:63) at org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext$BusyRunnable.internalRun(BusyIndicatorRunnableContext.java:113) at org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext$BusyRunnable.run(BusyIndicatorRunnableContext.java:80) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:84) at org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext.run(BusyIndicatorRunnableContext.java:126) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.checkActivation(RefactoringStarter.java:66) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate(RefactoringStarter.java:46) at org.eclipse.jdt.ui.actions.ExtractMethodAction.run(ExtractMethodAction.java:70) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun(SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run(SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.ui.actions.RetargetAction.runWithEvent(RetargetAction.java:187) at org.eclipse.ui.internal.WWinPluginAction.runWithEvent(WWinPluginAction.java:212) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:542) at org.eclipse.jface.action.ActionContributionItem.access$4(ActionContributionItem.java:496) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent(ActionContributionItem.java:468) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:848) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2188) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1878) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1680) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1663) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:291) at org.eclipse.core.launcher.Main.run(Main.java:747) at org.eclipse.core.launcher.Main.main(Main.java:583)
|
resolved fixed
|
099b903
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-20T17:33:56Z | 2003-08-05T16:13:20Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/ExtractMethodAnalyzer.java
| |
40,355 |
Bug 40355 quick fix: list of completions not wanted when there's only 1 [quick fix]
|
20030716 int f(){ return 1; } change '1' to 'true' use quick fix to change method type content assist window appears with 1 proposal (i don't need it then) moreover, after pressing esc i'm not taken to where i was before, i'm stuck in the method declaration
|
resolved fixed
|
f76bc15
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-21T10:49:57Z | 2003-07-17T13:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/CUCorrectionProposal.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text.correction;
import org.eclipse.compare.contentmergeviewer.ITokenComparator;
import org.eclipse.compare.rangedifferencer.RangeDifference;
import org.eclipse.compare.rangedifferencer.RangeDifferencer;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.swt.graphics.Image;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.internal.corext.refactoring.base.Change;
import org.eclipse.jdt.internal.corext.refactoring.changes.CompilationUnitChange;
import org.eclipse.jdt.internal.corext.textmanipulation.GroupDescription;
import org.eclipse.jdt.internal.corext.textmanipulation.MultiTextEdit;
import org.eclipse.jdt.internal.corext.textmanipulation.TextBuffer;
import org.eclipse.jdt.internal.corext.textmanipulation.TextEdit;
import org.eclipse.jdt.internal.corext.textmanipulation.TextRange;
import org.eclipse.jdt.internal.corext.textmanipulation.TextRegion;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.corext.util.Resources;
import org.eclipse.jdt.internal.corext.util.Strings;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.compare.JavaTokenComparator;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor;
import org.eclipse.jdt.internal.ui.text.link.LinkedPositionManager;
import org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI;
public class CUCorrectionProposal extends ChangeCorrectionProposal {
private ICompilationUnit fCompilationUnit;
private TextEdit fRootEdit;
public CUCorrectionProposal(String name, ICompilationUnit cu, int relevance) {
this(name, cu, relevance, JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE));
}
public CUCorrectionProposal(String name, ICompilationUnit cu, int relevance, Image image) {
super(name, null, relevance, image);
fRootEdit= new MultiTextEdit();
fCompilationUnit= cu;
}
public CUCorrectionProposal(String name, CompilationUnitChange change, int relevance, Image image) {
super(name, change, relevance, image);
fCompilationUnit= change.getCompilationUnit();
}
protected CompilationUnitChange createCompilationUnitChange(String name, ICompilationUnit cu, TextEdit rootEdit) throws CoreException {
CompilationUnitChange change= new CompilationUnitChange(name, cu);
change.setEdit(rootEdit);
change.setSave(false);
setChange(change);
return change;
}
/*
* @see ChangeCorrectionProposal#getChange()
*/
protected Change getChange() throws CoreException {
Change change= super.getChange();
if (change == null) {
return createCompilationUnitChange(getDisplayString(), fCompilationUnit, fRootEdit);
}
return change;
}
protected final void addEdits(CompilationUnitChange change) throws CoreException {
}
protected GroupDescription[] getLinkedRanges() {
return null;
}
protected ICompletionProposal[] getLinkedModeProposals(String name) {
return null;
}
protected GroupDescription getSelectionDescription() {
return null;
}
/*
* @see ICompletionProposal#getAdditionalProposalInfo()
*/
public String getAdditionalProposalInfo() {
StringBuffer buf= new StringBuffer();
try {
CompilationUnitChange change= getCompilationUnitChange();
TextBuffer previewConent= change.getPreviewTextBuffer();
String currentConentString= change.getCurrentContent();
ITokenComparator leftSide= new JavaTokenComparator(previewConent.getContent(), true);
ITokenComparator rightSide= new JavaTokenComparator(currentConentString, true);
RangeDifference[] differences= RangeDifferencer.findRanges(leftSide, rightSide);
for (int i= 0; i < differences.length; i++) {
RangeDifference curr= differences[i];
int start= leftSide.getTokenStart(curr.leftStart());
int end= leftSide.getTokenStart(curr.leftEnd());
if (curr.kind() == RangeDifference.CHANGE && curr.leftLength() > 0) {
buf.append("<b>"); //$NON-NLS-1$
appendContent(previewConent, start, end, buf, false);
buf.append("</b>"); //$NON-NLS-1$
} else if (curr.kind() == RangeDifference.NOCHANGE) {
appendContent(previewConent, start, end, buf, true);
}
}
} catch (CoreException e) {
JavaPlugin.log(e);
}
return buf.toString();
}
private final int surroundLines= 1;
private void appendContent(TextBuffer text, int startOffset, int endOffset, StringBuffer buf, boolean surroundLinesOnly) {
int startLine= text.getLineOfOffset(startOffset);
int endLine= text.getLineOfOffset(endOffset);
boolean dotsAdded= false;
if (surroundLinesOnly && startOffset == 0) { // no surround lines for the top no-change range
startLine= Math.max(endLine - surroundLines, 0);
buf.append("...<br>"); //$NON-NLS-1$
dotsAdded= true;
}
for (int i= startLine; i <= endLine; i++) {
if (surroundLinesOnly) {
if ((i - startLine > surroundLines) && (endLine - i > surroundLines)) {
if (!dotsAdded) {
buf.append("...<br>"); //$NON-NLS-1$
dotsAdded= true;
} else if (endOffset == text.getLength()) {
return; // no surround lines for the bottom no-change range
}
continue;
}
}
TextRegion lineInfo= text.getLineInformation(i);
int start= lineInfo.getOffset();
int end= start + lineInfo.getLength();
int from= Math.max(start, startOffset);
int to= Math.min(end, endOffset);
String content= text.getContent(from, to - from);
if (surroundLinesOnly && (from == start) && Strings.containsOnlyWhitespaces(content)) {
continue; // ignore empty lines exept when range started in the middle of a line
}
buf.append(content);
if (to == end && to != endOffset) { // new line when at the end of the line, and not end of range
buf.append("<br>"); //$NON-NLS-1$
}
}
}
/* (non-Javadoc)
* @see org.eclipse.jface.text.contentassist.ICompletionProposal#apply(org.eclipse.jface.text.IDocument)
*/
public void apply(IDocument document) {
try {
ICompilationUnit unit= JavaModelUtil.toOriginal(getCompilationUnit());
IStatus status= Resources.makeCommittable(unit.getResource(), null);
if (!status.isOK()) {
String label= CorrectionMessages.getString("CUCorrectionProposal.error.title"); //$NON-NLS-1$
String message= CorrectionMessages.getString("CUCorrectionProposal.error.message"); //$NON-NLS-1$
ErrorDialog.openError(JavaPlugin.getActiveWorkbenchShell(), label, message, status);
return;
}
CompilationUnitChange change= getCompilationUnitChange();
GroupDescription selection= getSelectionDescription();
GroupDescription[] linked= getLinkedRanges();
IEditorPart part= null;
if (selection != null || linked != null) {
change.setKeepExecutedTextEdits(true);
part= EditorUtility.isOpenInEditor(unit);
if (part == null) {
part= EditorUtility.openInEditor(unit, true);
}
IWorkbenchPage page= JavaPlugin.getActivePage();
if (page != null && part != null) {
page.bringToTop(part);
}
if (part != null) {
part.setFocus();
}
}
super.apply(document);
if (part == null) {
return;
}
if (linked != null && part instanceof JavaEditor) {
// enter linked mode
ITextViewer viewer= ((JavaEditor) part).getViewer();
enterLinkedMode(change, viewer, linked, selection);
} else if (selection != null && part instanceof ITextEditor) {
// select a result
TextRange range= change.getNewTextRange(selection.getTextEdits());
((ITextEditor) part).selectAndReveal(range.getOffset(), range.getLength());
}
} catch (CoreException e) {
JavaPlugin.log(e);
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
}
private void enterLinkedMode(CompilationUnitChange change, ITextViewer viewer, GroupDescription[] linked, GroupDescription selection) throws BadLocationException {
LinkedPositionManager manager= new LinkedPositionManager(viewer.getDocument());
LinkedPositionUI editor= new LinkedPositionUI(viewer, manager);
for (int i= 0; i < linked.length; i++) {
GroupDescription curr= linked[i];
String name= curr.getName(); // name used as key for link mode proposals & as kind for linked mode
TextRange range= change.getNewTextRange(curr.getTextEdits());
if (range != null && range.isValid() && name != null) {
ICompletionProposal[] linkedModeProposals= getLinkedModeProposals(name);
if (linkedModeProposals != null) {
manager.addPosition(range.getOffset(), range.getLength(), name, linkedModeProposals);
} else {
manager.addPosition(range.getOffset(), range.getLength(), name);
}
if (i == 0) {
editor.setInitialOffset(range.getOffset());
}
}
}
if (selection != null) {
TextRange range= change.getNewTextRange(selection.getTextEdits());
if (range != null && range.isValid()) {
editor.setFinalCaretOffset(range.getOffset() + range.getLength());
}
} else {
int cursorPosition= viewer.getSelectedRange().x;
if (cursorPosition != 0) {
editor.setFinalCaretOffset(cursorPosition);
}
}
editor.enter();
IRegion region= editor.getSelectedRegion();
viewer.setSelectedRange(region.getOffset(), region.getLength());
viewer.revealRange(region.getOffset(), region.getLength());
}
/**
* Gets the compilationUnitChange.
* @return Returns a CompilationUnitChange
*/
public CompilationUnitChange getCompilationUnitChange() throws CoreException {
return (CompilationUnitChange) getChange();
}
/**
* @return Returns the root text edit
*/
public TextEdit getRootTextEdit() {
return fRootEdit;
}
/**
* Returns the compilationUnit.
* @return ICompilationUnit
*/
public ICompilationUnit getCompilationUnit() {
return fCompilationUnit;
}
}
|
41,357 |
Bug 41357 NPE: Opening Browser after Javadoc export [javadoc]
|
OSX version 10.2.6 Eclipse: 200308060800 !ENTRY org.eclipse.debug.core 4 2 Aug 09, 2003 12:11:03.917 !MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.debug.core". !STACK 0 java.lang.NullPointerException at org.eclipse.jdt.internal.ui.actions.OpenBrowserUtil.open(OpenBrowserUtil.java:30) at org.eclipse.jdt.internal.ui.javadocexport.JavadocWizard.spawnInBrowser(JavadocWizard.java:460) at org.eclipse.jdt.internal.ui.javadocexport.JavadocWizard.access$3(JavadocWizard.java:455) at org.eclipse.jdt.internal.ui.javadocexport.JavadocWizard$JavadocDebugEventListener.handleDebugEvents( JavadocWizard.java:474) at org.eclipse.debug.core.DebugPlugin$EventNotifier.run(DebugPlugin.java:858) at org.eclipse.core.internal.runtime.InternalPlatform.run(InternalPlatform.java:1015) at org.eclipse.core.runtime.Platform.run(Platform.java:420) at org.eclipse.debug.core.DebugPlugin$EventNotifier.dispatch(DebugPlugin.java:890) at org.eclipse.debug.core.DebugPlugin.fireDebugEventSet(DebugPlugin.java:306) at org.eclipse.debug.internal.core.RuntimeProcess.fireEvent(RuntimeProcess.java:238) at org.eclipse.debug.internal.core.RuntimeProcess.fireTerminateEvent(RuntimeProcess.java:246) at org.eclipse.debug.internal.core.RuntimeProcess.terminated(RuntimeProcess.java:215) at org.eclipse.debug.internal.core.ProcessMonitorJob.run(ProcessMonitorJob.java:51) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:58) !ENTRY org.eclipse.debug.core 4 120 Aug 09, 2003 12:11:03.923 !MESSAGE An exception occurred while dispatching debug events. !STACK 0 java.lang.NullPointerException at org.eclipse.jdt.internal.ui.actions.OpenBrowserUtil.open(OpenBrowserUtil.java:30) at org.eclipse.jdt.internal.ui.javadocexport.JavadocWizard.spawnInBrowser(JavadocWizard.java:460) at org.eclipse.jdt.internal.ui.javadocexport.JavadocWizard.access$3(JavadocWizard.java:455) at org.eclipse.jdt.internal.ui.javadocexport.JavadocWizard$JavadocDebugEventListener.handleDebugEvents( JavadocWizard.java:474) at org.eclipse.debug.core.DebugPlugin$EventNotifier.run(DebugPlugin.java:858) at org.eclipse.core.internal.runtime.InternalPlatform.run(InternalPlatform.java:1015) at org.eclipse.core.runtime.Platform.run(Platform.java:420) at org.eclipse.debug.core.DebugPlugin$EventNotifier.dispatch(DebugPlugin.java:890) at org.eclipse.debug.core.DebugPlugin.fireDebugEventSet(DebugPlugin.java:306) at org.eclipse.debug.internal.core.RuntimeProcess.fireEvent(RuntimeProcess.java:238) at org.eclipse.debug.internal.core.RuntimeProcess.fireTerminateEvent(RuntimeProcess.java:246) at org.eclipse.debug.internal.core.RuntimeProcess.terminated(RuntimeProcess.java:215) at org.eclipse.debug.internal.core.ProcessMonitorJob.run(ProcessMonitorJob.java:51) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:58)
|
resolved fixed
|
17ab212
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-21T12:59:09Z | 2003-08-09T11:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/actions/OpenBrowserUtil.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.actions;
import java.net.URL;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.help.IHelp;
public class OpenBrowserUtil {
public static void open(final URL url, final Shell shell, final String dialogTitle) {
IHelp help= WorkbenchHelp.getHelpSupport();
if (help != null) {
BusyIndicator.showWhile(shell.getDisplay(), new Runnable() {
public void run() {
WorkbenchHelp.getHelpSupport().displayHelpResource(url.toExternalForm());
}
});
} else {
showMessage(shell, dialogTitle, ActionMessages.getString("OpenBrowserUtil.help_not_available"), false); //$NON-NLS-1$
}
}
private static void showMessage(final Shell shell, final String title, final String message, final boolean isError) {
Display.getDefault().asyncExec(new Runnable() {
public void run() {
if (isError) {
MessageDialog.openError(shell, title, message);
} else {
MessageDialog.openInformation(shell, title, message);
}
}
});
}
}
|
41,798 |
Bug 41798 New JUnit Plug-in test requires test suites to extend Test
|
The new JUnit plug-in test seems to require test suites to extend TestSuite. Otherwise an error is reported in the launch config dialog. It is however still possible to launch a test suite by opening it in the editor and choosing Run->Run As->New JUnit Plug-in Test To reproduce, try to run (and configure) the JDT UI AllAllTests testsuite.
|
resolved fixed
|
8543d6c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-21T15:36:07Z | 2003-08-21T12:46:40Z |
org.eclipse.jdt.junit.core/src/org/eclipse/jdt/internal/junit/util/TestSearchEngine.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.junit.util;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.jface.operation.IRunnableContext;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.ISourceReference;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.search.IJavaSearchConstants;
import org.eclipse.jdt.core.search.IJavaSearchResultCollector;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.ISearchPattern;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.internal.junit.ui.JUnitMessages;
import org.eclipse.jdt.internal.junit.ui.JUnitPlugin;
/**
* Custom Search engine for suite() methods
*/
public class TestSearchEngine {
private class JUnitSearchResultCollector implements IJavaSearchResultCollector {
IProgressMonitor fProgressMonitor;
List fList;
Set fFailed= new HashSet();
Set fMatches= new HashSet();
public JUnitSearchResultCollector(List list, IProgressMonitor progressMonitor) {
fProgressMonitor= progressMonitor;
fList= list;
}
public void accept(IResource resource, int start, int end, IJavaElement enclosingElement, int accuracy) throws JavaModelException{
if (!(enclosingElement instanceof IMethod))
return;
IMethod method= (IMethod)enclosingElement;
IType declaringType= method.getDeclaringType();
if (fMatches.contains(declaringType) || fFailed.contains(declaringType))
return;
if (!hasSuiteMethod(declaringType) && !isTestType(declaringType)) {
fFailed.add(declaringType);
return;
}
fMatches.add(declaringType);
}
public IProgressMonitor getProgressMonitor() {
return fProgressMonitor;
}
public void aboutToStart() {
}
public void done() {
fList.addAll(fMatches);
}
}
private List searchMethod(IProgressMonitor pm, final IJavaSearchScope scope) throws JavaModelException {
final List typesFound= new ArrayList(200);
searchMethod(typesFound, scope, pm);
return typesFound;
}
private List searchMethod(final List v, IJavaSearchScope scope, final IProgressMonitor progressMonitor) throws JavaModelException {
IJavaSearchResultCollector collector= new JUnitSearchResultCollector(v, progressMonitor);
ISearchPattern suitePattern= SearchEngine.createSearchPattern("suite() Test", IJavaSearchConstants.METHOD, IJavaSearchConstants.DECLARATIONS, true); //$NON-NLS-1$
ISearchPattern testPattern= SearchEngine.createSearchPattern("test*() void", IJavaSearchConstants.METHOD , IJavaSearchConstants.DECLARATIONS, true); //$NON-NLS-1$
SearchEngine engine= new SearchEngine();
engine.search(ResourcesPlugin.getWorkspace(), SearchEngine.createOrSearchPattern(suitePattern, testPattern), scope, collector);
return v;
}
public static IType[] findTests(IRunnableContext context, final Object[] elements) throws InvocationTargetException, InterruptedException{
final Set result= new HashSet();
if (elements.length > 0) {
IRunnableWithProgress runnable= new IRunnableWithProgress() {
public void run(IProgressMonitor pm) throws InterruptedException {
doFindTests(elements, result, pm);
}
};
context.run(true, true, runnable);
}
return (IType[]) result.toArray(new IType[result.size()]) ;
}
public static void doFindTests(Object[] elements, Set result, IProgressMonitor pm) throws InterruptedException {
int nElements= elements.length;
pm.beginTask(JUnitMessages.getString("TestSearchEngine.message.searching"), nElements); //$NON-NLS-1$
try {
for (int i= 0; i < nElements; i++) {
try {
collectTypes(elements[i], new SubProgressMonitor(pm, 1), result);
} catch (JavaModelException e) {
JUnitPlugin.log(e.getStatus());
}
if (pm.isCanceled()) {
throw new InterruptedException();
}
}
} finally {
pm.done();
}
}
private static void collectTypes(Object element, IProgressMonitor pm, Set result) throws JavaModelException/*, InvocationTargetException*/ {
element= computeScope(element);
while((element instanceof IJavaElement) && !(element instanceof ICompilationUnit) && (element instanceof ISourceReference)) {
if(element instanceof IType) {
if (hasSuiteMethod((IType)element) || isTestType((IType)element)) {
result.add(element);
return;
}
}
element= ((IJavaElement)element).getParent();
}
if (element instanceof ICompilationUnit) {
ICompilationUnit cu= (ICompilationUnit)element;
IType[] types= cu.getAllTypes();
for (int i= 0; i < types.length; i++) {
if (hasSuiteMethod(types[i]) || isTestType(types[i]))
result.add(types[i]);
}
}
else if (element instanceof IJavaElement) {
List found= searchSuiteMethods(pm, (IJavaElement)element);
result.addAll(found);
}
}
private static Object computeScope(Object element) throws JavaModelException {
if (element instanceof IFileEditorInput)
element= ((IFileEditorInput)element).getFile();
if (element instanceof IResource)
element= JavaCore.create((IResource)element);
if (element instanceof IClassFile) {
IClassFile cf= (IClassFile)element;
element= cf.getType();
}
return element;
}
private static List searchSuiteMethods(IProgressMonitor pm, IJavaElement element) throws JavaModelException {
IJavaSearchScope scope= SearchEngine.createJavaSearchScope(new IJavaElement[] { element });
TestSearchEngine searchEngine= new TestSearchEngine();
return searchEngine.searchMethod(pm, scope);
}
private static boolean hasSuiteMethod(IType type) throws JavaModelException {
IMethod method= type.getMethod("suite", new String[0]); //$NON-NLS-1$
if (method == null || !method.exists())
return false;
if (!Flags.isStatic(method.getFlags()) ||
!Flags.isPublic(method.getFlags()) ||
!Flags.isPublic(method.getDeclaringType().getFlags())) {
return false;
}
return true;
}
private static boolean isTestType(IType type) throws JavaModelException {
if (Flags.isAbstract(type.getFlags()))
return false;
if (!Flags.isPublic(type.getFlags()))
return false;
IType[] interfaces= type.newSupertypeHierarchy(null).getAllSuperInterfaces(type);
for (int i= 0; i < interfaces.length; i++)
if(interfaces[i].getFullyQualifiedName().equals(JUnitPlugin.TEST_INTERFACE_NAME))
return true;
return false;
}
public static boolean isTestImplementor(IType type) throws JavaModelException {
ITypeHierarchy typeHier= type.newSupertypeHierarchy(null);
IType[] superInterfaces= typeHier.getAllInterfaces();
for (int i= 0; i < superInterfaces.length; i++) {
if (superInterfaces[i].getFullyQualifiedName().equals(JUnitPlugin.TEST_INTERFACE_NAME))
return true;
}
return false;
}
}
|
41,798 |
Bug 41798 New JUnit Plug-in test requires test suites to extend Test
|
The new JUnit plug-in test seems to require test suites to extend TestSuite. Otherwise an error is reported in the launch config dialog. It is however still possible to launch a test suite by opening it in the editor and choosing Run->Run As->New JUnit Plug-in Test To reproduce, try to run (and configure) the JDT UI AllAllTests testsuite.
|
resolved fixed
|
8543d6c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-21T15:36:07Z | 2003-08-21T12:46:40Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/launcher/JUnitMainTab.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Sebastian Davids: [email protected] bug: 26293, 27889
*******************************************************************************/
package org.eclipse.jdt.internal.junit.launcher;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.ui.dialogs.ElementListSelectionDialog;
import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
import org.eclipse.ui.dialogs.SelectionDialog;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaModel;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.ISourceReference;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.ui.JavaElementSorter;
import org.eclipse.jdt.ui.StandardJavaElementContentProvider;
import org.eclipse.jdt.internal.junit.ui.JUnitMessages;
import org.eclipse.jdt.internal.junit.ui.JUnitPlugin;
import org.eclipse.jdt.internal.junit.util.TestSearchEngine;
import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext;
import org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator;
import org.eclipse.jdt.internal.ui.wizards.TypedViewerFilter;
/**
* This tab appears in the LaunchConfigurationDialog for launch configurations that
* require Java-specific launching information such as a main type and JRE.
*/
public class JUnitMainTab extends JUnitLaunchConfigurationTab {
// Project UI widgets
private Label fProjLabel;
private Text fProjText;
private Button fProjButton;
private Button fKeepRunning;
// Test class UI widgets
private Text fTestText;
private Button fSearchButton;
private final Image fTestIcon= createImage("obj16/test.gif"); //$NON-NLS-1$
private Label fTestMethodLabel;
private Text fContainerText;
private IJavaElement fContainerElement;
private final ILabelProvider fJavaElementLabelProvider= new JavaElementLabelProvider();
private Button fContainerSearchButton;
private Button fTestContainerRadioButton;
private Button fTestRadioButton;
private Label fTestLabel;
/**
* @see ILaunchConfigurationTab#createControl(TabItem)
*/
public void createControl(Composite parent) {
Composite comp = new Composite(parent, SWT.NONE);
setControl(comp);
GridLayout topLayout = new GridLayout();
topLayout.numColumns= 3;
comp.setLayout(topLayout);
Label label = new Label(comp, SWT.NONE);
GridData gd = new GridData();
gd.horizontalSpan = 3;
label.setLayoutData(gd);
createSingleTestSection(comp);
createTestContainerSelectionGroup(comp);
label = new Label(comp, SWT.NONE);
gd = new GridData();
gd.horizontalSpan = 3;
label.setLayoutData(gd);
createKeepAliveGroup(comp);
Dialog.applyDialogFont(comp);
validatePage();
}
protected void createSingleTestSection(Composite comp) {
fTestRadioButton= new Button(comp, SWT.RADIO);
fTestRadioButton.setText(JUnitMessages.getString("JUnitMainTab.label.oneTest")); //$NON-NLS-1$
GridData gd = new GridData();
gd.horizontalSpan = 3;
fTestRadioButton.setLayoutData(gd);
fTestRadioButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if (fTestRadioButton.getSelection())
testModeChanged();
}
});
fProjLabel = new Label(comp, SWT.NONE);
fProjLabel.setText(JUnitMessages.getString("JUnitMainTab.label.project")); //$NON-NLS-1$
gd= new GridData();
gd.horizontalIndent = 25;
fProjLabel.setLayoutData(gd);
fProjText= new Text(comp, SWT.SINGLE | SWT.BORDER);
fProjText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
fProjText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent evt) {
validatePage();
updateLaunchConfigurationDialog();
fSearchButton.setEnabled(fTestRadioButton.getSelection() && fProjText.getText().length() > 0);
}
});
fProjButton = new Button(comp, SWT.PUSH);
fProjButton.setText(JUnitMessages.getString("JUnitMainTab.label.browse")); //$NON-NLS-1$
fProjButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent evt) {
handleProjectButtonSelected();
}
});
setButtonGridData(fProjButton);
fTestLabel = new Label(comp, SWT.NONE);
gd = new GridData();
gd.horizontalIndent = 25;
fTestLabel.setLayoutData(gd);
fTestLabel.setText(JUnitMessages.getString("JUnitMainTab.label.test")); //$NON-NLS-1$
fTestText = new Text(comp, SWT.SINGLE | SWT.BORDER);
fTestText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
fTestText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent evt) {
validatePage();
updateLaunchConfigurationDialog();
}
});
fSearchButton = new Button(comp, SWT.PUSH);
fSearchButton.setEnabled(fProjText.getText().length() > 0);
fSearchButton.setText(JUnitMessages.getString("JUnitMainTab.label.search")); //$NON-NLS-1$
fSearchButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent evt) {
handleSearchButtonSelected();
}
});
setButtonGridData(fSearchButton);
new Label(comp, SWT.NONE);
fTestMethodLabel= new Label(comp, SWT.NONE);
fTestMethodLabel.setText(""); //$NON-NLS-1$
gd= new GridData();
gd.horizontalSpan = 2;
fTestMethodLabel.setLayoutData(gd);
}
protected void createTestContainerSelectionGroup(Composite comp) {
fTestContainerRadioButton= new Button(comp, SWT.RADIO);
fTestContainerRadioButton.setText(JUnitMessages.getString("JUnitMainTab.label.containerTest")); //$NON-NLS-1$
GridData gd = new GridData();
gd.horizontalSpan = 3;
fTestContainerRadioButton.setLayoutData(gd);
fTestContainerRadioButton.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
if (fTestContainerRadioButton.getSelection())
testModeChanged();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
fContainerText = new Text(comp, SWT.SINGLE | SWT.BORDER | SWT.READ_ONLY);
gd = new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalIndent= 25;
gd.horizontalSpan = 2;
fContainerText.setLayoutData(gd);
fContainerText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent evt) {
updateLaunchConfigurationDialog();
}
});
fContainerSearchButton = new Button(comp, SWT.PUSH);
fContainerSearchButton.setText(JUnitMessages.getString("JUnitMainTab.label.search")); //$NON-NLS-1$
fContainerSearchButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent evt) {
handleContainerSearchButtonSelected();
}
});
setButtonGridData(fContainerSearchButton);
}
private void handleContainerSearchButtonSelected() {
IJavaElement javaElement= chooseContainer(fContainerElement);
if (javaElement != null) {
fContainerElement= javaElement;
fContainerText.setText(getPresentationName(javaElement));
validatePage();
updateLaunchConfigurationDialog();
}
}
public void createKeepAliveGroup(Composite comp) {
GridData gd;
fKeepRunning = new Button(comp, SWT.CHECK);
fKeepRunning.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
updateLaunchConfigurationDialog();
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
fKeepRunning.setText(JUnitMessages.getString("JUnitMainTab.label.keeprunning")); //$NON-NLS-1$
gd= new GridData();
gd.horizontalAlignment= GridData.FILL;
gd.horizontalSpan= 2;
fKeepRunning.setLayoutData(gd);
}
protected static Image createImage(String path) {
try {
ImageDescriptor id= ImageDescriptor.createFromURL(JUnitPlugin.makeIconFileURL(path));
return id.createImage();
} catch (MalformedURLException e) {
// fall through
}
return null;
}
/**
* @see ILaunchConfigurationTab#initializeFrom(ILaunchConfiguration)
*/
public void initializeFrom(ILaunchConfiguration config) {
updateProjectFromConfig(config);
String containerHandle= ""; //$NON-NLS-1$
try {
containerHandle = config.getAttribute(JUnitBaseLaunchConfiguration.LAUNCH_CONTAINER_ATTR, ""); //$NON-NLS-1$
} catch (CoreException ce) {
}
if (containerHandle.length() > 0)
updateTestContainerFromConfig(config);
else
updateTestTypeFromConfig(config);
updateKeepRunning(config);
}
private void updateKeepRunning(ILaunchConfiguration config) {
boolean running= false;
try {
running= config.getAttribute(JUnitBaseLaunchConfiguration.ATTR_KEEPRUNNING, false);
} catch (CoreException ce) {
}
fKeepRunning.setSelection(running);
}
protected void updateProjectFromConfig(ILaunchConfiguration config) {
String projectName= ""; //$NON-NLS-1$
try {
projectName = config.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, ""); //$NON-NLS-1$
} catch (CoreException ce) {
}
fProjText.setText(projectName);
}
protected void updateTestTypeFromConfig(ILaunchConfiguration config) {
String testTypeName= ""; //$NON-NLS-1$
String testMethodName= ""; //$NON-NLS-1$
try {
testTypeName = config.getAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, ""); //$NON-NLS-1$
testMethodName = config.getAttribute(JUnitBaseLaunchConfiguration.TESTNAME_ATTR, ""); //$NON-NLS-1$
} catch (CoreException ce) {
}
fTestRadioButton.setSelection(true);
setEnableSingleTestGroup(true);
setEnableContainerTestGroup(false);
fTestContainerRadioButton.setSelection(false);
fTestText.setText(testTypeName);
fContainerText.setText(""); //$NON-NLS-1$
if (!"".equals(testMethodName)) { //$NON-NLS-1$
fTestMethodLabel.setText(JUnitMessages.getString("JUnitMainTab.label.method")+testMethodName); //$NON-NLS-1$
} else {
fTestMethodLabel.setText(""); //$NON-NLS-1$
}
}
protected void updateTestContainerFromConfig(ILaunchConfiguration config) {
String containerHandle= ""; //$NON-NLS-1$
try {
containerHandle = config.getAttribute(JUnitBaseLaunchConfiguration.LAUNCH_CONTAINER_ATTR, ""); //$NON-NLS-1$
if (containerHandle.length() > 0) {
fContainerElement= JavaCore.create(containerHandle);
}
} catch (CoreException ce) {
}
fTestContainerRadioButton.setSelection(true);
setEnableSingleTestGroup(false);
setEnableContainerTestGroup(true);
fTestRadioButton.setSelection(false);
if (fContainerElement != null)
fContainerText.setText(getPresentationName(fContainerElement));
fTestText.setText(""); //$NON-NLS-1$
}
/**
* @see ILaunchConfigurationTab#performApply(ILaunchConfigurationWorkingCopy)
*/
public void performApply(ILaunchConfigurationWorkingCopy config) {
config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, fProjText.getText());
if (fTestContainerRadioButton.getSelection() && fContainerElement != null) {
config.setAttribute(JUnitBaseLaunchConfiguration.LAUNCH_CONTAINER_ATTR, fContainerElement.getHandleIdentifier());
//bug 26293
config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, ""); //$NON-NLS-1$
} else {
config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, fTestText.getText());
//bug 26293
config.setAttribute(JUnitBaseLaunchConfiguration.LAUNCH_CONTAINER_ATTR, ""); //$NON-NLS-1$
}
config.setAttribute(JUnitBaseLaunchConfiguration.ATTR_KEEPRUNNING, fKeepRunning.getSelection());
}
/**
* @see ILaunchConfigurationTab#dispose()
*/
public void dispose() {
super.dispose();
fTestIcon.dispose();
fJavaElementLabelProvider.dispose();
}
/**
* @see AbstractLaunchConfigurationTab#getImage()
*/
public Image getImage() {
return fTestIcon;
}
/**
* Show a dialog that lists all main types
*/
protected void handleSearchButtonSelected() {
Shell shell = getShell();
IJavaProject javaProject = getJavaProject();
SelectionDialog dialog = new TestSelectionDialog(shell, new ProgressMonitorDialog(shell), javaProject);
dialog.setTitle(JUnitMessages.getString("JUnitMainTab.testdialog.title")); //$NON-NLS-1$
dialog.setMessage(JUnitMessages.getString("JUnitMainTab.testdialog.message")); //$NON-NLS-1$
if (dialog.open() == SelectionDialog.CANCEL) {
return;
}
Object[] results = dialog.getResult();
if ((results == null) || (results.length < 1)) {
return;
}
IType type = (IType)results[0];
if (type != null) {
fTestText.setText(type.getFullyQualifiedName());
javaProject = type.getJavaProject();
fProjText.setText(javaProject.getElementName());
}
}
/**
* Show a dialog that lets the user select a project. This in turn provides
* context for the main type, allowing the user to key a main type name, or
* constraining the search for main types to the specified project.
*/
protected void handleProjectButtonSelected() {
IJavaProject project = chooseJavaProject();
if (project == null) {
return;
}
String projectName = project.getElementName();
fProjText.setText(projectName);
}
/**
* Realize a Java Project selection dialog and return the first selected project,
* or null if there was none.
*/
protected IJavaProject chooseJavaProject() {
IJavaProject[] projects;
try {
projects= JavaCore.create(getWorkspaceRoot()).getJavaProjects();
} catch (JavaModelException e) {
JUnitPlugin.log(e.getStatus());
projects= new IJavaProject[0];
}
ILabelProvider labelProvider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT);
ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), labelProvider);
dialog.setTitle(JUnitMessages.getString("JUnitMainTab.projectdialog.title")); //$NON-NLS-1$
dialog.setMessage(JUnitMessages.getString("JUnitMainTab.projectdialog.message")); //$NON-NLS-1$
dialog.setElements(projects);
IJavaProject javaProject = getJavaProject();
if (javaProject != null) {
dialog.setInitialSelections(new Object[] { javaProject });
}
if (dialog.open() == ElementListSelectionDialog.OK) {
return (IJavaProject) dialog.getFirstResult();
}
return null;
}
/**
* Return the IJavaProject corresponding to the project name in the project name
* text field, or null if the text does not match a project name.
*/
protected IJavaProject getJavaProject() {
String projectName = fProjText.getText().trim();
if (projectName.length() < 1) {
return null;
}
return getJavaModel().getJavaProject(projectName);
}
/**
* Convenience method to get the workspace root.
*/
private IWorkspaceRoot getWorkspaceRoot() {
return ResourcesPlugin.getWorkspace().getRoot();
}
/**
* Convenience method to get access to the java model.
*/
private IJavaModel getJavaModel() {
return JavaCore.create(getWorkspaceRoot());
}
/**
* @see ILaunchConfigurationTab#isValid(ILaunchConfiguration)
*/
public boolean isValid(ILaunchConfiguration config) {
return getErrorMessage() == null;
}
private void testModeChanged() {
boolean isSingleTestMode= fTestRadioButton.getSelection();
setEnableSingleTestGroup(isSingleTestMode);
setEnableContainerTestGroup(!isSingleTestMode);
validatePage();
updateLaunchConfigurationDialog();
}
private void validatePage() {
setErrorMessage(null);
setMessage(null);
if (fTestContainerRadioButton.getSelection()) {
if (fContainerElement == null)
setErrorMessage(JUnitMessages.getString("JUnitMainTab.error.noContainer")); //$NON-NLS-1$
return;
}
String projectName = fProjText.getText().trim();
if (projectName.length() == 0) {
setErrorMessage(JUnitMessages.getString("JUnitMainTab.error.projectnotdefined")); //$NON-NLS-1$
return;
}
IProject project = getWorkspaceRoot().getProject(projectName);
if (!project.exists()) {
setErrorMessage(JUnitMessages.getString("JUnitMainTab.error.projectnotexists")); //$NON-NLS-1$
return;
}
try {
if (!project.hasNature(JavaCore.NATURE_ID)) {
setErrorMessage(JUnitMessages.getString("JUnitMainTab.error.notJavaProject")); //$NON-NLS-1$
return;
}
IJavaProject jProject = getJavaProject();
String className = fTestText.getText().trim();
if (className.length() == 0) {
setErrorMessage(JUnitMessages.getString("JUnitMainTab.error.testnotdefined")); //$NON-NLS-1$
return;
}
IType type = jProject.findType(className);
if (type == null)
setErrorMessage(JUnitMessages.getString("JUnitMainTab.error.testnotexists")); //$NON-NLS-1$
else if (!TestSearchEngine.isTestImplementor(type))
setErrorMessage(JUnitMessages.getString("JUnitMainTab.error.invalidTest")); //$NON-NLS-1$
} catch (Exception e) {
}
}
private void setEnableContainerTestGroup(boolean enabled) {
fContainerSearchButton.setEnabled(enabled);
fContainerText.setEnabled(enabled);
}
private void setEnableSingleTestGroup(boolean enabled) {
fProjLabel.setEnabled(enabled);
fProjText.setEnabled(enabled);
fProjButton.setEnabled(enabled);
fTestLabel.setEnabled(enabled);
fTestText.setEnabled(enabled);
fSearchButton.setEnabled(enabled && fProjText.getText().length() > 0);
fTestMethodLabel.setEnabled(enabled);
}
/**
* @see ILaunchConfigurationTab#setDefaults(ILaunchConfigurationWorkingCopy)
*/
public void setDefaults(ILaunchConfigurationWorkingCopy config) {
IJavaElement javaElement = getContext();
if (javaElement != null) {
initializeJavaProject(javaElement, config);
} else {
// We set empty attributes for project & main type so that when one config is
// compared to another, the existence of empty attributes doesn't cause an
// incorrect result (the performApply() method can result in empty values
// for these attributes being set on a config if there is nothing in the
// corresponding text boxes)
config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, ""); //$NON-NLS-1$
config.setAttribute(JUnitBaseLaunchConfiguration.LAUNCH_CONTAINER_ATTR, ""); //$NON-NLS-1$
}
initializeTestAttributes(javaElement, config);
}
private void initializeTestAttributes(IJavaElement javaElement, ILaunchConfigurationWorkingCopy config) {
if (javaElement != null && javaElement.getElementType() < IJavaElement.COMPILATION_UNIT)
initializeTestContainer(javaElement, config);
else
initializeTestType(javaElement, config);
}
private void initializeTestContainer(IJavaElement javaElement, ILaunchConfigurationWorkingCopy config) {
config.setAttribute(JUnitBaseLaunchConfiguration.LAUNCH_CONTAINER_ATTR, javaElement.getHandleIdentifier());
initializeName(config, javaElement.getElementName());
}
private void initializeName(ILaunchConfigurationWorkingCopy config, String name) {
if (name == null) {
name= ""; //$NON-NLS-1$
}
if (name.length() > 0) {
int index = name.lastIndexOf('.');
if (index > 0) {
name = name.substring(index + 1);
}
name= getLaunchConfigurationDialog().generateName(name);
config.rename(name);
}
}
/**
* Set the main type & name attributes on the working copy based on the IJavaElement
*/
protected void initializeTestType(IJavaElement javaElement, ILaunchConfigurationWorkingCopy config) {
String name= ""; //$NON-NLS-1$
try {
// we only do a search for compilation units or class files or
// or source references
if ((javaElement instanceof ICompilationUnit) ||
(javaElement instanceof ISourceReference) ||
(javaElement instanceof IClassFile)) {
IType[] types = TestSearchEngine.findTests(new BusyIndicatorRunnableContext(), new Object[] {javaElement});
if ((types == null) || (types.length < 1)) {
return;
}
// Simply grab the first main type found in the searched element
name = types[0].getFullyQualifiedName();
}
} catch (InterruptedException ie) {
} catch (InvocationTargetException ite) {
}
if (name == null)
name= ""; //$NON-NLS-1$
config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, name);
initializeName(config, name);
}
/**
* @see ILaunchConfigurationTab#getName()
*/
public String getName() {
return JUnitMessages.getString("JUnitMainTab.tab.label"); //$NON-NLS-1$
}
private IJavaElement chooseContainer(IJavaElement initElement) {
Class[] acceptedClasses= new Class[] { IPackageFragmentRoot.class, IJavaProject.class, IPackageFragment.class };
TypedElementSelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, false) {
public boolean isSelectedValid(Object element) {
return true;
}
};
acceptedClasses= new Class[] { IJavaModel.class, IPackageFragmentRoot.class, IJavaProject.class, IPackageFragment.class };
ViewerFilter filter= new TypedViewerFilter(acceptedClasses) {
public boolean select(Viewer viewer, Object parent, Object element) {
return super.select(viewer, parent, element);
}
};
StandardJavaElementContentProvider provider= new StandardJavaElementContentProvider();
ILabelProvider labelProvider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT);
ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), labelProvider, provider);
dialog.setValidator(validator);
dialog.setSorter(new JavaElementSorter());
dialog.setTitle(JUnitMessages.getString("JUnitMainTab.folderdialog.title")); //$NON-NLS-1$
dialog.setMessage(JUnitMessages.getString("JUnitMainTab.folderdialog.message")); //$NON-NLS-1$
dialog.addFilter(filter);
dialog.setInput(JavaCore.create(getWorkspaceRoot()));
dialog.setInitialSelection(initElement);
dialog.setAllowMultiple(false);
if (dialog.open() == ElementTreeSelectionDialog.OK) {
Object element= dialog.getFirstResult();
return (IJavaElement)element;
}
return null;
}
private String getPresentationName(IJavaElement element) {
return fJavaElementLabelProvider.getText(element);
}
}
|
41,798 |
Bug 41798 New JUnit Plug-in test requires test suites to extend Test
|
The new JUnit plug-in test seems to require test suites to extend TestSuite. Otherwise an error is reported in the launch config dialog. It is however still possible to launch a test suite by opening it in the editor and choosing Run->Run As->New JUnit Plug-in Test To reproduce, try to run (and configure) the JDT UI AllAllTests testsuite.
|
resolved fixed
|
8543d6c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-21T15:36:07Z | 2003-08-21T12:46:40Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/util/TestSearchEngine.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.junit.util;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.jface.operation.IRunnableContext;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.ISourceReference;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.search.IJavaSearchConstants;
import org.eclipse.jdt.core.search.IJavaSearchResultCollector;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.ISearchPattern;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.internal.junit.ui.JUnitMessages;
import org.eclipse.jdt.internal.junit.ui.JUnitPlugin;
/**
* Custom Search engine for suite() methods
*/
public class TestSearchEngine {
private class JUnitSearchResultCollector implements IJavaSearchResultCollector {
IProgressMonitor fProgressMonitor;
List fList;
Set fFailed= new HashSet();
Set fMatches= new HashSet();
public JUnitSearchResultCollector(List list, IProgressMonitor progressMonitor) {
fProgressMonitor= progressMonitor;
fList= list;
}
public void accept(IResource resource, int start, int end, IJavaElement enclosingElement, int accuracy) throws JavaModelException{
if (!(enclosingElement instanceof IMethod))
return;
IMethod method= (IMethod)enclosingElement;
IType declaringType= method.getDeclaringType();
if (fMatches.contains(declaringType) || fFailed.contains(declaringType))
return;
if (!hasSuiteMethod(declaringType) && !isTestType(declaringType)) {
fFailed.add(declaringType);
return;
}
fMatches.add(declaringType);
}
public IProgressMonitor getProgressMonitor() {
return fProgressMonitor;
}
public void aboutToStart() {
}
public void done() {
fList.addAll(fMatches);
}
}
private List searchMethod(IProgressMonitor pm, final IJavaSearchScope scope) throws JavaModelException {
final List typesFound= new ArrayList(200);
searchMethod(typesFound, scope, pm);
return typesFound;
}
private List searchMethod(final List v, IJavaSearchScope scope, final IProgressMonitor progressMonitor) throws JavaModelException {
IJavaSearchResultCollector collector= new JUnitSearchResultCollector(v, progressMonitor);
ISearchPattern suitePattern= SearchEngine.createSearchPattern("suite() Test", IJavaSearchConstants.METHOD, IJavaSearchConstants.DECLARATIONS, true); //$NON-NLS-1$
ISearchPattern testPattern= SearchEngine.createSearchPattern("test*() void", IJavaSearchConstants.METHOD , IJavaSearchConstants.DECLARATIONS, true); //$NON-NLS-1$
SearchEngine engine= new SearchEngine();
engine.search(ResourcesPlugin.getWorkspace(), SearchEngine.createOrSearchPattern(suitePattern, testPattern), scope, collector);
return v;
}
public static IType[] findTests(IRunnableContext context, final Object[] elements) throws InvocationTargetException, InterruptedException{
final Set result= new HashSet();
if (elements.length > 0) {
IRunnableWithProgress runnable= new IRunnableWithProgress() {
public void run(IProgressMonitor pm) throws InterruptedException {
doFindTests(elements, result, pm);
}
};
context.run(true, true, runnable);
}
return (IType[]) result.toArray(new IType[result.size()]) ;
}
public static void doFindTests(Object[] elements, Set result, IProgressMonitor pm) throws InterruptedException {
int nElements= elements.length;
pm.beginTask(JUnitMessages.getString("TestSearchEngine.message.searching"), nElements); //$NON-NLS-1$
try {
for (int i= 0; i < nElements; i++) {
try {
collectTypes(elements[i], new SubProgressMonitor(pm, 1), result);
} catch (JavaModelException e) {
JUnitPlugin.log(e.getStatus());
}
if (pm.isCanceled()) {
throw new InterruptedException();
}
}
} finally {
pm.done();
}
}
private static void collectTypes(Object element, IProgressMonitor pm, Set result) throws JavaModelException/*, InvocationTargetException*/ {
element= computeScope(element);
while((element instanceof IJavaElement) && !(element instanceof ICompilationUnit) && (element instanceof ISourceReference)) {
if(element instanceof IType) {
if (hasSuiteMethod((IType)element) || isTestType((IType)element)) {
result.add(element);
return;
}
}
element= ((IJavaElement)element).getParent();
}
if (element instanceof ICompilationUnit) {
ICompilationUnit cu= (ICompilationUnit)element;
IType[] types= cu.getAllTypes();
for (int i= 0; i < types.length; i++) {
if (hasSuiteMethod(types[i]) || isTestType(types[i]))
result.add(types[i]);
}
}
else if (element instanceof IJavaElement) {
List found= searchSuiteMethods(pm, (IJavaElement)element);
result.addAll(found);
}
}
private static Object computeScope(Object element) throws JavaModelException {
if (element instanceof IFileEditorInput)
element= ((IFileEditorInput)element).getFile();
if (element instanceof IResource)
element= JavaCore.create((IResource)element);
if (element instanceof IClassFile) {
IClassFile cf= (IClassFile)element;
element= cf.getType();
}
return element;
}
private static List searchSuiteMethods(IProgressMonitor pm, IJavaElement element) throws JavaModelException {
IJavaSearchScope scope= SearchEngine.createJavaSearchScope(new IJavaElement[] { element });
TestSearchEngine searchEngine= new TestSearchEngine();
return searchEngine.searchMethod(pm, scope);
}
private static boolean hasSuiteMethod(IType type) throws JavaModelException {
IMethod method= type.getMethod("suite", new String[0]); //$NON-NLS-1$
if (method == null || !method.exists())
return false;
if (!Flags.isStatic(method.getFlags()) ||
!Flags.isPublic(method.getFlags()) ||
!Flags.isPublic(method.getDeclaringType().getFlags())) {
return false;
}
return true;
}
private static boolean isTestType(IType type) throws JavaModelException {
if (Flags.isAbstract(type.getFlags()))
return false;
if (!Flags.isPublic(type.getFlags()))
return false;
IType[] interfaces= type.newSupertypeHierarchy(null).getAllSuperInterfaces(type);
for (int i= 0; i < interfaces.length; i++)
if(interfaces[i].getFullyQualifiedName().equals(JUnitPlugin.TEST_INTERFACE_NAME))
return true;
return false;
}
public static boolean isTestImplementor(IType type) throws JavaModelException {
ITypeHierarchy typeHier= type.newSupertypeHierarchy(null);
IType[] superInterfaces= typeHier.getAllInterfaces();
for (int i= 0; i < superInterfaces.length; i++) {
if (superInterfaces[i].getFullyQualifiedName().equals(JUnitPlugin.TEST_INTERFACE_NAME))
return true;
}
return false;
}
}
|
40,767 |
Bug 40767 refactor rename method failure [refactoring]
|
--------------------A.java--------------------------- package a; public class A { private static final A g_instance = new A(); private A() { } public static A getInstance()//<-- refactor rename this method { return g_instance; } } ------------------------------------------------------ ----------------------B.java-------------------------- package a; public class B { I i = new I() { public void method() { A.getInstance(); } }; } interface I { public void method(); } ----------------------------------------------------- when you rename the above marked method you get an error saying that another name shadows access to the renamed element. If you click continue B.java does not get updated.
|
resolved fixed
|
91d40a1
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-21T17:56:02Z | 2003-07-25T13:33:20Z |
org.eclipse.jdt.ui/core
| |
40,767 |
Bug 40767 refactor rename method failure [refactoring]
|
--------------------A.java--------------------------- package a; public class A { private static final A g_instance = new A(); private A() { } public static A getInstance()//<-- refactor rename this method { return g_instance; } } ------------------------------------------------------ ----------------------B.java-------------------------- package a; public class B { I i = new I() { public void method() { A.getInstance(); } }; } interface I { public void method(); } ----------------------------------------------------- when you rename the above marked method you get an error saying that another name shadows access to the renamed element. If you click continue B.java does not get updated.
|
resolved fixed
|
91d40a1
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-21T17:56:02Z | 2003-07-25T13:33:20Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/SearchResultGroup.java
| |
40,785 |
Bug 40785 [plan item] Overview ruler improvements
|
- navigation from ruler to editor - hovering over header area shows number of errors/warning (header annotations in general)
|
resolved fixed
|
0c04535
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-22T09:43:23Z | 2003-07-25T16:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/CompilationUnitDocumentProvider.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.javaeditor;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IMarkerDelta;
import org.eclipse.core.resources.IResource;
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.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.swt.widgets.Display;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.ListenerList;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DefaultLineTracker;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ILineTracker;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.AnnotationModelEvent;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.IAnnotationModelListener;
import org.eclipse.jface.text.source.IAnnotationModelListenerExtension;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.editors.text.FileDocumentProvider;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.texteditor.AbstractMarkerAnnotationModel;
import org.eclipse.ui.texteditor.MarkerAnnotation;
import org.eclipse.ui.texteditor.ResourceMarkerAnnotationModel;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaModelStatusConstants;
import org.eclipse.jdt.core.IProblemRequestor;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jdt.internal.ui.IJavaStatusConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.JavaUIStatus;
import org.eclipse.jdt.internal.ui.text.IJavaPartitions;
import org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionProcessor;
import org.eclipse.jdt.internal.ui.text.java.IProblemRequestorExtension;
public class CompilationUnitDocumentProvider extends FileDocumentProvider implements ICompilationUnitDocumentProvider {
/**
* Here for visibility issues only.
*/
protected class _FileSynchronizer extends FileSynchronizer {
public _FileSynchronizer(IFileEditorInput fileEditorInput) {
super(fileEditorInput);
}
}
/**
* Bundle of all required informations to allow working copy management.
*/
protected class CompilationUnitInfo extends FileInfo {
ICompilationUnit fCopy;
public CompilationUnitInfo(IDocument document, IAnnotationModel model, _FileSynchronizer fileSynchronizer, ICompilationUnit copy) {
super(document, model, fileSynchronizer);
fCopy= copy;
}
public void setModificationStamp(long timeStamp) {
fModificationStamp= timeStamp;
}
}
/**
* Annotation representating an <code>IProblem</code>.
*/
static protected class ProblemAnnotation extends Annotation implements IJavaAnnotation {
private static final String TASK_ANNOTATION_TYPE= "org.eclipse.ui.workbench.texteditor.task"; //$NON-NLS-1$
private static final String ERROR_ANNOTATION_TYPE= "org.eclipse.ui.workbench.texteditor.error"; //$NON-NLS-1$
private static final String WARNING_ANNOTATION_TYPE= "org.eclipse.ui.workbench.texteditor.warning"; //$NON-NLS-1$
private static final String INFO_ANNOTATION_TYPE= "org.eclipse.ui.workbench.texteditor.info"; //$NON-NLS-1$
private static Image fgQuickFixImage;
private static Image fgQuickFixErrorImage;
private static boolean fgQuickFixImagesInitialized= false;
private ICompilationUnit fCompilationUnit;
private List fOverlaids;
private IProblem fProblem;
private Image fImage;
private boolean fQuickFixImagesInitialized= false;
private String fType;
public ProblemAnnotation(IProblem problem, ICompilationUnit cu) {
fProblem= problem;
fCompilationUnit= cu;
setLayer(MarkerAnnotation.PROBLEM_LAYER + 1);
if (IProblem.Task == fProblem.getID())
fType= TASK_ANNOTATION_TYPE;
else if (fProblem.isWarning())
fType= WARNING_ANNOTATION_TYPE;
else if (fProblem.isError())
fType= ERROR_ANNOTATION_TYPE;
else
fType= INFO_ANNOTATION_TYPE;
}
private void initializeImages() {
// http://bugs.eclipse.org/bugs/show_bug.cgi?id=18936
if (!fQuickFixImagesInitialized) {
if (isProblem() && indicateQuixFixableProblems() && JavaCorrectionProcessor.hasCorrections(this)) { // no light bulb for tasks
if (!fgQuickFixImagesInitialized) {
fgQuickFixImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_FIXABLE_PROBLEM);
fgQuickFixErrorImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_FIXABLE_ERROR);
fgQuickFixImagesInitialized= true;
}
if (ERROR_ANNOTATION_TYPE.equals(fType))
fImage= fgQuickFixErrorImage;
else
fImage= fgQuickFixImage;
}
fQuickFixImagesInitialized= true;
}
}
private boolean indicateQuixFixableProblems() {
return PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_CORRECTION_INDICATION);
}
/*
* @see Annotation#paint
*/
public void paint(GC gc, Canvas canvas, Rectangle r) {
initializeImages();
if (fImage != null)
drawImage(fImage, gc, canvas, r, SWT.CENTER, SWT.TOP);
}
/*
* @see IJavaAnnotation#getImage(Display)
*/
public Image getImage(Display display) {
initializeImages();
return fImage;
}
/*
* @see IJavaAnnotation#getMessage()
*/
public String getMessage() {
return fProblem.getMessage();
}
/*
* @see IJavaAnnotation#isTemporary()
*/
public boolean isTemporary() {
return true;
}
/*
* @see IJavaAnnotation#getArguments()
*/
public String[] getArguments() {
return isProblem() ? fProblem.getArguments() : null;
}
/*
* @see IJavaAnnotation#getId()
*/
public int getId() {
return fProblem.getID();
}
/*
* @see IJavaAnnotation#isProblem()
*/
public boolean isProblem() {
return WARNING_ANNOTATION_TYPE.equals(fType) || ERROR_ANNOTATION_TYPE.equals(fType);
}
/*
* @see IJavaAnnotation#isRelevant()
*/
public boolean isRelevant() {
return true;
}
/*
* @see IJavaAnnotation#hasOverlay()
*/
public boolean hasOverlay() {
return false;
}
/*
* @see IJavaAnnotation#addOverlaid(IJavaAnnotation)
*/
public void addOverlaid(IJavaAnnotation annotation) {
if (fOverlaids == null)
fOverlaids= new ArrayList(1);
fOverlaids.add(annotation);
}
/*
* @see IJavaAnnotation#removeOverlaid(IJavaAnnotation)
*/
public void removeOverlaid(IJavaAnnotation annotation) {
if (fOverlaids != null) {
fOverlaids.remove(annotation);
if (fOverlaids.size() == 0)
fOverlaids= null;
}
}
/*
* @see IJavaAnnotation#getOverlaidIterator()
*/
public Iterator getOverlaidIterator() {
if (fOverlaids != null)
return fOverlaids.iterator();
return null;
}
public String getAnnotationType() {
return fType;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.javaeditor.IJavaAnnotation#getCompilationUnit()
*/
public ICompilationUnit getCompilationUnit() {
return fCompilationUnit;
}
}
/**
* Internal structure for mapping positions to some value.
* The reason for this specific structure is that positions can
* change over time. Thus a lookup is based on value and not
* on hash value.
*/
protected static class ReverseMap {
static class Entry {
Position fPosition;
Object fValue;
}
private List fList= new ArrayList(2);
private int fAnchor= 0;
public ReverseMap() {
}
public Object get(Position position) {
Entry entry;
// behind anchor
int length= fList.size();
for (int i= fAnchor; i < length; i++) {
entry= (Entry) fList.get(i);
if (entry.fPosition.equals(position)) {
fAnchor= i;
return entry.fValue;
}
}
// before anchor
for (int i= 0; i < fAnchor; i++) {
entry= (Entry) fList.get(i);
if (entry.fPosition.equals(position)) {
fAnchor= i;
return entry.fValue;
}
}
return null;
}
private int getIndex(Position position) {
Entry entry;
int length= fList.size();
for (int i= 0; i < length; i++) {
entry= (Entry) fList.get(i);
if (entry.fPosition.equals(position))
return i;
}
return -1;
}
public void put(Position position, Object value) {
int index= getIndex(position);
if (index == -1) {
Entry entry= new Entry();
entry.fPosition= position;
entry.fValue= value;
fList.add(entry);
} else {
Entry entry= (Entry) fList.get(index);
entry.fValue= value;
}
}
public void remove(Position position) {
int index= getIndex(position);
if (index > -1)
fList.remove(index);
}
public void clear() {
fList.clear();
}
}
/**
* Annotation model dealing with java marker annotations and temporary problems.
* Also acts as problem requestor for its compilation unit. Initialiy inactive. Must explicitly be
* activated.
*/
protected class CompilationUnitAnnotationModel extends ResourceMarkerAnnotationModel implements IProblemRequestor, IProblemRequestorExtension {
private IFileEditorInput fInput;
private List fCollectedProblems;
private List fGeneratedAnnotations;
private IProgressMonitor fProgressMonitor;
private boolean fIsActive= false;
private ReverseMap fReverseMap= new ReverseMap();
private List fPreviouslyOverlaid= null;
private List fCurrentlyOverlaid= new ArrayList();
private CompilationUnitAnnotationModelEvent fCurrentEvent;
public CompilationUnitAnnotationModel(IFileEditorInput input) {
super(input.getFile());
fInput= input;
fCurrentEvent= new CompilationUnitAnnotationModelEvent(this, getResource());
}
protected MarkerAnnotation createMarkerAnnotation(IMarker marker) {
return new JavaMarkerAnnotation(marker);
}
protected Position createPositionFromProblem(IProblem problem) {
int start= problem.getSourceStart();
if (start < 0)
return null;
int length= problem.getSourceEnd() - problem.getSourceStart() + 1;
if (length < 0)
return null;
return new Position(start, length);
}
protected void update(IMarkerDelta[] markerDeltas) {
super.update(markerDeltas);
if (markerDeltas != null && markerDeltas.length > 0) {
try {
ICompilationUnit workingCopy = getWorkingCopy(fInput);
if (workingCopy != null)
workingCopy.reconcile(true, null);
} catch (JavaModelException ex) {
if (!ex.isDoesNotExist())
handleCoreException(ex, ex.getMessage());
}
}
}
/*
* @see IProblemRequestor#beginReporting()
*/
public void beginReporting() {
ICompilationUnit unit= getWorkingCopy(fInput);
if (unit != null && unit.getJavaProject().isOnClasspath(unit))
fCollectedProblems= new ArrayList();
else
fCollectedProblems= null;
}
/*
* @see IProblemRequestor#acceptProblem(IProblem)
*/
public void acceptProblem(IProblem problem) {
if (isActive())
fCollectedProblems.add(problem);
}
/*
* @see IProblemRequestor#endReporting()
*/
public void endReporting() {
if (!isActive())
return;
if (fProgressMonitor != null && fProgressMonitor.isCanceled())
return;
boolean isCanceled= false;
boolean temporaryProblemsChanged= false;
synchronized (fAnnotations) {
fPreviouslyOverlaid= fCurrentlyOverlaid;
fCurrentlyOverlaid= new ArrayList();
if (fGeneratedAnnotations.size() > 0) {
temporaryProblemsChanged= true;
removeAnnotations(fGeneratedAnnotations, false, true);
fGeneratedAnnotations.clear();
}
if (fCollectedProblems != null && fCollectedProblems.size() > 0) {
ICompilationUnit cu= getWorkingCopy(fInput);
Iterator e= fCollectedProblems.iterator();
while (e.hasNext()) {
IProblem problem= (IProblem) e.next();
if (fProgressMonitor != null && fProgressMonitor.isCanceled()) {
isCanceled= true;
break;
}
Position position= createPositionFromProblem(problem);
if (position != null) {
try {
ProblemAnnotation annotation= new ProblemAnnotation(problem, cu);
addAnnotation(annotation, position, false);
overlayMarkers(position, annotation);
fGeneratedAnnotations.add(annotation);
temporaryProblemsChanged= true;
} catch (BadLocationException x) {
// ignore invalid position
}
}
}
fCollectedProblems.clear();
}
removeMarkerOverlays(isCanceled);
fPreviouslyOverlaid.clear();
fPreviouslyOverlaid= null;
}
if (temporaryProblemsChanged)
fireModelChanged();
}
private void removeMarkerOverlays(boolean isCanceled) {
if (isCanceled) {
fCurrentlyOverlaid.addAll(fPreviouslyOverlaid);
} else if (fPreviouslyOverlaid != null) {
Iterator e= fPreviouslyOverlaid.iterator();
while (e.hasNext()) {
JavaMarkerAnnotation annotation= (JavaMarkerAnnotation) e.next();
annotation.setOverlay(null);
}
}
}
/**
* Overlays value with problem annotation.
* @param problemAnnotation
*/
private void setOverlay(Object value, ProblemAnnotation problemAnnotation) {
if (value instanceof JavaMarkerAnnotation) {
JavaMarkerAnnotation annotation= (JavaMarkerAnnotation) value;
if (annotation.isProblem()) {
annotation.setOverlay(problemAnnotation);
fPreviouslyOverlaid.remove(annotation);
fCurrentlyOverlaid.add(annotation);
}
}
}
private void overlayMarkers(Position position, ProblemAnnotation problemAnnotation) {
Object value= getAnnotations(position);
if (value instanceof List) {
List list= (List) value;
for (Iterator e = list.iterator(); e.hasNext();)
setOverlay(e.next(), problemAnnotation);
} else {
setOverlay(value, problemAnnotation);
}
}
/**
* Tells this annotation model to collect temporary problems from now on.
*/
private void startCollectingProblems() {
fCollectedProblems= new ArrayList();
fGeneratedAnnotations= new ArrayList();
}
/**
* Tells this annotation model to no longer collect temporary problems.
*/
private void stopCollectingProblems() {
if (fGeneratedAnnotations != null) {
removeAnnotations(fGeneratedAnnotations, true, true);
fGeneratedAnnotations.clear();
}
fCollectedProblems= null;
fGeneratedAnnotations= null;
}
/*
* @see AnnotationModel#fireModelChanged()
*/
protected void fireModelChanged() {
fireModelChanged(fCurrentEvent);
fCurrentEvent= new CompilationUnitAnnotationModelEvent(this, getResource());
}
/*
* @see IProblemRequestor#isActive()
*/
public boolean isActive() {
return fIsActive && (fCollectedProblems != null);
}
/*
* @see IProblemRequestorExtension#setProgressMonitor(IProgressMonitor)
*/
public void setProgressMonitor(IProgressMonitor monitor) {
fProgressMonitor= monitor;
}
/*
* @see IProblemRequestorExtension#setIsActive(boolean)
*/
public void setIsActive(boolean isActive) {
if (fIsActive != isActive) {
fIsActive= isActive;
if (fIsActive)
startCollectingProblems();
else
stopCollectingProblems();
}
}
private Object getAnnotations(Position position) {
return fReverseMap.get(position);
}
/*
* @see AnnotationModel#addAnnotation(Annotation, Position, boolean)
*/
protected void addAnnotation(Annotation annotation, Position position, boolean fireModelChanged) throws BadLocationException {
super.addAnnotation(annotation, position, fireModelChanged);
fCurrentEvent.annotationAdded(annotation);
Object cached= fReverseMap.get(position);
if (cached == null)
fReverseMap.put(position, annotation);
else if (cached instanceof List) {
List list= (List) cached;
list.add(annotation);
} else if (cached instanceof Annotation) {
List list= new ArrayList(2);
list.add(cached);
list.add(annotation);
fReverseMap.put(position, list);
}
}
/*
* @see AnnotationModel#removeAllAnnotations(boolean)
*/
protected void removeAllAnnotations(boolean fireModelChanged) {
for (Iterator iter= getAnnotationIterator(); iter.hasNext();) {
fCurrentEvent.annotationRemoved((Annotation) iter.next());
}
super.removeAllAnnotations(fireModelChanged);
fReverseMap.clear();
}
/*
* @see AnnotationModel#removeAnnotation(Annotation, boolean)
*/
protected void removeAnnotation(Annotation annotation, boolean fireModelChanged) {
fCurrentEvent.annotationRemoved(annotation);
Position position= getPosition(annotation);
Object cached= fReverseMap.get(position);
if (cached instanceof List) {
List list= (List) cached;
list.remove(annotation);
if (list.size() == 1) {
fReverseMap.put(position, list.get(0));
list.clear();
}
} else if (cached instanceof Annotation) {
fReverseMap.remove(position);
}
super.removeAnnotation(annotation, fireModelChanged);
}
}
protected static class GlobalAnnotationModelListener implements IAnnotationModelListener, IAnnotationModelListenerExtension {
private ListenerList fListenerList;
public GlobalAnnotationModelListener() {
fListenerList= new ListenerList();
}
/**
* @see IAnnotationModelListener#modelChanged(IAnnotationModel)
*/
public void modelChanged(IAnnotationModel model) {
Object[] listeners= fListenerList.getListeners();
for (int i= 0; i < listeners.length; i++) {
((IAnnotationModelListener) listeners[i]).modelChanged(model);
}
}
/**
* @see IAnnotationModelListenerExtension#modelChanged(AnnotationModelEvent)
*/
public void modelChanged(AnnotationModelEvent event) {
Object[] listeners= fListenerList.getListeners();
for (int i= 0; i < listeners.length; i++) {
Object curr= listeners[i];
if (curr instanceof IAnnotationModelListenerExtension) {
((IAnnotationModelListenerExtension) curr).modelChanged(event);
}
}
}
public void addListener(IAnnotationModelListener listener) {
fListenerList.add(listener);
}
public void removeListener(IAnnotationModelListener listener) {
fListenerList.remove(listener);
}
}
/** Preference key for temporary problems */
private final static String HANDLE_TEMPORARY_PROBLEMS= PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS;
/** Indicates whether the save has been initialized by this provider */
private boolean fIsAboutToSave= false;
/** The save policy used by this provider */
private ISavePolicy fSavePolicy;
/** Internal property changed listener */
private IPropertyChangeListener fPropertyListener;
/** Annotation model listener added to all created CU annotation models */
private GlobalAnnotationModelListener fGlobalAnnotationModelListener;
/**
* Constructor
*/
public CompilationUnitDocumentProvider() {
fPropertyListener= new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
if (HANDLE_TEMPORARY_PROBLEMS.equals(event.getProperty()))
enableHandlingTemporaryProblems();
}
};
fGlobalAnnotationModelListener= new GlobalAnnotationModelListener();
JavaPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(fPropertyListener);
}
/**
* Creates a compilation unit from the given file.
*
* @param file the file from which to create the compilation unit
*/
protected ICompilationUnit createCompilationUnit(IFile file) {
Object element= JavaCore.create(file);
if (element instanceof ICompilationUnit)
return (ICompilationUnit) element;
return null;
}
/*
* @see AbstractDocumentProvider#createElementInfo(Object)
*/
protected ElementInfo createElementInfo(Object element) throws CoreException {
if ( !(element instanceof IFileEditorInput))
return super.createElementInfo(element);
IFileEditorInput input= (IFileEditorInput) element;
ICompilationUnit original= createCompilationUnit(input.getFile());
if (original != null) {
try {
try {
refreshFile(input.getFile());
} catch (CoreException x) {
handleCoreException(x, JavaEditorMessages.getString("CompilationUnitDocumentProvider.error.createElementInfo")); //$NON-NLS-1$
}
IAnnotationModel m= createCompilationUnitAnnotationModel(input);
IProblemRequestor r= m instanceof IProblemRequestor ? (IProblemRequestor) m : null;
ICompilationUnit c= null;
if (JavaPlugin.USE_WORKING_COPY_OWNERS) {
original.becomeWorkingCopy(r, getProgressMonitor());
c= original;
} else {
c= (ICompilationUnit) original.getSharedWorkingCopy(getProgressMonitor(), JavaPlugin.getDefault().getBufferFactory(), r);
}
DocumentAdapter a= null;
try {
a= (DocumentAdapter) c.getBuffer();
} catch (ClassCastException x) {
IStatus status= new Status(IStatus.ERROR, JavaUI.ID_PLUGIN, IJavaStatusConstants.TEMPLATE_IO_EXCEPTION, "Shared working copy has wrong buffer", x); //$NON-NLS-1$
throw new CoreException(status);
}
_FileSynchronizer f= new _FileSynchronizer(input);
f.install();
CompilationUnitInfo info= new CompilationUnitInfo(a.getDocument(), m, f, c);
info.setModificationStamp(computeModificationStamp(input.getFile()));
info.fStatus= a.getStatus();
info.fEncoding= getPersistedEncoding(input);
if (r instanceof IProblemRequestorExtension) {
IProblemRequestorExtension extension= (IProblemRequestorExtension) r;
extension.setIsActive(isHandlingTemporaryProblems());
}
m.addAnnotationModelListener(fGlobalAnnotationModelListener);
return info;
} catch (JavaModelException x) {
throw new CoreException(x.getStatus());
}
} else {
return super.createElementInfo(element);
}
}
/*
* @see AbstractDocumentProvider#disposeElementInfo(Object, ElementInfo)
*/
protected void disposeElementInfo(Object element, ElementInfo info) {
if (info instanceof CompilationUnitInfo) {
CompilationUnitInfo cuInfo= (CompilationUnitInfo) info;
if (JavaPlugin.USE_WORKING_COPY_OWNERS) {
try {
cuInfo.fCopy.discardWorkingCopy();
} catch (JavaModelException x) {
handleCoreException(x, x.getMessage());
}
} else {
cuInfo.fCopy.destroy();
}
cuInfo.fModel.removeAnnotationModelListener(fGlobalAnnotationModelListener);
}
super.disposeElementInfo(element, info);
}
/*
* @see AbstractDocumentProvider#doSaveDocument(IProgressMonitor, Object, IDocument, boolean)
*/
protected void doSaveDocument(IProgressMonitor monitor, Object element, IDocument document, boolean overwrite) throws CoreException {
ElementInfo elementInfo= getElementInfo(element);
if (elementInfo instanceof CompilationUnitInfo) {
CompilationUnitInfo info= (CompilationUnitInfo) elementInfo;
// update structure, assumes lock on info.fCopy
info.fCopy.reconcile();
ICompilationUnit original= (ICompilationUnit) info.fCopy.getOriginalElement();
IResource resource= original.getResource();
if (resource == null) {
// underlying resource has been deleted, just recreate file, ignore the rest
super.doSaveDocument(monitor, element, document, overwrite);
return;
}
if (resource != null && !overwrite)
checkSynchronizationState(info.fModificationStamp, resource);
if (fSavePolicy != null)
fSavePolicy.preSave(info.fCopy);
// inform about the upcoming content change
fireElementStateChanging(element);
try {
fIsAboutToSave= true;
// commit working copy
if (JavaPlugin.USE_WORKING_COPY_OWNERS)
info.fCopy.commitWorkingCopy(overwrite, monitor);
else
info.fCopy.commit(overwrite, monitor);
} catch (CoreException x) {
// inform about the failure
fireElementStateChangeFailed(element);
throw x;
} catch (RuntimeException x) {
// inform about the failure
fireElementStateChangeFailed(element);
throw x;
} finally {
fIsAboutToSave= false;
}
// If here, the dirty state of the editor will change to "not dirty".
// Thus, the state changing flag will be reset.
AbstractMarkerAnnotationModel model= (AbstractMarkerAnnotationModel) info.fModel;
model.updateMarkers(info.fDocument);
if (resource != null)
info.setModificationStamp(computeModificationStamp(resource));
if (fSavePolicy != null) {
ICompilationUnit unit= fSavePolicy.postSave(original);
if (unit != null) {
IResource r= unit.getResource();
IMarker[] markers= r.findMarkers(IMarker.MARKER, true, IResource.DEPTH_ZERO);
if (markers != null && markers.length > 0) {
for (int i= 0; i < markers.length; i++)
model.updateMarker(markers[i], info.fDocument, null);
}
}
}
} else {
super.doSaveDocument(monitor, element, document, overwrite);
}
}
/**
* Replaces createAnnotionModel of the super class.
*/
protected IAnnotationModel createCompilationUnitAnnotationModel(Object element) throws CoreException {
if ( !(element instanceof IFileEditorInput))
throw new CoreException(JavaUIStatus.createError(
IJavaModelStatusConstants.INVALID_RESOURCE_TYPE, "", null)); //$NON-NLS-1$
IFileEditorInput input= (IFileEditorInput) element;
return new CompilationUnitAnnotationModel(input);
}
/*
* @see org.eclipse.ui.editors.text.StorageDocumentProvider#createEmptyDocument()
*/
protected IDocument createEmptyDocument() {
return new PartiallySynchronizedDocument();
}
/*
* @see AbstractDocumentProvider#resetDocument(Object)
*/
public void resetDocument(Object element) throws CoreException {
if (element == null)
return;
ElementInfo elementInfo= getElementInfo(element);
if (elementInfo instanceof CompilationUnitInfo) {
CompilationUnitInfo info= (CompilationUnitInfo) elementInfo;
IDocument document;
IStatus status= null;
try {
ICompilationUnit original= (ICompilationUnit) info.fCopy.getOriginalElement();
IResource resource= original.getResource();
if (resource instanceof IFile) {
IFile file= (IFile) resource;
try {
refreshFile(file);
} catch (CoreException x) {
handleCoreException(x, JavaEditorMessages.getString("CompilationUnitDocumentProvider.error.resetDocument")); //$NON-NLS-1$
}
IFileEditorInput input= new FileEditorInput(file);
document= super.createDocument(input);
} else {
document= createEmptyDocument();
}
} catch (CoreException x) {
document= createEmptyDocument();
status= x.getStatus();
}
fireElementContentAboutToBeReplaced(element);
removeUnchangedElementListeners(element, info);
info.fDocument.set(document.get());
info.fCanBeSaved= false;
info.fStatus= status;
addUnchangedElementListeners(element, info);
fireElementContentReplaced(element);
fireElementDirtyStateChanged(element, false);
} else {
super.resetDocument(element);
}
}
/**
* Returns the preference whether handling temporary problems is enabled.
*/
protected boolean isHandlingTemporaryProblems() {
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
return store.getBoolean(HANDLE_TEMPORARY_PROBLEMS);
}
/**
* Switches the state of problem acceptance according to the value in the preference store.
*/
protected void enableHandlingTemporaryProblems() {
boolean enable= isHandlingTemporaryProblems();
for (Iterator iter= getConnectedElements(); iter.hasNext();) {
ElementInfo element= getElementInfo(iter.next());
if (element instanceof CompilationUnitInfo) {
CompilationUnitInfo info= (CompilationUnitInfo)element;
if (info.fModel instanceof IProblemRequestorExtension) {
IProblemRequestorExtension extension= (IProblemRequestorExtension) info.fModel;
extension.setIsActive(enable);
}
}
}
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#saveDocumentContent(org.eclipse.core.runtime.IProgressMonitor, java.lang.Object, org.eclipse.jface.text.IDocument, boolean)
*/
public void saveDocumentContent(IProgressMonitor monitor, Object element, IDocument document, boolean overwrite) throws CoreException {
if (!fIsAboutToSave)
return;
if (element instanceof IFileEditorInput) {
IFileEditorInput input= (IFileEditorInput) element;
try {
String encoding= getEncoding(element);
if (encoding == null)
encoding= ResourcesPlugin.getEncoding();
InputStream stream= new ByteArrayInputStream(document.get().getBytes(encoding));
IFile file= input.getFile();
file.setContents(stream, overwrite, true, monitor);
} catch (IOException x) {
IStatus s= new Status(IStatus.ERROR, JavaUI.ID_PLUGIN, IStatus.OK, x.getMessage(), x);
throw new CoreException(s);
}
}
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#shutdown()
*/
public void shutdown() {
JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(fPropertyListener);
Iterator e= getConnectedElements();
while (e.hasNext())
disconnect(e.next());
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#addGlobalAnnotationModelListener(org.eclipse.jface.text.source.IAnnotationModelListener)
*/
public void addGlobalAnnotationModelListener(IAnnotationModelListener listener) {
fGlobalAnnotationModelListener.addListener(listener);
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#removeGlobalAnnotationModelListener(org.eclipse.jface.text.source.IAnnotationModelListener)
*/
public void removeGlobalAnnotationModelListener(IAnnotationModelListener listener) {
fGlobalAnnotationModelListener.removeListener(listener);
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#getWorkingCopy(java.lang.Object)
*/
public ICompilationUnit getWorkingCopy(Object element) {
ElementInfo elementInfo= getElementInfo(element);
if (elementInfo instanceof CompilationUnitInfo) {
CompilationUnitInfo info= (CompilationUnitInfo) elementInfo;
return info.fCopy;
}
return null;
}
/*
* @see org.eclipse.ui.texteditor.IDocumentProviderExtension3#createEmptyDocument(java.lang.Object)
*/
public IDocument createEmptyDocument(Object element) {
return createEmptyDocument();
}
/*
* @see org.eclipse.ui.editors.text.StorageDocumentProvider#setupDocument(java.lang.Object, org.eclipse.jface.text.IDocument)
*/
protected void setupDocument(Object element, IDocument document) {
if (document != null) {
JavaTextTools tools= JavaPlugin.getDefault().getJavaTextTools();
tools.setupDocument(document, IJavaPartitions.JAVA_PARTITIONING);
}
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#createLineTracker(java.lang.Object)
*/
public ILineTracker createLineTracker(Object element) {
return new DefaultLineTracker();
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#setSavePolicy(org.eclipse.jdt.internal.ui.javaeditor.ISavePolicy)
*/
public void setSavePolicy(ISavePolicy savePolicy) {
fSavePolicy= savePolicy;
}
/*
* Here for visibility reasons.
* @see AbstractDocumentProvider#createDocument(Object)
*/
public IDocument createDocument(Object element) throws CoreException {
return super.createDocument(element);
}
}
|
40,785 |
Bug 40785 [plan item] Overview ruler improvements
|
- navigation from ruler to editor - hovering over header area shows number of errors/warning (header annotations in general)
|
resolved fixed
|
0c04535
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-22T09:43:23Z | 2003-07-25T16:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/JavaEditor.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.javaeditor;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ResourceBundle;
import java.util.StringTokenizer;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Preferences;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BidiSegmentEvent;
import org.eclipse.swt.custom.BidiSegmentListener;
import org.eclipse.swt.custom.StyleRange;
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.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
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.Separator;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.IPostSelectionProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.text.BadLocationException;
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.ITextInputListener;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.ITextViewerExtension2;
import org.eclipse.jface.text.ITextViewerExtension3;
import org.eclipse.jface.text.ITextViewerExtension4;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.text.TextUtilities;
import org.eclipse.jface.text.information.IInformationProvider;
import org.eclipse.jface.text.information.IInformationProviderExtension2;
import org.eclipse.jface.text.information.InformationPresenter;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.IAnnotationAccess;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.IOverviewRuler;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.IVerticalRuler;
import org.eclipse.jface.text.source.LineChangeHover;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
import org.eclipse.ui.IEditorActionBarContributor;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPartService;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.EditorActionBarContributor;
import org.eclipse.ui.part.IShowInTargetList;
import org.eclipse.ui.texteditor.AddTaskAction;
import org.eclipse.ui.texteditor.AnnotationPreference;
import org.eclipse.ui.texteditor.DefaultRangeIndicator;
import org.eclipse.ui.texteditor.ExtendedTextEditor;
import org.eclipse.ui.texteditor.IAbstractTextEditorHelpContextIds;
import org.eclipse.ui.texteditor.IEditorStatusLine;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
import org.eclipse.ui.texteditor.MarkerAnnotation;
import org.eclipse.ui.texteditor.ResourceAction;
import org.eclipse.ui.texteditor.SourceViewerDecorationSupport;
import org.eclipse.ui.texteditor.TextEditorAction;
import org.eclipse.ui.texteditor.TextOperationAction;
import org.eclipse.ui.views.contentoutline.ContentOutline;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
import org.eclipse.ui.views.tasklist.TaskList;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICodeAssist;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IImportContainer;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IPackageDeclaration;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.ISourceReference;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.actions.IJavaEditorActionDefinitionIds;
import org.eclipse.jdt.ui.actions.JavaSearchActionGroup;
import org.eclipse.jdt.ui.actions.OpenEditorActionGroup;
import org.eclipse.jdt.ui.actions.OpenViewActionGroup;
import org.eclipse.jdt.ui.actions.ShowActionGroup;
import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.GoToNextPreviousMemberAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.SelectionHistory;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectEnclosingAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectHistoryAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectNextAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectPreviousAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectionAction;
import org.eclipse.jdt.internal.ui.text.HTMLTextPresenter;
import org.eclipse.jdt.internal.ui.text.IJavaPartitions;
import org.eclipse.jdt.internal.ui.text.JavaChangeHover;
import org.eclipse.jdt.internal.ui.text.JavaPairMatcher;
import org.eclipse.jdt.internal.ui.util.JavaUIHelp;
import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider;
/**
* Java specific text editor.
*/
public abstract class JavaEditor extends ExtendedTextEditor implements IViewPartInputProvider {
/**
* Internal implementation class for a change listener.
* @since 3.0
*/
protected abstract class AbstractSelectionChangedListener implements ISelectionChangedListener {
/**
* Installs this selection changed listener with the given selection provider. If
* the selection provider is a post selection provider, post selection changed
* events are the preferred choice, otherwise normal selection changed events
* are requested.
*
* @param selectionProvider
*/
public void install(ISelectionProvider selectionProvider) {
if (selectionProvider == null)
return;
if (selectionProvider instanceof IPostSelectionProvider) {
IPostSelectionProvider provider= (IPostSelectionProvider) selectionProvider;
provider.addPostSelectionChangedListener(this);
} else {
selectionProvider.addSelectionChangedListener(this);
}
}
/**
* Removes this selection changed listener from the given selection provider.
*
* @param selectionProvider
*/
public void uninstall(ISelectionProvider selectionProvider) {
if (selectionProvider == null)
return;
if (selectionProvider instanceof IPostSelectionProvider) {
IPostSelectionProvider provider= (IPostSelectionProvider) selectionProvider;
provider.removePostSelectionChangedListener(this);
} else {
selectionProvider.removeSelectionChangedListener(this);
}
}
}
/**
* Updates the Java outline page selection and this editor's range indicator.
*
* @since 3.0
*/
private class EditorSelectionChangedListener extends AbstractSelectionChangedListener {
/*
* @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent)
*/
public void selectionChanged(SelectionChangedEvent event) {
selectionChanged();
}
public void selectionChanged() {
ISourceReference element= computeHighlightRangeSourceReference();
synchronizeOutlinePage(element);
setSelection(element, false);
}
}
/**
* Updates the selection in the editor's widget with the selection of the outline page.
*/
class OutlineSelectionChangedListener extends AbstractSelectionChangedListener {
public void selectionChanged(SelectionChangedEvent event) {
doSelectionChanged(event);
}
}
/*
* Link mode.
*/
class MouseClickListener implements KeyListener, MouseListener, MouseMoveListener,
FocusListener, PaintListener, IPropertyChangeListener, IDocumentListener, ITextInputListener {
/** The session is active. */
private boolean fActive;
/** The currently active style range. */
private IRegion fActiveRegion;
/** The currently active style range as position. */
private Position fRememberedPosition;
/** The hand cursor. */
private Cursor fCursor;
/** The link color. */
private Color fColor;
/** The key modifier mask. */
private int fKeyModifierMask;
public void deactivate() {
deactivate(false);
}
public void deactivate(boolean redrawAll) {
if (!fActive)
return;
repairRepresentation(redrawAll);
fActive= false;
}
public void install() {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
StyledText text= sourceViewer.getTextWidget();
if (text == null || text.isDisposed())
return;
updateColor(sourceViewer);
sourceViewer.addTextInputListener(this);
IDocument document= sourceViewer.getDocument();
if (document != null)
document.addDocumentListener(this);
text.addKeyListener(this);
text.addMouseListener(this);
text.addMouseMoveListener(this);
text.addFocusListener(this);
text.addPaintListener(this);
updateKeyModifierMask();
IPreferenceStore preferenceStore= getPreferenceStore();
preferenceStore.addPropertyChangeListener(this);
}
private void updateKeyModifierMask() {
String modifiers= getPreferenceStore().getString(BROWSER_LIKE_LINKS_KEY_MODIFIER);
fKeyModifierMask= computeStateMask(modifiers);
if (fKeyModifierMask == -1) {
// Fallback to stored state mask
fKeyModifierMask= getPreferenceStore().getInt(BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK);
}
}
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;
}
public void uninstall() {
if (fColor != null) {
fColor.dispose();
fColor= null;
}
if (fCursor != null) {
fCursor.dispose();
fCursor= null;
}
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
sourceViewer.removeTextInputListener(this);
IDocument document= sourceViewer.getDocument();
if (document != null)
document.removeDocumentListener(this);
IPreferenceStore preferenceStore= getPreferenceStore();
if (preferenceStore != null)
preferenceStore.removePropertyChangeListener(this);
StyledText text= sourceViewer.getTextWidget();
if (text == null || text.isDisposed())
return;
text.removeKeyListener(this);
text.removeMouseListener(this);
text.removeMouseMoveListener(this);
text.removeFocusListener(this);
text.removePaintListener(this);
}
/*
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
if (event.getProperty().equals(JavaEditor.LINK_COLOR)) {
ISourceViewer viewer= getSourceViewer();
if (viewer != null)
updateColor(viewer);
} else if (event.getProperty().equals(BROWSER_LIKE_LINKS_KEY_MODIFIER)) {
updateKeyModifierMask();
}
}
private void updateColor(ISourceViewer viewer) {
if (fColor != null)
fColor.dispose();
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
Display display= text.getDisplay();
fColor= createColor(getPreferenceStore(), JavaEditor.LINK_COLOR, display);
}
/**
* 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);
if (rgb != null)
return new Color(display, rgb);
}
return null;
}
private void repairRepresentation() {
repairRepresentation(false);
}
private void repairRepresentation(boolean redrawAll) {
if (fActiveRegion == null)
return;
ISourceViewer viewer= getSourceViewer();
if (viewer != null) {
resetCursor(viewer);
int offset= fActiveRegion.getOffset();
int length= fActiveRegion.getLength();
// remove style
if (!redrawAll && viewer instanceof ITextViewerExtension2)
((ITextViewerExtension2) viewer).invalidateTextPresentation(offset, length);
else
viewer.invalidateTextPresentation();
// remove underline
if (viewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) viewer;
offset= extension.modelOffset2WidgetOffset(offset);
} else {
offset -= viewer.getVisibleRegion().getOffset();
}
StyledText text= viewer.getTextWidget();
try {
text.redrawRange(offset, length, true);
} catch (IllegalArgumentException x) {
JavaPlugin.log(x);
}
}
fActiveRegion= null;
}
// will eventually be replaced by a method provided by jdt.core
private IRegion selectWord(IDocument document, int anchor) {
try {
int offset= anchor;
char c;
while (offset >= 0) {
c= document.getChar(offset);
if (!Character.isJavaIdentifierPart(c))
break;
--offset;
}
int start= offset;
offset= anchor;
int length= document.getLength();
while (offset < length) {
c= document.getChar(offset);
if (!Character.isJavaIdentifierPart(c))
break;
++offset;
}
int end= offset;
if (start == end)
return new Region(start, 0);
else
return new Region(start + 1, end - start - 1);
} catch (BadLocationException x) {
return null;
}
}
IRegion getCurrentTextRegion(ISourceViewer viewer) {
int offset= getCurrentTextOffset(viewer);
if (offset == -1)
return null;
IJavaElement input= SelectionConverter.getInput(JavaEditor.this);
if (input == null)
return null;
try {
IJavaElement[] elements= null;
synchronized (input) {
elements= ((ICodeAssist) input).codeSelect(offset, 0);
}
if (elements == null || elements.length == 0)
return null;
return selectWord(viewer.getDocument(), offset);
} catch (JavaModelException e) {
return null;
}
}
private int getCurrentTextOffset(ISourceViewer viewer) {
try {
StyledText text= viewer.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 (viewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) viewer;
return extension.widgetOffset2ModelOffset(widgetOffset);
} else {
return widgetOffset + viewer.getVisibleRegion().getOffset();
}
} catch (IllegalArgumentException e) {
return -1;
}
}
private void highlightRegion(ISourceViewer viewer, IRegion region) {
if (region.equals(fActiveRegion))
return;
repairRepresentation();
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
// highlight region
int offset= 0;
int length= 0;
if (viewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) viewer;
IRegion widgetRange= extension.modelRange2WidgetRange(region);
if (widgetRange == null)
return;
offset= widgetRange.getOffset();
length= widgetRange.getLength();
} else {
offset= region.getOffset() - viewer.getVisibleRegion().getOffset();
length= region.getLength();
}
StyleRange oldStyleRange= text.getStyleRangeAtOffset(offset);
Color foregroundColor= fColor;
Color backgroundColor= oldStyleRange == null ? text.getBackground() : oldStyleRange.background;
StyleRange styleRange= new StyleRange(offset, length, foregroundColor, backgroundColor);
text.setStyleRange(styleRange);
// underline
text.redrawRange(offset, length, true);
fActiveRegion= region;
}
private void activateCursor(ISourceViewer 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 void resetCursor(ISourceViewer viewer) {
StyledText text= viewer.getTextWidget();
if (text != null && !text.isDisposed())
text.setCursor(null);
if (fCursor != null) {
fCursor.dispose();
fCursor= null;
}
}
/*
* @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.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;
deactivate();
if (wasActive) {
IAction action= getAction("OpenEditor"); //$NON-NLS-1$
if (action != null)
action.run();
}
}
/*
* @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;
}
ISourceViewer viewer= getSourceViewer();
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= getCurrentTextRegion(viewer);
if (region == null || region.getLength() == 0) {
repairRepresentation();
return;
}
highlightRegion(viewer, region);
activateCursor(viewer);
}
/*
* @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();
}
/*
* @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 && !fRememberedPosition.isDeleted()) {
event.getDocument().removePosition(fRememberedPosition);
fActiveRegion= new Region(fRememberedPosition.getOffset(), fRememberedPosition.getLength());
}
fRememberedPosition= null;
ISourceViewer viewer= getSourceViewer();
if (viewer != null) {
StyledText widget= viewer.getTextWidget();
if (widget != null && !widget.isDisposed()) {
widget.getDisplay().asyncExec(new Runnable() {
public void run() {
deactivate();
}
});
}
}
}
/*
* @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);
}
/*
* @see PaintListener#paintControl(PaintEvent)
*/
public void paintControl(PaintEvent event) {
if (fActiveRegion == null)
return;
ISourceViewer viewer= getSourceViewer();
if (viewer == null)
return;
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
int offset= 0;
int length= 0;
if (viewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) viewer;
IRegion widgetRange= extension.modelRange2WidgetRange(new Region(offset, length));
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);
}
private boolean includes(IRegion region, IRegion position) {
return
position.getOffset() >= region.getOffset() &&
position.getOffset() + position.getLength() <= region.getOffset() + region.getLength();
}
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 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;
}
}
/**
* This action dispatches into two behaviours: If there is no current text
* hover, the javadoc is displayed using information presenter. If there is
* a current text hover, it is converted into a information presenter in
* order to make it sticky.
*/
class InformationDispatchAction extends TextEditorAction {
/** The wrapped text operation action. */
private final TextOperationAction fTextOperationAction;
/**
* Creates a dispatch action.
*/
public InformationDispatchAction(ResourceBundle resourceBundle, String prefix, final TextOperationAction textOperationAction) {
super(resourceBundle, prefix, JavaEditor.this);
if (textOperationAction == null)
throw new IllegalArgumentException();
fTextOperationAction= textOperationAction;
}
/*
* @see org.eclipse.jface.action.IAction#run()
*/
public void run() {
/**
* Information provider used to present the information.
*
* @since 3.0
*/
class InformationProvider implements IInformationProvider, IInformationProviderExtension2 {
private IRegion fHoverRegion;
private String fHoverInfo;
private IInformationControlCreator fControlCreator;
InformationProvider(IRegion hoverRegion, String hoverInfo, IInformationControlCreator controlCreator) {
fHoverRegion= hoverRegion;
fHoverInfo= hoverInfo;
fControlCreator= controlCreator;
}
/*
* @see org.eclipse.jface.text.information.IInformationProvider#getSubject(org.eclipse.jface.text.ITextViewer, int)
*/
public IRegion getSubject(ITextViewer textViewer, int invocationOffset) {
return fHoverRegion;
}
/*
* @see org.eclipse.jface.text.information.IInformationProvider#getInformation(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion)
*/
public String getInformation(ITextViewer textViewer, IRegion subject) {
return fHoverInfo;
}
/*
* @see org.eclipse.jface.text.information.IInformationProviderExtension2#getInformationPresenterControlCreator()
* @since 3.0
*/
public IInformationControlCreator getInformationPresenterControlCreator() {
return fControlCreator;
}
}
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null) {
fTextOperationAction.run();
return;
}
if (sourceViewer instanceof ITextViewerExtension4) {
ITextViewerExtension4 extension4= (ITextViewerExtension4) sourceViewer;
extension4.moveFocusToWidgetToken();
}
if (! (sourceViewer instanceof ITextViewerExtension2)) {
fTextOperationAction.run();
return;
}
ITextViewerExtension2 textViewerExtension2= (ITextViewerExtension2) sourceViewer;
// does a text hover exist?
ITextHover textHover= textViewerExtension2.getCurrentTextHover();
if (textHover == null) {
fTextOperationAction.run();
return;
}
Point hoverEventLocation= textViewerExtension2.getHoverEventLocation();
int offset= computeOffsetAtLocation(sourceViewer, hoverEventLocation.x, hoverEventLocation.y);
if (offset == -1) {
fTextOperationAction.run();
return;
}
try {
// get the text hover content
String contentType= TextUtilities.getContentType(sourceViewer.getDocument(), IJavaPartitions.JAVA_PARTITIONING, offset);
IRegion hoverRegion= textHover.getHoverRegion(sourceViewer, offset);
if (hoverRegion == null)
return;
String hoverInfo= textHover.getHoverInfo(sourceViewer, hoverRegion);
IInformationControlCreator controlCreator= null;
if (textHover instanceof IInformationProviderExtension2)
controlCreator= ((IInformationProviderExtension2)textHover).getInformationPresenterControlCreator();
IInformationProvider informationProvider= new InformationProvider(hoverRegion, hoverInfo, controlCreator);
fInformationPresenter.setOffset(offset);
fInformationPresenter.setInformationProvider(informationProvider, contentType);
fInformationPresenter.showInformation();
} catch (BadLocationException e) {
}
}
// modified version from TextViewer
private int computeOffsetAtLocation(ITextViewer textViewer, int x, int y) {
StyledText styledText= textViewer.getTextWidget();
IDocument document= textViewer.getDocument();
if (document == null)
return -1;
try {
int widgetLocation= styledText.getOffsetAtLocation(new Point(x, y));
if (textViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) textViewer;
return extension.widgetOffset2ModelOffset(widgetLocation);
} else {
IRegion visibleRegion= textViewer.getVisibleRegion();
return widgetLocation + visibleRegion.getOffset();
}
} catch (IllegalArgumentException e) {
return -1;
}
}
}
static protected class AnnotationAccess implements IAnnotationAccess {
/*
* @see org.eclipse.jface.text.source.IAnnotationAccess#getType(org.eclipse.jface.text.source.Annotation)
*/
public Object getType(Annotation annotation) {
if (annotation instanceof IJavaAnnotation) {
IJavaAnnotation javaAnnotation= (IJavaAnnotation) annotation;
if (javaAnnotation.isRelevant())
return javaAnnotation.getAnnotationType();
}
return null;
}
/*
* @see org.eclipse.jface.text.source.IAnnotationAccess#isMultiLine(org.eclipse.jface.text.source.Annotation)
*/
public boolean isMultiLine(Annotation annotation) {
return true;
}
/*
* @see org.eclipse.jface.text.source.IAnnotationAccess#isTemporary(org.eclipse.jface.text.source.Annotation)
*/
public boolean isTemporary(Annotation annotation) {
if (annotation instanceof IJavaAnnotation) {
IJavaAnnotation javaAnnotation= (IJavaAnnotation) annotation;
if (javaAnnotation.isRelevant())
return javaAnnotation.isTemporary();
}
return false;
}
}
private class PropertyChangeListener implements org.eclipse.core.runtime.Preferences.IPropertyChangeListener {
/*
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
handlePreferencePropertyChanged(event);
}
}
/** Preference key for the link color */
protected final static String LINK_COLOR= PreferenceConstants.EDITOR_LINK_COLOR;
/** Preference key for matching brackets */
protected final static String MATCHING_BRACKETS= PreferenceConstants.EDITOR_MATCHING_BRACKETS;
/** Preference key for matching brackets color */
protected final static String MATCHING_BRACKETS_COLOR= PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR;
/** Preference key for compiler task tags */
private final static String COMPILER_TASK_TAGS= JavaCore.COMPILER_TASK_TAGS;
/** Preference key for browser like links */
private final static String BROWSER_LIKE_LINKS= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS;
/** Preference key for key modifier of browser like links */
private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER;
/**
* Preference key for key modifier mask of browser like links.
* The value is only used if the value of <code>EDITOR_BROWSER_LIKE_LINKS</code>
* cannot be resolved to valid SWT modifier bits.
*
* @since 2.1.1
*/
private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK;
protected final static char[] BRACKETS= { '{', '}', '(', ')', '[', ']' };
/** The outline page */
protected JavaOutlinePage fOutlinePage;
/** Outliner context menu Id */
protected String fOutlinerContextMenuId;
/**
* The editor selection changed listener.
*
* @since 3.0
*/
private EditorSelectionChangedListener fEditorSelectionChangedListener;
/** The selection changed listener */
protected AbstractSelectionChangedListener fOutlineSelectionChangedListener= new OutlineSelectionChangedListener();
/** The editor's bracket matcher */
protected JavaPairMatcher fBracketMatcher= new JavaPairMatcher(BRACKETS);
/** The mouse listener */
private MouseClickListener fMouseListener;
/** The information presenter. */
private InformationPresenter fInformationPresenter;
/** History for structure select action */
private SelectionHistory fSelectionHistory;
/** The preference property change listener for java core. */
private org.eclipse.core.runtime.Preferences.IPropertyChangeListener fPropertyChangeListener= new PropertyChangeListener();
protected CompositeActionGroup fActionGroups;
private CompositeActionGroup fContextMenuGroup;
/**
* Returns the most narrow java element including the given offset.
*
* @param offset the offset inside of the requested element
* @return the most narrow java element
*/
abstract protected IJavaElement getElementAt(int offset);
/**
* Returns the java element of this editor's input corresponding to the given IJavaElement
*/
abstract protected IJavaElement getCorrespondingElement(IJavaElement element);
/**
* Sets the input of the editor's outline page.
*/
abstract protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input);
/**
* Default constructor.
*/
public JavaEditor() {
super();
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
setSourceViewerConfiguration(new JavaSourceViewerConfiguration(textTools, this, IJavaPartitions.JAVA_PARTITIONING));
setRangeIndicator(new DefaultRangeIndicator());
setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore());
setKeyBindingScopes(new String[] { "org.eclipse.jdt.ui.javaEditorScope" }); //$NON-NLS-1$
}
/*
* @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
*/
protected final ISourceViewer createSourceViewer(Composite parent, IVerticalRuler verticalRuler, int styles) {
ISourceViewer viewer= createJavaSourceViewer(parent, verticalRuler, getOverviewRuler(), isOverviewRulerVisible(), styles);
StyledText text= viewer.getTextWidget();
text.addBidiSegmentListener(new BidiSegmentListener() {
public void lineGetSegments(BidiSegmentEvent event) {
event.segments= getBidiLineSegments(event.lineOffset, event.lineText);
}
});
JavaUIHelp.setHelp(this, text, IJavaHelpContextIds.JAVA_EDITOR);
// ensure source viewer decoration support has been created and configured
getSourceViewerDecorationSupport(viewer);
return viewer;
}
/*
* @see org.eclipse.ui.texteditor.ExtendedTextEditor#createAnnotationAccess()
*/
protected IAnnotationAccess createAnnotationAccess() {
return new AnnotationAccess();
}
public final ISourceViewer getViewer() {
return getSourceViewer();
}
/*
* @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
*/
protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean isOverviewRulerVisible, int styles) {
return new JavaSourceViewer(parent, verticalRuler, getOverviewRuler(), isOverviewRulerVisible(), styles);
}
/*
* @see AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent)
*/
protected boolean affectsTextPresentation(PropertyChangeEvent event) {
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
return textTools.affectsBehavior(event);
}
/**
* Sets the outliner's context menu ID.
*/
protected void setOutlinerContextMenuId(String menuId) {
fOutlinerContextMenuId= menuId;
}
/**
* Returns the standard action group of this editor.
*/
protected ActionGroup getActionGroup() {
return fActionGroups;
}
/*
* @see AbstractTextEditor#editorContextMenuAboutToShow
*/
public void editorContextMenuAboutToShow(IMenuManager menu) {
super.editorContextMenuAboutToShow(menu);
menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, new Separator(IContextMenuConstants.GROUP_OPEN));
menu.insertAfter(IContextMenuConstants.GROUP_OPEN, new GroupMarker(IContextMenuConstants.GROUP_SHOW));
ActionContext context= new ActionContext(getSelectionProvider().getSelection());
fContextMenuGroup.setContext(context);
fContextMenuGroup.fillContextMenu(menu);
fContextMenuGroup.setContext(null);
}
/**
* Creates the outline page used with this editor.
*/
protected JavaOutlinePage createOutlinePage() {
JavaOutlinePage page= new JavaOutlinePage(fOutlinerContextMenuId, this);
fOutlineSelectionChangedListener.install(page);
setOutlinePageInput(page, getEditorInput());
return page;
}
/**
* Informs the editor that its outliner has been closed.
*/
public void outlinePageClosed() {
if (fOutlinePage != null) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage= null;
resetHighlightRange();
}
}
/**
* Synchronizes the outliner selection with the given element
* position in the editor.
*
* @param element the java element to select
*/
protected void synchronizeOutlinePage(ISourceReference element) {
synchronizeOutlinePage(element, true);
}
/**
* Synchronizes the outliner selection with the given element
* position in the editor.
*
* @param element the java element to select
* @param checkIfOutlinePageActive <code>true</code> if check for active outline page needs to be done
*/
protected void synchronizeOutlinePage(ISourceReference element, boolean checkIfOutlinePageActive) {
if (fOutlinePage != null && element != null && !(checkIfOutlinePageActive && isJavaOutlinePageActive())) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage.select(element);
fOutlineSelectionChangedListener.install(fOutlinePage);
}
}
/**
* Synchronizes the outliner selection with the actual cursor
* position in the editor.
*/
public void synchronizeOutlinePageSelection() {
synchronizeOutlinePage(computeHighlightRangeSourceReference());
}
/*
* Get the desktop's StatusLineManager
*/
protected IStatusLineManager getStatusLineManager() {
IEditorActionBarContributor contributor= getEditorSite().getActionBarContributor();
if (contributor instanceof EditorActionBarContributor) {
return ((EditorActionBarContributor) contributor).getActionBars().getStatusLineManager();
}
return null;
}
/*
* @see AbstractTextEditor#getAdapter(Class)
*/
public Object getAdapter(Class required) {
if (IContentOutlinePage.class.equals(required)) {
if (fOutlinePage == null)
fOutlinePage= createOutlinePage();
return fOutlinePage;
}
if (required == IShowInTargetList.class) {
return new IShowInTargetList() {
public String[] getShowInTargetIds() {
return new String[] { JavaUI.ID_PACKAGES, IPageLayout.ID_OUTLINE, IPageLayout.ID_RES_NAV };
}
};
}
return super.getAdapter(required);
}
protected void setSelection(ISourceReference reference, boolean moveCursor) {
ISelection selection= getSelectionProvider().getSelection();
if (selection instanceof TextSelection) {
TextSelection textSelection= (TextSelection) selection;
if (textSelection.getOffset() != 0 || textSelection.getLength() != 0)
markInNavigationHistory();
}
if (reference != null) {
StyledText textWidget= null;
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer != null)
textWidget= sourceViewer.getTextWidget();
if (textWidget == null)
return;
try {
ISourceRange range= reference.getSourceRange();
if (range == null)
return;
int offset= range.getOffset();
int length= range.getLength();
if (offset < 0 || length < 0)
return;
setHighlightRange(offset, length, moveCursor);
if (!moveCursor)
return;
offset= -1;
length= -1;
if (reference instanceof IMember) {
range= ((IMember) reference).getNameRange();
if (range != null) {
offset= range.getOffset();
length= range.getLength();
}
} else if (reference instanceof IImportDeclaration) {
String name= ((IImportDeclaration) reference).getElementName();
if (name != null && name.length() > 0) {
String content= reference.getSource();
if (content != null) {
offset= range.getOffset() + content.indexOf(name);
length= name.length();
}
}
} else if (reference instanceof IPackageDeclaration) {
String name= ((IPackageDeclaration) reference).getElementName();
if (name != null && name.length() > 0) {
String content= reference.getSource();
if (content != null) {
offset= range.getOffset() + content.indexOf(name);
length= name.length();
}
}
}
if (offset > -1 && length > 0) {
try {
textWidget.setRedraw(false);
sourceViewer.revealRange(offset, length);
sourceViewer.setSelectedRange(offset, length);
} finally {
textWidget.setRedraw(true);
}
markInNavigationHistory();
}
} catch (JavaModelException x) {
} catch (IllegalArgumentException x) {
}
} else if (moveCursor) {
resetHighlightRange();
markInNavigationHistory();
}
}
public void setSelection(IJavaElement element) {
if (element == null || element instanceof ICompilationUnit || element instanceof IClassFile) {
/*
* If the element is an ICompilationUnit this unit is either the input
* of this editor or not being displayed. In both cases, nothing should
* happened. (http://dev.eclipse.org/bugs/show_bug.cgi?id=5128)
*/
return;
}
IJavaElement corresponding= getCorrespondingElement(element);
if (corresponding instanceof ISourceReference) {
ISourceReference reference= (ISourceReference) corresponding;
// set hightlight range
setSelection(reference, true);
// set outliner selection
if (fOutlinePage != null) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage.select(reference);
fOutlineSelectionChangedListener.install(fOutlinePage);
}
}
}
protected void doSelectionChanged(SelectionChangedEvent event) {
ISourceReference reference= null;
ISelection selection= event.getSelection();
Iterator iter= ((IStructuredSelection) selection).iterator();
while (iter.hasNext()) {
Object o= iter.next();
if (o instanceof ISourceReference) {
reference= (ISourceReference) o;
break;
}
}
if (!isActivePart() && JavaPlugin.getActivePage() != null)
JavaPlugin.getActivePage().bringToTop(this);
setSelection(reference, !isActivePart());
}
/*
* @see AbstractTextEditor#adjustHighlightRange(int, int)
*/
protected void adjustHighlightRange(int offset, int length) {
try {
IJavaElement element= getElementAt(offset);
while (element instanceof ISourceReference) {
ISourceRange range= ((ISourceReference) element).getSourceRange();
if (offset < range.getOffset() + range.getLength() && range.getOffset() < offset + length) {
setHighlightRange(range.getOffset(), range.getLength(), true);
if (fOutlinePage != null) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage.select((ISourceReference) element);
fOutlineSelectionChangedListener.install(fOutlinePage);
}
return;
}
element= element.getParent();
}
} catch (JavaModelException x) {
JavaPlugin.log(x.getStatus());
}
resetHighlightRange();
}
protected boolean isActivePart() {
IWorkbenchPart part= getActivePart();
return part != null && part.equals(this);
}
private boolean isJavaOutlinePageActive() {
IWorkbenchPart part= getActivePart();
return part instanceof ContentOutline && ((ContentOutline)part).getCurrentPage() == fOutlinePage;
}
private IWorkbenchPart getActivePart() {
IWorkbenchWindow window= getSite().getWorkbenchWindow();
IPartService service= window.getPartService();
IWorkbenchPart part= service.getActivePart();
return part;
}
/*
* @see AbstractTextEditor#doSetInput
*/
protected void doSetInput(IEditorInput input) throws CoreException {
super.doSetInput(input);
setOutlinePageInput(fOutlinePage, input);
}
/*
* @see IWorkbenchPart#dispose()
*/
public void dispose() {
if (isBrowserLikeLinks())
disableBrowserLikeLinks();
if (fPropertyChangeListener != null) {
Preferences preferences= JavaCore.getPlugin().getPluginPreferences();
preferences.removePropertyChangeListener(fPropertyChangeListener);
fPropertyChangeListener= null;
}
if (fBracketMatcher != null) {
fBracketMatcher.dispose();
fBracketMatcher= null;
}
if (fSelectionHistory != null) {
fSelectionHistory.dispose();
fSelectionHistory= null;
}
if (fEditorSelectionChangedListener != null) {
fEditorSelectionChangedListener.uninstall(getSelectionProvider());
fEditorSelectionChangedListener= null;
}
super.dispose();
}
protected void createActions() {
super.createActions();
ResourceAction resAction= new AddTaskAction(JavaEditorMessages.getResourceBundle(), "AddTask.", this); //$NON-NLS-1$
resAction.setHelpContextId(IAbstractTextEditorHelpContextIds.ADD_TASK_ACTION);
resAction.setActionDefinitionId(ITextEditorActionDefinitionIds.ADD_TASK);
setAction(ITextEditorActionConstants.ADD_TASK, resAction);
ActionGroup oeg, ovg, jsg, sg;
fActionGroups= new CompositeActionGroup(new ActionGroup[] {
oeg= new OpenEditorActionGroup(this),
sg= new ShowActionGroup(this),
ovg= new OpenViewActionGroup(this),
jsg= new JavaSearchActionGroup(this)
});
fContextMenuGroup= new CompositeActionGroup(new ActionGroup[] {oeg, ovg, sg, jsg});
resAction= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc.", this, ISourceViewer.INFORMATION, true); //$NON-NLS-1$
resAction= new InformationDispatchAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc.", (TextOperationAction) resAction); //$NON-NLS-1$
resAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_JAVADOC);
setAction("ShowJavaDoc", resAction); //$NON-NLS-1$
WorkbenchHelp.setHelp(resAction, IJavaHelpContextIds.SHOW_JAVADOC_ACTION);
Action action= new GotoMatchingBracketAction(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_MATCHING_BRACKET);
setAction(GotoMatchingBracketAction.GOTO_MATCHING_BRACKET, action);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"ShowOutline.", this, JavaSourceViewer.SHOW_OUTLINE, true); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_OUTLINE);
setAction(IJavaEditorActionDefinitionIds.SHOW_OUTLINE, action);
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.SHOW_OUTLINE_ACTION);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"OpenStructure.", this, JavaSourceViewer.OPEN_STRUCTURE, true); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_STRUCTURE);
setAction(IJavaEditorActionDefinitionIds.OPEN_STRUCTURE, action);
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.OPEN_STRUCTURE_ACTION);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"OpenHierarchy.", this, JavaSourceViewer.SHOW_HIERARCHY, true); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_HIERARCHY);
setAction(IJavaEditorActionDefinitionIds.OPEN_HIERARCHY, action);
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.OPEN_HIERARCHY_ACTION);
fSelectionHistory= new SelectionHistory(this);
action= new StructureSelectEnclosingAction(this, fSelectionHistory);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_ENCLOSING);
setAction(StructureSelectionAction.ENCLOSING, action);
action= new StructureSelectNextAction(this, fSelectionHistory);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_NEXT);
setAction(StructureSelectionAction.NEXT, action);
action= new StructureSelectPreviousAction(this, fSelectionHistory);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_PREVIOUS);
setAction(StructureSelectionAction.PREVIOUS, action);
StructureSelectHistoryAction historyAction= new StructureSelectHistoryAction(this, fSelectionHistory);
historyAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_LAST);
setAction(StructureSelectionAction.HISTORY, historyAction);
fSelectionHistory.setHistoryAction(historyAction);
action= GoToNextPreviousMemberAction.newGoToNextMemberAction(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_NEXT_MEMBER);
setAction(GoToNextPreviousMemberAction.NEXT_MEMBER, action);
action= GoToNextPreviousMemberAction.newGoToPreviousMemberAction(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_PREVIOUS_MEMBER);
setAction(GoToNextPreviousMemberAction.PREVIOUS_MEMBER, action);
}
public void updatedTitleImage(Image image) {
setTitleImage(image);
}
/*
* @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
*/
protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
try {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
String property= event.getProperty();
if (PreferenceConstants.EDITOR_TAB_WIDTH.equals(property)) {
Object value= event.getNewValue();
if (value instanceof Integer) {
sourceViewer.getTextWidget().setTabs(((Integer) value).intValue());
} else if (value instanceof String) {
sourceViewer.getTextWidget().setTabs(Integer.parseInt((String) value));
}
return;
}
if (isJavaEditorHoverProperty(property))
updateHoverBehavior();
if (BROWSER_LIKE_LINKS.equals(property)) {
if (isBrowserLikeLinks())
enableBrowserLikeLinks();
else
disableBrowserLikeLinks();
return;
}
if (PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE.equals(property)) {
if ((event.getNewValue() instanceof Boolean) && ((Boolean)event.getNewValue()).booleanValue()) {
fEditorSelectionChangedListener= new EditorSelectionChangedListener();
fEditorSelectionChangedListener.install(getSelectionProvider());
fEditorSelectionChangedListener.selectionChanged();
} else {
fEditorSelectionChangedListener.uninstall(getSelectionProvider());
fEditorSelectionChangedListener= null;
}
return;
}
if (PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE.equals(property)) {
if (event.getNewValue() instanceof Boolean) {
Boolean disable= (Boolean) event.getNewValue();
configureInsertMode(OVERWRITE, !disable.booleanValue());
}
}
} finally {
super.handlePreferenceStoreChanged(event);
}
}
private boolean isJavaEditorHoverProperty(String property) {
return PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS.equals(property);
}
/**
* Return whether the browser like links should be enabled
* according to the preference store settings.
* @return <code>true</code> if the browser like links should be enabled
*/
private boolean isBrowserLikeLinks() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(BROWSER_LIKE_LINKS);
}
/**
* Enables browser like links.
*/
private void enableBrowserLikeLinks() {
if (fMouseListener == null) {
fMouseListener= new MouseClickListener();
fMouseListener.install();
}
}
/**
* Disables browser like links.
*/
private void disableBrowserLikeLinks() {
if (fMouseListener != null) {
fMouseListener.uninstall();
fMouseListener= null;
}
}
/**
* Handles a property change event describing a change
* of the java core's preferences and updates the preference
* related editor properties.
*
* @param event the property change event
*/
protected void handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
if (COMPILER_TASK_TAGS.equals(event.getProperty())) {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer != null && affectsTextPresentation(new PropertyChangeEvent(event.getSource(), event.getProperty(), event.getOldValue(), event.getNewValue())))
sourceViewer.invalidateTextPresentation();
}
}
/**
* Returns a segmentation of the line of the given viewer's input document appropriate for
* bidi rendering. The default implementation returns only the string literals of a java code
* line as segments.
*
* @param viewer the text viewer
* @param lineOffset the offset of the line
* @return the line's bidi segmentation
* @throws BadLocationException in case lineOffset is not valid in document
*/
public static int[] getBidiLineSegments(ITextViewer viewer, int lineOffset) throws BadLocationException {
IDocument document= viewer.getDocument();
if (document == null)
return null;
IRegion line= document.getLineInformationOfOffset(lineOffset);
ITypedRegion[] linePartitioning= TextUtilities.computePartitioning(document, IJavaPartitions.JAVA_PARTITIONING, lineOffset, line.getLength());
List segmentation= new ArrayList();
for (int i= 0; i < linePartitioning.length; i++) {
if (IJavaPartitions.JAVA_STRING.equals(linePartitioning[i].getType()))
segmentation.add(linePartitioning[i]);
}
if (segmentation.size() == 0)
return null;
int size= segmentation.size();
int[] segments= new int[size * 2 + 1];
int j= 0;
for (int i= 0; i < size; i++) {
ITypedRegion segment= (ITypedRegion) segmentation.get(i);
if (i == 0)
segments[j++]= 0;
int offset= segment.getOffset() - lineOffset;
if (offset > segments[j - 1])
segments[j++]= offset;
if (offset + segment.getLength() >= line.getLength())
break;
segments[j++]= offset + segment.getLength();
}
if (j < segments.length) {
int[] result= new int[j];
System.arraycopy(segments, 0, result, 0, j);
segments= result;
}
return segments;
}
/**
* Returns a segmentation of the given line appropriate for bidi rendering. The default
* implementation returns only the string literals of a java code line as segments.
*
* @param lineOffset the offset of the line
* @param line the content of the line
* @return the line's bidi segmentation
*/
protected int[] getBidiLineSegments(int widgetLineOffset, String line) {
if (line != null && line.length() > 0) {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer != null) {
int lineOffset;
if (sourceViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) sourceViewer;
lineOffset= extension.widgetOffset2ModelOffset(widgetLineOffset);
} else {
IRegion visible= sourceViewer.getVisibleRegion();
lineOffset= visible.getOffset() + widgetLineOffset;
}
try {
return getBidiLineSegments(sourceViewer, lineOffset);
} catch (BadLocationException x) {
// don't segment line in this case
}
}
}
return null;
}
/*
* 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);
}
}
/*
* @see org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput()
*/
public Object getViewPartInput() {
return getEditorInput().getAdapter(IJavaElement.class);
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#doSetSelection(ISelection)
*/
protected void doSetSelection(ISelection selection) {
super.doSetSelection(selection);
synchronizeOutlinePageSelection();
}
/*
* @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite)
*/
public void createPartControl(Composite parent) {
super.createPartControl(parent);
Preferences preferences= JavaCore.getPlugin().getPluginPreferences();
preferences.addPropertyChangeListener(fPropertyChangeListener);
IInformationControlCreator informationControlCreator= new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell shell) {
boolean cutDown= false;
int style= cutDown ? SWT.NONE : (SWT.V_SCROLL | SWT.H_SCROLL);
return new DefaultInformationControl(shell, SWT.RESIZE, style, new HTMLTextPresenter(cutDown));
}
};
fInformationPresenter= new InformationPresenter(informationControlCreator);
fInformationPresenter.setSizeConstraints(60, 10, true, true);
fInformationPresenter.install(getSourceViewer());
if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE)) {
fEditorSelectionChangedListener= new EditorSelectionChangedListener();
fEditorSelectionChangedListener.install(getSelectionProvider());
}
if (isBrowserLikeLinks())
enableBrowserLikeLinks();
if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE))
configureInsertMode(OVERWRITE, false);
}
protected void configureSourceViewerDecorationSupport(SourceViewerDecorationSupport support) {
support.setCharacterPairMatcher(fBracketMatcher);
support.setMatchingCharacterPainterPreferenceKeys(MATCHING_BRACKETS, MATCHING_BRACKETS_COLOR);
super.configureSourceViewerDecorationSupport(support);
}
/**
* Jumps to the next enabled annotation according to the given direction.
* An annotation type is enabled if it is configured to be in the
* Next/Previous tool bar drop down menu and if it is checked.
*/
public void gotoAnnotation(boolean forward) {
ISelectionProvider provider= getSelectionProvider();
ITextSelection s= (ITextSelection) provider.getSelection();
Position annotationPosition= new Position(0, 0);
IJavaAnnotation nextAnnotation= getNextAnnotation(s.getOffset(), s.getLength(),forward, annotationPosition);
setStatusLineErrorMessage(null);
if (nextAnnotation != null) {
IMarker marker= null;
if (nextAnnotation instanceof MarkerAnnotation)
marker= ((MarkerAnnotation) nextAnnotation).getMarker();
else {
Iterator e= nextAnnotation.getOverlaidIterator();
if (e != null) {
while (e.hasNext()) {
Object o= e.next();
if (o instanceof MarkerAnnotation) {
marker= ((MarkerAnnotation) o).getMarker();
break;
}
}
}
}
if (marker != null) {
IWorkbenchPage page= getSite().getPage();
IViewPart view= view= page.findView("org.eclipse.ui.views.TaskList"); //$NON-NLS-1$
if (view instanceof TaskList) {
StructuredSelection ss= new StructuredSelection(marker);
((TaskList) view).setSelection(ss, true);
}
}
selectAndReveal(annotationPosition.getOffset(), annotationPosition.getLength());
if (nextAnnotation.isProblem())
setStatusLineErrorMessage(nextAnnotation.getMessage());
}
}
/**
* Jumps to the matching bracket.
*/
public void gotoMatchingBracket() {
ISourceViewer sourceViewer= getSourceViewer();
IDocument document= sourceViewer.getDocument();
if (document == null)
return;
IRegion selection= getSignedSelection(sourceViewer);
int selectionLength= Math.abs(selection.getLength());
if (selectionLength > 1) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.invalidSelection")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
// #26314
int sourceCaretOffset= selection.getOffset() + selection.getLength();
if (isSurroundedByBrackets(document, sourceCaretOffset))
sourceCaretOffset -= selection.getLength();
IRegion region= fBracketMatcher.match(document, sourceCaretOffset);
if (region == null) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.noMatchingBracket")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
int offset= region.getOffset();
int length= region.getLength();
if (length < 1)
return;
int anchor= fBracketMatcher.getAnchor();
// http://dev.eclipse.org/bugs/show_bug.cgi?id=34195
int targetOffset= (JavaPairMatcher.RIGHT == anchor) ? offset + 1: offset + length;
boolean visible= false;
if (sourceViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) sourceViewer;
visible= (extension.modelOffset2WidgetOffset(targetOffset) > -1);
} else {
IRegion visibleRegion= sourceViewer.getVisibleRegion();
// http://dev.eclipse.org/bugs/show_bug.cgi?id=34195
visible= (targetOffset >= visibleRegion.getOffset() && targetOffset <= visibleRegion.getOffset() + visibleRegion.getLength());
}
if (!visible) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.bracketOutsideSelectedElement")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
if (selection.getLength() < 0)
targetOffset -= selection.getLength();
sourceViewer.setSelectedRange(targetOffset, selection.getLength());
sourceViewer.revealRange(targetOffset, selection.getLength());
}
/**
* Ses the given message as error message to this editor's status line.
* @param msg message to be set
*/
protected void setStatusLineErrorMessage(String msg) {
IEditorStatusLine statusLine= (IEditorStatusLine) getAdapter(IEditorStatusLine.class);
if (statusLine != null)
statusLine.setMessage(true, msg, null);
}
private static IRegion getSignedSelection(ITextViewer viewer) {
StyledText text= viewer.getTextWidget();
int caretOffset= text.getCaretOffset();
Point selection= text.getSelection();
// caret left
int offset, length;
if (caretOffset == selection.x) {
offset= selection.y;
length= selection.x - selection.y;
// caret right
} else {
offset= selection.x;
length= selection.y - selection.x;
}
return new Region(offset, length);
}
private static boolean isBracket(char character) {
for (int i= 0; i != BRACKETS.length; ++i)
if (character == BRACKETS[i])
return true;
return false;
}
private static boolean isSurroundedByBrackets(IDocument document, int offset) {
if (offset == 0 || offset == document.getLength())
return false;
try {
return
isBracket(document.getChar(offset - 1)) &&
isBracket(document.getChar(offset));
} catch (BadLocationException e) {
return false;
}
}
private IJavaAnnotation getNextAnnotation(int offset, int length, boolean forward, Position annotationPosition) {
IJavaAnnotation nextAnnotation= null;
Position nextAnnotationPosition= null;
IJavaAnnotation containingAnnotation= null;
Position containingAnnotationPosition= null;
boolean currentAnnotation= false;
IDocument document= getDocumentProvider().getDocument(getEditorInput());
int endOfDocument= document.getLength();
int distance= 0;
IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput());
Iterator e= new JavaAnnotationIterator(model, true);
while (e.hasNext()) {
IJavaAnnotation a= (IJavaAnnotation) e.next();
Preferences workbenchTextEditorPrefStore= Platform.getPlugin("org.eclipse.ui.workbench.texteditor").getPluginPreferences(); //$NON-NLS-1$
Iterator iter= getAnnotationPreferences().getAnnotationPreferences().iterator();
boolean isNavigationTarget= false;
while (iter.hasNext()) {
AnnotationPreference annotationPref= (AnnotationPreference)iter.next();
if (annotationPref.getAnnotationType().equals(a.getAnnotationType())) {
String key;
if (forward)
key= annotationPref.getIsGoToNextNavigationTargetKey();
else
key= annotationPref.getIsGoToPreviousNavigationTargetKey();
if (key != null)
isNavigationTarget= workbenchTextEditorPrefStore.getBoolean(key);
break;
}
annotationPref= null;
}
if (a.hasOverlay() || !isNavigationTarget)
continue;
Position p= model.getPosition((Annotation) a);
if (!(p.includes(offset) || (p.getLength() == 0 && offset == p.offset))) {
int currentDistance= 0;
if (forward) {
currentDistance= p.getOffset() - offset;
if (currentDistance < 0)
currentDistance= endOfDocument - offset + p.getOffset();
} else {
currentDistance= offset - p.getOffset();
if (currentDistance < 0)
currentDistance= offset + endOfDocument - p.getOffset();
}
if (nextAnnotation == null || currentDistance < distance) {
distance= currentDistance;
nextAnnotation= a;
nextAnnotationPosition= p;
}
} else {
if (containingAnnotationPosition == null || containingAnnotationPosition.length > p.length) {
containingAnnotation= a;
containingAnnotationPosition= p;
if (length == p.length)
currentAnnotation= true;
}
}
}
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;
}
/**
* Computes and returns the source reference that includes the caret and
* serves as provider for the outline page selection and the editor range
* indication.
*
* @return the computed source reference
* @since 3.0
*/
protected ISourceReference computeHighlightRangeSourceReference() {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return null;
StyledText styledText= sourceViewer.getTextWidget();
if (styledText == null)
return null;
int caret= 0;
if (sourceViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3)sourceViewer;
caret= extension.widgetOffset2ModelOffset(styledText.getCaretOffset());
} else {
int offset= sourceViewer.getVisibleRegion().getOffset();
caret= offset + styledText.getCaretOffset();
}
IJavaElement element= getElementAt(caret, false);
if ( !(element instanceof ISourceReference))
return null;
if (element.getElementType() == IJavaElement.IMPORT_DECLARATION) {
IImportDeclaration declaration= (IImportDeclaration) element;
IImportContainer container= (IImportContainer) declaration.getParent();
ISourceRange srcRange= null;
try {
srcRange= container.getSourceRange();
} catch (JavaModelException e) {
}
if (srcRange != null && srcRange.getOffset() == caret)
return container;
}
return (ISourceReference) element;
}
/**
* Returns the most narrow java element including the given offset.
*
* @param offset the offset inside of the requested element
* @param reconcile <code>true</code> if editor input should be reconciled in advance
* @return the most narrow java element
* @since 3.0
*/
protected IJavaElement getElementAt(int offset, boolean reconcile) {
return getElementAt(offset);
}
/*
* @see org.eclipse.ui.texteditor.ExtendedTextEditor#createChangeHover()
*/
protected LineChangeHover createChangeHover() {
return new JavaChangeHover(IJavaPartitions.JAVA_PARTITIONING);
}
protected boolean isPrefQuickDiffAlwaysOn() {
return false; // never show change ruler for the non-editable java editor. Overridden in subclasses like CompilationUnitEditor
}
}
|
40,785 |
Bug 40785 [plan item] Overview ruler improvements
|
- navigation from ruler to editor - hovering over header area shows number of errors/warning (header annotations in general)
|
resolved fixed
|
0c04535
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-22T09:43:23Z | 2003-07-25T16:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/filebuffers/CompilationUnitDocumentProvider2.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.javaeditor.filebuffers;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IMarkerDelta;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
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.swt.widgets.Display;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.ListenerList;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DefaultLineTracker;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ILineTracker;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.AnnotationModelEvent;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.IAnnotationModelListener;
import org.eclipse.jface.text.source.IAnnotationModelListenerExtension;
import org.eclipse.ui.editors.text.TextFileDocumentProvider;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.texteditor.AbstractMarkerAnnotationModel;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.ui.texteditor.MarkerAnnotation;
import org.eclipse.ui.texteditor.ResourceMarkerAnnotationModel;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IProblemRequestor;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitAnnotationModelEvent;
import org.eclipse.jdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider;
import org.eclipse.jdt.internal.ui.javaeditor.IJavaAnnotation;
import org.eclipse.jdt.internal.ui.javaeditor.ISavePolicy;
import org.eclipse.jdt.internal.ui.javaeditor.JavaMarkerAnnotation;
import org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionProcessor;
import org.eclipse.jdt.internal.ui.text.java.IProblemRequestorExtension;
public class CompilationUnitDocumentProvider2 extends TextFileDocumentProvider implements ICompilationUnitDocumentProvider {
/**
* Bundle of all required informations to allow working copy management.
*/
static protected class CompilationUnitInfo extends FileInfo {
public ICompilationUnit fCopy;
}
/**
* Annotation representating an <code>IProblem</code>.
*/
static protected class ProblemAnnotation extends Annotation implements IJavaAnnotation {
private static final String TASK_ANNOTATION_TYPE= "org.eclipse.ui.workbench.texteditor.task"; //$NON-NLS-1$
private static final String ERROR_ANNOTATION_TYPE= "org.eclipse.ui.workbench.texteditor.error"; //$NON-NLS-1$
private static final String WARNING_ANNOTATION_TYPE= "org.eclipse.ui.workbench.texteditor.warning"; //$NON-NLS-1$
private static final String INFO_ANNOTATION_TYPE= "org.eclipse.ui.workbench.texteditor.info"; //$NON-NLS-1$
private static Image fgQuickFixImage;
private static Image fgQuickFixErrorImage;
private static boolean fgQuickFixImagesInitialized= false;
private ICompilationUnit fCompilationUnit;
private List fOverlaids;
private IProblem fProblem;
private Image fImage;
private boolean fQuickFixImagesInitialized= false;
private String fType;
public ProblemAnnotation(IProblem problem, ICompilationUnit cu) {
fProblem= problem;
fCompilationUnit= cu;
setLayer(MarkerAnnotation.PROBLEM_LAYER + 1);
if (IProblem.Task == fProblem.getID())
fType= TASK_ANNOTATION_TYPE;
else if (fProblem.isWarning())
fType= WARNING_ANNOTATION_TYPE;
else if (fProblem.isError())
fType= ERROR_ANNOTATION_TYPE;
else
fType= INFO_ANNOTATION_TYPE;
}
private void initializeImages() {
// http://bugs.eclipse.org/bugs/show_bug.cgi?id=18936
if (!fQuickFixImagesInitialized) {
if (isProblem() && indicateQuixFixableProblems() && JavaCorrectionProcessor.hasCorrections(this)) { // no light bulb for tasks
if (!fgQuickFixImagesInitialized) {
fgQuickFixImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_FIXABLE_PROBLEM);
fgQuickFixErrorImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_FIXABLE_ERROR);
fgQuickFixImagesInitialized= true;
}
if (ERROR_ANNOTATION_TYPE.equals(fType))
fImage= fgQuickFixErrorImage;
else
fImage= fgQuickFixImage;
}
fQuickFixImagesInitialized= true;
}
}
private boolean indicateQuixFixableProblems() {
return PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_CORRECTION_INDICATION);
}
/*
* @see Annotation#paint
*/
public void paint(GC gc, Canvas canvas, Rectangle r) {
initializeImages();
if (fImage != null)
drawImage(fImage, gc, canvas, r, SWT.CENTER, SWT.TOP);
}
/*
* @see IJavaAnnotation#getImage(Display)
*/
public Image getImage(Display display) {
initializeImages();
return fImage;
}
/*
* @see IJavaAnnotation#getMessage()
*/
public String getMessage() {
return fProblem.getMessage();
}
/*
* @see IJavaAnnotation#isTemporary()
*/
public boolean isTemporary() {
return true;
}
/*
* @see IJavaAnnotation#getArguments()
*/
public String[] getArguments() {
return isProblem() ? fProblem.getArguments() : null;
}
/*
* @see IJavaAnnotation#getId()
*/
public int getId() {
return fProblem.getID();
}
/*
* @see IJavaAnnotation#isProblem()
*/
public boolean isProblem() {
return WARNING_ANNOTATION_TYPE.equals(fType) || ERROR_ANNOTATION_TYPE.equals(fType);
}
/*
* @see IJavaAnnotation#isRelevant()
*/
public boolean isRelevant() {
return true;
}
/*
* @see IJavaAnnotation#hasOverlay()
*/
public boolean hasOverlay() {
return false;
}
/*
* @see IJavaAnnotation#addOverlaid(IJavaAnnotation)
*/
public void addOverlaid(IJavaAnnotation annotation) {
if (fOverlaids == null)
fOverlaids= new ArrayList(1);
fOverlaids.add(annotation);
}
/*
* @see IJavaAnnotation#removeOverlaid(IJavaAnnotation)
*/
public void removeOverlaid(IJavaAnnotation annotation) {
if (fOverlaids != null) {
fOverlaids.remove(annotation);
if (fOverlaids.size() == 0)
fOverlaids= null;
}
}
/*
* @see IJavaAnnotation#getOverlaidIterator()
*/
public Iterator getOverlaidIterator() {
if (fOverlaids != null)
return fOverlaids.iterator();
return null;
}
public String getAnnotationType() {
return fType;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.javaeditor.IJavaAnnotation#getCompilationUnit()
*/
public ICompilationUnit getCompilationUnit() {
return fCompilationUnit;
}
}
/**
* Internal structure for mapping positions to some value.
* The reason for this specific structure is that positions can
* change over time. Thus a lookup is based on value and not
* on hash value.
*/
protected static class ReverseMap {
static class Entry {
Position fPosition;
Object fValue;
}
private List fList= new ArrayList(2);
private int fAnchor= 0;
public ReverseMap() {
}
public Object get(Position position) {
Entry entry;
// behind anchor
int length= fList.size();
for (int i= fAnchor; i < length; i++) {
entry= (Entry) fList.get(i);
if (entry.fPosition.equals(position)) {
fAnchor= i;
return entry.fValue;
}
}
// before anchor
for (int i= 0; i < fAnchor; i++) {
entry= (Entry) fList.get(i);
if (entry.fPosition.equals(position)) {
fAnchor= i;
return entry.fValue;
}
}
return null;
}
private int getIndex(Position position) {
Entry entry;
int length= fList.size();
for (int i= 0; i < length; i++) {
entry= (Entry) fList.get(i);
if (entry.fPosition.equals(position))
return i;
}
return -1;
}
public void put(Position position, Object value) {
int index= getIndex(position);
if (index == -1) {
Entry entry= new Entry();
entry.fPosition= position;
entry.fValue= value;
fList.add(entry);
} else {
Entry entry= (Entry) fList.get(index);
entry.fValue= value;
}
}
public void remove(Position position) {
int index= getIndex(position);
if (index > -1)
fList.remove(index);
}
public void clear() {
fList.clear();
}
}
/**
* Annotation model dealing with java marker annotations and temporary problems.
* Also acts as problem requestor for its compilation unit. Initialiy inactive. Must explicitly be
* activated.
*/
protected static class CompilationUnitAnnotationModel extends ResourceMarkerAnnotationModel implements IProblemRequestor, IProblemRequestorExtension {
private ICompilationUnit fCompilationUnit;
private List fCollectedProblems;
private List fGeneratedAnnotations;
private IProgressMonitor fProgressMonitor;
private boolean fIsActive= false;
private ReverseMap fReverseMap= new ReverseMap();
private List fPreviouslyOverlaid= null;
private List fCurrentlyOverlaid= new ArrayList();
private CompilationUnitAnnotationModelEvent fCurrentEvent;
public CompilationUnitAnnotationModel(IResource resource) {
super(resource);
fCurrentEvent= new CompilationUnitAnnotationModelEvent(this, getResource());
}
public void setCompilationUnit(ICompilationUnit unit) {
fCompilationUnit= unit;
}
protected MarkerAnnotation createMarkerAnnotation(IMarker marker) {
return new JavaMarkerAnnotation(marker);
}
protected Position createPositionFromProblem(IProblem problem) {
int start= problem.getSourceStart();
if (start < 0)
return null;
int length= problem.getSourceEnd() - problem.getSourceStart() + 1;
if (length < 0)
return null;
return new Position(start, length);
}
protected void update(IMarkerDelta[] markerDeltas) {
super.update(markerDeltas);
if (markerDeltas != null && markerDeltas.length > 0) {
try {
if (fCompilationUnit != null)
fCompilationUnit.reconcile(true, null);
} catch (JavaModelException ex) {
if (!ex.isDoesNotExist())
handleCoreException(ex, ex.getMessage());
}
}
}
/*
* @see IProblemRequestor#beginReporting()
*/
public void beginReporting() {
if (fCompilationUnit != null && fCompilationUnit.getJavaProject().isOnClasspath(fCompilationUnit))
fCollectedProblems= new ArrayList();
else
fCollectedProblems= null;
}
/*
* @see IProblemRequestor#acceptProblem(IProblem)
*/
public void acceptProblem(IProblem problem) {
if (isActive())
fCollectedProblems.add(problem);
}
/*
* @see IProblemRequestor#endReporting()
*/
public void endReporting() {
if (!isActive())
return;
if (fProgressMonitor != null && fProgressMonitor.isCanceled())
return;
boolean isCanceled= false;
boolean temporaryProblemsChanged= false;
synchronized (fAnnotations) {
fPreviouslyOverlaid= fCurrentlyOverlaid;
fCurrentlyOverlaid= new ArrayList();
if (fGeneratedAnnotations.size() > 0) {
temporaryProblemsChanged= true;
removeAnnotations(fGeneratedAnnotations, false, true);
fGeneratedAnnotations.clear();
}
if (fCollectedProblems != null && fCollectedProblems.size() > 0) {
Iterator e= fCollectedProblems.iterator();
while (e.hasNext()) {
IProblem problem= (IProblem) e.next();
if (fProgressMonitor != null && fProgressMonitor.isCanceled()) {
isCanceled= true;
break;
}
Position position= createPositionFromProblem(problem);
if (position != null) {
try {
ProblemAnnotation annotation= new ProblemAnnotation(problem, fCompilationUnit);
addAnnotation(annotation, position, false);
overlayMarkers(position, annotation);
fGeneratedAnnotations.add(annotation);
temporaryProblemsChanged= true;
} catch (BadLocationException x) {
// ignore invalid position
}
}
}
fCollectedProblems.clear();
}
removeMarkerOverlays(isCanceled);
fPreviouslyOverlaid.clear();
fPreviouslyOverlaid= null;
}
if (temporaryProblemsChanged)
fireModelChanged();
}
private void removeMarkerOverlays(boolean isCanceled) {
if (isCanceled) {
fCurrentlyOverlaid.addAll(fPreviouslyOverlaid);
} else if (fPreviouslyOverlaid != null) {
Iterator e= fPreviouslyOverlaid.iterator();
while (e.hasNext()) {
JavaMarkerAnnotation annotation= (JavaMarkerAnnotation) e.next();
annotation.setOverlay(null);
}
}
}
/**
* Overlays value with problem annotation.
* @param problemAnnotation
*/
private void setOverlay(Object value, ProblemAnnotation problemAnnotation) {
if (value instanceof JavaMarkerAnnotation) {
JavaMarkerAnnotation annotation= (JavaMarkerAnnotation) value;
if (annotation.isProblem()) {
annotation.setOverlay(problemAnnotation);
fPreviouslyOverlaid.remove(annotation);
fCurrentlyOverlaid.add(annotation);
}
}
}
private void overlayMarkers(Position position, ProblemAnnotation problemAnnotation) {
Object value= getAnnotations(position);
if (value instanceof List) {
List list= (List) value;
for (Iterator e = list.iterator(); e.hasNext();)
setOverlay(e.next(), problemAnnotation);
} else {
setOverlay(value, problemAnnotation);
}
}
/**
* Tells this annotation model to collect temporary problems from now on.
*/
private void startCollectingProblems() {
fCollectedProblems= new ArrayList();
fGeneratedAnnotations= new ArrayList();
}
/**
* Tells this annotation model to no longer collect temporary problems.
*/
private void stopCollectingProblems() {
if (fGeneratedAnnotations != null) {
removeAnnotations(fGeneratedAnnotations, true, true);
fGeneratedAnnotations.clear();
}
fCollectedProblems= null;
fGeneratedAnnotations= null;
}
/*
* @see AnnotationModel#fireModelChanged()
*/
protected void fireModelChanged() {
fireModelChanged(fCurrentEvent);
fCurrentEvent= new CompilationUnitAnnotationModelEvent(this, getResource());
}
/*
* @see IProblemRequestor#isActive()
*/
public boolean isActive() {
return fIsActive && (fCollectedProblems != null);
}
/*
* @see IProblemRequestorExtension#setProgressMonitor(IProgressMonitor)
*/
public void setProgressMonitor(IProgressMonitor monitor) {
fProgressMonitor= monitor;
}
/*
* @see IProblemRequestorExtension#setIsActive(boolean)
*/
public void setIsActive(boolean isActive) {
if (fIsActive != isActive) {
fIsActive= isActive;
if (fIsActive)
startCollectingProblems();
else
stopCollectingProblems();
}
}
private Object getAnnotations(Position position) {
return fReverseMap.get(position);
}
/*
* @see AnnotationModel#addAnnotation(Annotation, Position, boolean)
*/
protected void addAnnotation(Annotation annotation, Position position, boolean fireModelChanged) throws BadLocationException {
super.addAnnotation(annotation, position, fireModelChanged);
fCurrentEvent.annotationAdded(annotation);
Object cached= fReverseMap.get(position);
if (cached == null)
fReverseMap.put(position, annotation);
else if (cached instanceof List) {
List list= (List) cached;
list.add(annotation);
} else if (cached instanceof Annotation) {
List list= new ArrayList(2);
list.add(cached);
list.add(annotation);
fReverseMap.put(position, list);
}
}
/*
* @see AnnotationModel#removeAllAnnotations(boolean)
*/
protected void removeAllAnnotations(boolean fireModelChanged) {
for (Iterator iter= getAnnotationIterator(); iter.hasNext();) {
fCurrentEvent.annotationRemoved((Annotation) iter.next());
}
super.removeAllAnnotations(fireModelChanged);
fReverseMap.clear();
}
/*
* @see AnnotationModel#removeAnnotation(Annotation, boolean)
*/
protected void removeAnnotation(Annotation annotation, boolean fireModelChanged) {
fCurrentEvent.annotationRemoved(annotation);
Position position= getPosition(annotation);
Object cached= fReverseMap.get(position);
if (cached instanceof List) {
List list= (List) cached;
list.remove(annotation);
if (list.size() == 1) {
fReverseMap.put(position, list.get(0));
list.clear();
}
} else if (cached instanceof Annotation) {
fReverseMap.remove(position);
}
super.removeAnnotation(annotation, fireModelChanged);
}
}
protected static class GlobalAnnotationModelListener implements IAnnotationModelListener, IAnnotationModelListenerExtension {
private ListenerList fListenerList;
public GlobalAnnotationModelListener() {
fListenerList= new ListenerList();
}
/**
* @see IAnnotationModelListener#modelChanged(IAnnotationModel)
*/
public void modelChanged(IAnnotationModel model) {
Object[] listeners= fListenerList.getListeners();
for (int i= 0; i < listeners.length; i++) {
((IAnnotationModelListener) listeners[i]).modelChanged(model);
}
}
/**
* @see IAnnotationModelListenerExtension#modelChanged(AnnotationModelEvent)
*/
public void modelChanged(AnnotationModelEvent event) {
Object[] listeners= fListenerList.getListeners();
for (int i= 0; i < listeners.length; i++) {
Object curr= listeners[i];
if (curr instanceof IAnnotationModelListenerExtension) {
((IAnnotationModelListenerExtension) curr).modelChanged(event);
}
}
}
public void addListener(IAnnotationModelListener listener) {
fListenerList.add(listener);
}
public void removeListener(IAnnotationModelListener listener) {
fListenerList.remove(listener);
}
}
/** Preference key for temporary problems */
private final static String HANDLE_TEMPORARY_PROBLEMS= PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS;
/** Indicates whether the save has been initialized by this provider */
private boolean fIsAboutToSave= false;
/** The save policy used by this provider */
private ISavePolicy fSavePolicy;
/** Internal property changed listener */
private IPropertyChangeListener fPropertyListener;
/** Annotation model listener added to all created CU annotation models */
private GlobalAnnotationModelListener fGlobalAnnotationModelListener;
/** Parent document provider for file editor inputs. */
private IDocumentProvider fParentProviderForFileResources;
/** Parent document provider for storage editor inputs (non-resources). */
private IDocumentProvider fParentProviderForNonResources;
/**
* Constructor
*/
public CompilationUnitDocumentProvider2() {
fGlobalAnnotationModelListener= new GlobalAnnotationModelListener();
fParentProviderForFileResources= new TextFileDocumentProvider();
fParentProviderForNonResources= new JavaStorageDocumentProvider();
fPropertyListener= new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
if (HANDLE_TEMPORARY_PROBLEMS.equals(event.getProperty()))
enableHandlingTemporaryProblems();
}
};
JavaPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(fPropertyListener);
}
/**
* Creates a compilation unit from the given file.
*
* @param file the file from which to create the compilation unit
*/
protected ICompilationUnit createCompilationUnit(IFile file) {
Object element= JavaCore.create(file);
if (element instanceof ICompilationUnit)
return (ICompilationUnit) element;
return null;
}
/*
* @see org.eclipse.ui.editors.text.TextFileDocumentProvider#createEmptyFileInfo()
*/
protected FileInfo createEmptyFileInfo() {
return new CompilationUnitInfo();
}
/*
* @see org.eclipse.ui.editors.text.TextFileDocumentProvider#createAnnotationModel(org.eclipse.core.resources.IFile)
*/
protected IAnnotationModel createAnnotationModel(IFile file) {
return new CompilationUnitAnnotationModel(file);
}
/*
* @see org.eclipse.ui.editors.text.TextFileDocumentProvider#createFileInfo(java.lang.Object)
*/
protected FileInfo createFileInfo(Object element) throws CoreException {
if (!(element instanceof IFileEditorInput))
return null;
IFileEditorInput input= (IFileEditorInput) element;
ICompilationUnit original= createCompilationUnit(input.getFile());
if (original == null)
return null;
FileInfo info= super.createFileInfo(element);
if (!(info instanceof CompilationUnitInfo))
return null;
CompilationUnitInfo cuInfo= (CompilationUnitInfo) info;
IProblemRequestor requestor= cuInfo.fModel instanceof IProblemRequestor ? (IProblemRequestor) cuInfo.fModel : null;
if (JavaPlugin.USE_WORKING_COPY_OWNERS) {
original.becomeWorkingCopy(requestor, getProgressMonitor());
cuInfo.fCopy= original;
} else {
cuInfo.fCopy= (ICompilationUnit) original.getSharedWorkingCopy(getProgressMonitor(), JavaPlugin.getDefault().getBufferFactory(), requestor);
}
if (cuInfo.fModel instanceof CompilationUnitAnnotationModel) {
CompilationUnitAnnotationModel model= (CompilationUnitAnnotationModel) cuInfo.fModel;
model.setCompilationUnit(cuInfo.fCopy);
}
cuInfo.fModel.addAnnotationModelListener(fGlobalAnnotationModelListener);
if (requestor instanceof IProblemRequestorExtension) {
IProblemRequestorExtension extension= (IProblemRequestorExtension) requestor;
extension.setIsActive(isHandlingTemporaryProblems());
}
return cuInfo;
}
/*
* @see org.eclipse.ui.editors.text.TextFileDocumentProvider#disposeFileInfo(java.lang.Object, org.eclipse.ui.editors.text.TextFileDocumentProvider.FileInfo)
*/
protected void disposeFileInfo(Object element, FileInfo info) {
if (info instanceof CompilationUnitInfo) {
CompilationUnitInfo cuInfo= (CompilationUnitInfo) info;
if (JavaPlugin.USE_WORKING_COPY_OWNERS) {
try {
cuInfo.fCopy.discardWorkingCopy();
} catch (JavaModelException x) {
handleCoreException(x, x.getMessage());
}
} else {
cuInfo.fCopy.destroy();
}
cuInfo.fModel.removeAnnotationModelListener(fGlobalAnnotationModelListener);
}
super.disposeFileInfo(element, info);
}
/*
* @see org.eclipse.ui.editors.text.TextFileDocumentProvider#saveDocument(org.eclipse.core.runtime.IProgressMonitor, java.lang.Object, org.eclipse.jface.text.IDocument, boolean)
*/
public void saveDocument(IProgressMonitor monitor, Object element, IDocument ignore, boolean overwrite) throws CoreException {
FileInfo fileInfo= getFileInfo(element);
if (fileInfo instanceof CompilationUnitInfo) {
CompilationUnitInfo info= (CompilationUnitInfo) fileInfo;
// update structure, assumes lock on info.fCopy
info.fCopy.reconcile();
ICompilationUnit original= (ICompilationUnit) info.fCopy.getOriginalElement();
IResource resource= original.getResource();
if (resource == null) {
// underlying resource has been deleted, just recreate file, ignore the rest
super.saveDocument(monitor, element, ignore, overwrite);
return;
}
if (fSavePolicy != null)
fSavePolicy.preSave(info.fCopy);
try {
fIsAboutToSave= true;
// commit working copy
if (JavaPlugin.USE_WORKING_COPY_OWNERS) {
info.fCopy.commitWorkingCopy(overwrite, monitor);
} else {
info.fCopy.commit(overwrite, monitor);
// next call required as commiting working copies changed to no longer walk through the right buffer
saveDocumentContent(monitor, element, ignore, overwrite);
}
} catch (CoreException x) {
// inform about the failure
fireElementStateChangeFailed(element);
throw x;
} catch (RuntimeException x) {
// inform about the failure
fireElementStateChangeFailed(element);
throw x;
} finally {
fIsAboutToSave= false;
}
// If here, the dirty state of the editor will change to "not dirty".
// Thus, the state changing flag will be reset.
AbstractMarkerAnnotationModel model= (AbstractMarkerAnnotationModel) info.fModel;
IDocument document= getDocument(element);
model.updateMarkers(document);
if (fSavePolicy != null) {
ICompilationUnit unit= fSavePolicy.postSave(original);
if (unit != null) {
IResource r= unit.getResource();
IMarker[] markers= r.findMarkers(IMarker.MARKER, true, IResource.DEPTH_ZERO);
if (markers != null && markers.length > 0) {
for (int i= 0; i < markers.length; i++)
model.updateMarker(markers[i], document, null);
}
}
}
} else {
super.saveDocument(monitor, element, ignore, overwrite);
}
}
/**
* Returns the preference whether handling temporary problems is enabled.
*/
protected boolean isHandlingTemporaryProblems() {
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
return store.getBoolean(HANDLE_TEMPORARY_PROBLEMS);
}
/**
* Switches the state of problem acceptance according to the value in the preference store.
*/
protected void enableHandlingTemporaryProblems() {
boolean enable= isHandlingTemporaryProblems();
for (Iterator iter= getFileInfosIterator(); iter.hasNext();) {
FileInfo info= (FileInfo) iter.next();
if (info.fModel instanceof IProblemRequestorExtension) {
IProblemRequestorExtension extension= (IProblemRequestorExtension) info.fModel;
extension.setIsActive(enable);
}
}
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#setSavePolicy(org.eclipse.jdt.internal.ui.javaeditor.ISavePolicy)
*/
public void setSavePolicy(ISavePolicy savePolicy) {
fSavePolicy= savePolicy;
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#addGlobalAnnotationModelListener(org.eclipse.jface.text.source.IAnnotationModelListener)
*/
public void addGlobalAnnotationModelListener(IAnnotationModelListener listener) {
fGlobalAnnotationModelListener.addListener(listener);
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#removeGlobalAnnotationModelListener(org.eclipse.jface.text.source.IAnnotationModelListener)
*/
public void removeGlobalAnnotationModelListener(IAnnotationModelListener listener) {
fGlobalAnnotationModelListener.removeListener(listener);
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#getWorkingCopy(java.lang.Object)
*/
public ICompilationUnit getWorkingCopy(Object element) {
FileInfo fileInfo= getFileInfo(element);
if (fileInfo instanceof CompilationUnitInfo) {
CompilationUnitInfo info= (CompilationUnitInfo) fileInfo;
return info.fCopy;
}
return null;
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#shutdown()
*/
public void shutdown() {
JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(fPropertyListener);
Iterator e= getConnectedElementsIterator();
while (e.hasNext())
disconnect(e.next());
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#saveDocumentContent(org.eclipse.core.runtime.IProgressMonitor, java.lang.Object, org.eclipse.jface.text.IDocument, boolean)
*/
public void saveDocumentContent(IProgressMonitor monitor, Object element, IDocument document, boolean overwrite) throws CoreException {
if (!fIsAboutToSave)
return;
super.saveDocument(monitor, element, document, overwrite);
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#createLineTracker(java.lang.Object)
*/
public ILineTracker createLineTracker(Object element) {
return new DefaultLineTracker();
}
/*
* @see IDocumentProvider#connect(Object)
*/
public void connect(Object element) throws CoreException {
setParentDocumentProvider(getParentProvider(element));
super.connect(element);
}
/**
* Returns the parent provider for the given element.
*
* @param element the element
* @return the parent document provider
*/
private IDocumentProvider getParentProvider(Object element) {
if (element instanceof IFileEditorInput)
return fParentProviderForFileResources;
else
return fParentProviderForNonResources;
}
}
|
38,357 |
Bug 38357 Reorder suggestion for moving class to new package [quick fix]
|
When the directory structure and package name of a class doesn't match, a suggestion offers two choices: o Move to new director corresponding to package name o Add/change package declaration to match directory structure However, when a class with no package is moved into a directory, the suggestions are prompted as: o Move to (default package) o Add package statement new.directory I'd suggest that (at least in the case of default packages) the 'add package statement' should come before the 'move to new directory'. Further, I think it has advantages for situations where bulk renaming of packages occur (e.g. the name of the project has changed) and it is easier to rename the directory and then perform the first suggestion, which in this case is unlikely to be moving it back to the original package. I'd like to see these two suggestions reversed in order, so that the package statement reflects the directory first, and then the suggestion to move the class to a new package second.
|
verified fixed
|
b3c3163
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-23T15:23:00Z | 2003-06-03T11:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/ReorgCorrectionsSubProcessor.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text.correction;
import java.util.Collection;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.swt.graphics.Image;
import org.eclipse.jface.text.IDocument;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IPackageDeclaration;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaConventions;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.ImportDeclaration;
import org.eclipse.jdt.ui.actions.OrganizeImportsAction;
import org.eclipse.jdt.ui.text.java.IInvocationContext;
import org.eclipse.jdt.ui.text.java.IProblemLocation;
import org.eclipse.jdt.internal.corext.dom.ASTNodes;
import org.eclipse.jdt.internal.corext.dom.ASTRewrite;
import org.eclipse.jdt.internal.corext.refactoring.CompositeChange;
import org.eclipse.jdt.internal.corext.refactoring.changes.CreatePackageChange;
import org.eclipse.jdt.internal.corext.refactoring.changes.MoveCompilationUnitChange;
import org.eclipse.jdt.internal.corext.refactoring.changes.RenameCompilationUnitChange;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor;
public class ReorgCorrectionsSubProcessor {
public static void getWrongTypeNameProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
String[] args= problem.getProblemArguments();
if (args.length == 2) {
ICompilationUnit cu= context.getCompilationUnit();
boolean isLinked= JavaModelUtil.toOriginal(cu).getResource().isLinked();
// rename type
proposals.add(new CorrectMainTypeNameProposal(cu, args[1], 5));
String newCUName= args[1] + ".java"; //$NON-NLS-1$
ICompilationUnit newCU= ((IPackageFragment) (cu.getParent())).getCompilationUnit(newCUName);
if (!newCU.exists() && !isLinked && !JavaConventions.validateCompilationUnitName(newCUName).matches(IStatus.ERROR)) {
RenameCompilationUnitChange change= new RenameCompilationUnitChange(cu, newCUName);
// rename cu
String label= CorrectionMessages.getFormattedString("ReorgCorrectionsSubProcessor.renamecu.description", newCUName); //$NON-NLS-1$
proposals.add(new ChangeCorrectionProposal(label, change, 6, JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_RENAME)));
}
}
}
public static void getWrongPackageDeclNameProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
String[] args= problem.getProblemArguments();
if (args.length == 1) {
ICompilationUnit cu= context.getCompilationUnit();
boolean isLinked= JavaModelUtil.toOriginal(cu).getResource().isLinked();
// correct pack decl
proposals.add(new CorrectPackageDeclarationProposal(cu, problem, 5));
// move to pack
IPackageDeclaration[] packDecls= cu.getPackageDeclarations();
String newPackName= packDecls.length > 0 ? packDecls[0].getElementName() : ""; //$NON-NLS-1$
IPackageFragmentRoot root= JavaModelUtil.getPackageFragmentRoot(cu);
IPackageFragment newPack= root.getPackageFragment(newPackName);
ICompilationUnit newCU= newPack.getCompilationUnit(cu.getElementName());
if (!newCU.exists() && !isLinked) {
String label;
if (newPack.isDefaultPackage()) {
label= CorrectionMessages.getFormattedString("ReorgCorrectionsSubProcessor.movecu.default.description", cu.getElementName()); //$NON-NLS-1$
} else {
label= CorrectionMessages.getFormattedString("ReorgCorrectionsSubProcessor.movecu.description", new Object[] { cu.getElementName(), newPack.getElementName() }); //$NON-NLS-1$
}
CompositeChange composite= new CompositeChange(label);
composite.add(new CreatePackageChange(newPack));
composite.add(new MoveCompilationUnitChange(cu, newPack));
proposals.add(new ChangeCorrectionProposal(label, composite, 6, JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_MOVE)));
}
}
}
public static void removeImportStatementProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
final ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
if (selectedNode != null) {
ASTNode node= ASTNodes.getParent(selectedNode, ASTNode.IMPORT_DECLARATION);
if (node instanceof ImportDeclaration) {
ASTRewrite rewrite= new ASTRewrite(node.getParent());
rewrite.markAsRemoved(node);
String label= CorrectionMessages.getString("ReorgCorrectionsSubProcessor.unusedimport.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_DELETE_IMPORT);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 6, image);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
String name= CorrectionMessages.getString("ReorgCorrectionsSubProcessor.organizeimports.description"); //$NON-NLS-1$
ChangeCorrectionProposal proposal= new ChangeCorrectionProposal(name, null, 5) {
public void apply(IDocument document) {
IEditorInput input= new FileEditorInput((IFile) JavaModelUtil.toOriginal(cu).getResource());
IWorkbenchPage p= JavaPlugin.getActivePage();
if (p == null) {
return;
}
IEditorPart part= p.findEditor(input);
if (part instanceof JavaEditor) {
OrganizeImportsAction action= new OrganizeImportsAction((JavaEditor) part);
action.run(cu);
}
}
};
proposals.add(proposal);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.