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,044
Bug 41044 quickfix "add catch block to surrounding try" does not comply with code formatter [quick fix]
i have selected the code formatter option: "insert a new line in control statements" which puts catch blocks on new lines however if you use the "add catch to surrounding try" quickfix on the file below the generated catch block will not be on a new line! -----------------------------------A.java------------------------- import java.io.FileNotFoundException; import java.io.IOException; public class A { void method() { try { if(false) { throw new FileNotFoundException(); } throw new IOException(); } catch (final FileNotFoundException e) { e.printStackTrace(); } } }
resolved fixed
47aefad
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-08-23T16:07:40Z
2003-08-01T09:26:40Z
org.eclipse.jdt.ui/core
41,044
Bug 41044 quickfix "add catch block to surrounding try" does not comply with code formatter [quick fix]
i have selected the code formatter option: "insert a new line in control statements" which puts catch blocks on new lines however if you use the "add catch to surrounding try" quickfix on the file below the generated catch block will not be on a new line! -----------------------------------A.java------------------------- import java.io.FileNotFoundException; import java.io.IOException; public class A { void method() { try { if(false) { throw new FileNotFoundException(); } throw new IOException(); } catch (final FileNotFoundException e) { e.printStackTrace(); } } }
resolved fixed
47aefad
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-08-23T16:07:40Z
2003-08-01T09:26:40Z
extension/org/eclipse/jdt/internal/corext/dom/ASTRewriteAnalyzer.java
41,044
Bug 41044 quickfix "add catch block to surrounding try" does not comply with code formatter [quick fix]
i have selected the code formatter option: "insert a new line in control statements" which puts catch blocks on new lines however if you use the "add catch to surrounding try" quickfix on the file below the generated catch block will not be on a new line! -----------------------------------A.java------------------------- import java.io.FileNotFoundException; import java.io.IOException; public class A { void method() { try { if(false) { throw new FileNotFoundException(); } throw new IOException(); } catch (final FileNotFoundException e) { e.printStackTrace(); } } }
resolved fixed
47aefad
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-08-23T16:07:40Z
2003-08-01T09:26:40Z
org.eclipse.jdt.ui/core
41,044
Bug 41044 quickfix "add catch block to surrounding try" does not comply with code formatter [quick fix]
i have selected the code formatter option: "insert a new line in control statements" which puts catch blocks on new lines however if you use the "add catch to surrounding try" quickfix on the file below the generated catch block will not be on a new line! -----------------------------------A.java------------------------- import java.io.FileNotFoundException; import java.io.IOException; public class A { void method() { try { if(false) { throw new FileNotFoundException(); } throw new IOException(); } catch (final FileNotFoundException e) { e.printStackTrace(); } } }
resolved fixed
47aefad
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-08-23T16:07:40Z
2003-08-01T09:26:40Z
extension/org/eclipse/jdt/internal/corext/dom/ASTRewriteFormatter.java
41,044
Bug 41044 quickfix "add catch block to surrounding try" does not comply with code formatter [quick fix]
i have selected the code formatter option: "insert a new line in control statements" which puts catch blocks on new lines however if you use the "add catch to surrounding try" quickfix on the file below the generated catch block will not be on a new line! -----------------------------------A.java------------------------- import java.io.FileNotFoundException; import java.io.IOException; public class A { void method() { try { if(false) { throw new FileNotFoundException(); } throw new IOException(); } catch (final FileNotFoundException e) { e.printStackTrace(); } } }
resolved fixed
47aefad
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-08-23T16:07:40Z
2003-08-01T09:26:40Z
org.eclipse.jdt.ui/core
41,044
Bug 41044 quickfix "add catch block to surrounding try" does not comply with code formatter [quick fix]
i have selected the code formatter option: "insert a new line in control statements" which puts catch blocks on new lines however if you use the "add catch to surrounding try" quickfix on the file below the generated catch block will not be on a new line! -----------------------------------A.java------------------------- import java.io.FileNotFoundException; import java.io.IOException; public class A { void method() { try { if(false) { throw new FileNotFoundException(); } throw new IOException(); } catch (final FileNotFoundException e) { e.printStackTrace(); } } }
resolved fixed
47aefad
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-08-23T16:07:40Z
2003-08-01T09:26:40Z
extension/org/eclipse/jdt/internal/corext/util/CodeFormatterUtil.java
41,905
Bug 41905 [syntax highlighting] hyperlink style navigation should respect font style
A new option allows to change the font style for method names. When hyperlink style navigation is on, method names will change to be a link when hovered over. The font displayed for links does not respect the font styled defined, e.g. if my method names are bold, the link style should be bold as well.
resolved fixed
a55d0c2
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-08-25T11:32:40Z
2003-08-25T05: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.text.CollationElementIterator; import java.text.Collator; import java.text.RuleBasedCollator; 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.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.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; 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.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.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.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.swt.SWT; import org.eclipse.swt.custom.BidiSegmentEvent; import org.eclipse.swt.custom.BidiSegmentListener; import org.eclipse.swt.custom.ST; 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.Event; import org.eclipse.swt.widgets.Shell; 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.DefaultMarkerAnnotationAccess; 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.MarkerAnnotationPreferences; import org.eclipse.ui.texteditor.ResourceAction; import org.eclipse.ui.texteditor.SourceViewerDecorationSupport; import org.eclipse.ui.texteditor.TextEditorAction; import org.eclipse.ui.texteditor.TextNavigationAction; 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; /** * 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 extends DefaultMarkerAnnotationAccess { public AnnotationAccess(MarkerAnnotationPreferences markerAnnotationPreferences) { super(markerAnnotationPreferences); } /* * @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); } } /** * This action implements smart home. * * Instead of going to the start of a line it does the following: * * - if smart home/end is enabled and the caret is after the line's first non-whitespace then the caret is moved directly before it, taking JavaDoc and multi-line comments into account. * - if the caret is before the line's first non-whitespace the caret is moved to the beginning of the line * - if the caret is at the beginning of the line see first case. * * @since 3.0 */ protected class SmartLineStartAction extends LineStartAction { /** * Creates a new smart line start action * * @param textWidget the styled text widget * @param doSelect a boolean flag which tells if the text up to the beginning of the line should be selected */ public SmartLineStartAction(final StyledText textWidget, final boolean doSelect) { super(textWidget, doSelect); } /* * @see org.eclipse.ui.texteditor.AbstractTextEditor.LineStartAction#getLineStartPosition(java.lang.String, int, java.lang.String) */ protected int getLineStartPosition(final IDocument document, final String line, final int length, final int offset) { String type= IDocument.DEFAULT_CONTENT_TYPE; try { type= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, offset).getType(); } catch (BadLocationException exception) { // Should not happen } int index= super.getLineStartPosition(document, line, length, offset); if (type.equals(IJavaPartitions.JAVA_DOC) || type.equals(IJavaPartitions.JAVA_MULTI_LINE_COMMENT)) { if (index < length - 1 && line.charAt(index) == '*' && line.charAt(index + 1) != '/') { do { ++index; } while (index < length && Character.isWhitespace(line.charAt(index))); } } else { if (index < length - 1 && line.charAt(index) == '/' && line.charAt(++index) == '/') { do { ++index; } while (index < length && Character.isWhitespace(line.charAt(index))); } } return index; } } /** * Text navigation action to navigate to the next sub-word. * * @since 3.0 */ protected abstract class NextSubWordAction extends TextNavigationAction { /** Collator to determine the sub-word boundaries */ private final RuleBasedCollator fCollator= (RuleBasedCollator)Collator.getInstance(); /** * Creates a new next sub-word action. * * @param code Action code for the default operation. Must be an action code from @see org.eclipse.swt.custom.ST. */ protected NextSubWordAction(int code) { super(getSourceViewer().getTextWidget(), code); // Only compare upper-/lower case fCollator.setStrength(Collator.TERTIARY); } /* * @see org.eclipse.jface.action.IAction#run() */ public void run() { try { final ISourceViewer viewer= getSourceViewer(); final IDocument document= viewer.getDocument(); int position= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset()); // Check whether we are in a java code partititon and the preference is enabled final IPreferenceStore store= getPreferenceStore(); final ITypedRegion region= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, position); if (!region.getType().equals(IDocument.DEFAULT_CONTENT_TYPE) || !store.getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)) { super.run(); return; } // Check whether right hand character of caret is valid identifier start if (Character.isJavaIdentifierStart(document.getChar(position))) { int offset= 0; int order= CollationElementIterator.NULLORDER; short previous= Short.MAX_VALUE; short next= Short.MAX_VALUE; // Acquire collator for partition around caret final String buffer= document.get(position, region.getOffset() + region.getLength() - position); final CollationElementIterator iterator= fCollator.getCollationElementIterator(buffer); // Iterate to first upper-case character do { // Check whether we reached end of word offset= iterator.getOffset(); if (!Character.isJavaIdentifierPart(document.getChar(position + offset))) throw new BadLocationException(); // Test next characters order= iterator.next(); next= CollationElementIterator.tertiaryOrder(order); if (next <= previous) previous= next; else break; } while (order != CollationElementIterator.NULLORDER); // Check for leading underscores position += offset; if (Character.getType(document.getChar(position - 1)) != Character.CONNECTOR_PUNCTUATION) { setCaretPosition(position); return; } } } catch (BadLocationException exception) { // Use default behavior } super.run(); } /** * Sets the caret position to the sub-word boundary given with <code>position</code>. * * @param position Position where the action should move the caret */ protected abstract void setCaretPosition(int position); } /** * Text navigation action to navigate to the next sub-word. * * @since 3.0 */ protected class NavigateNextSubWordAction extends NextSubWordAction { /** * Creates a new navigate next sub-word action. */ public NavigateNextSubWordAction() { super(ST.WORD_NEXT); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { final ISourceViewer viewer= getSourceViewer(); viewer.getTextWidget().setCaretOffset(modelOffset2WidgetOffset(viewer, position)); } } /** * Text operation action to delete the next sub-word. * * @since 3.0 */ protected class DeleteNextSubWordAction extends NextSubWordAction { /** * Creates a new delete next sub-word action. */ public DeleteNextSubWordAction() { super(ST.DELETE_WORD_NEXT); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { final ISourceViewer viewer= getSourceViewer(); final int caret= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset()); try { viewer.getDocument().replace(caret, position - caret, ""); //$NON-NLS-1$ } catch (BadLocationException exception) { // Should not happen } } } /** * Text operation action to select the next sub-word. * * @since 3.0 */ protected class SelectNextSubWordAction extends NextSubWordAction { /** * Creates a new select next sub-word action. */ public SelectNextSubWordAction() { super(ST.SELECT_WORD_NEXT); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { final ISourceViewer viewer= getSourceViewer(); final StyledText text= viewer.getTextWidget(); if (text != null && !text.isDisposed()) { final Point selection= text.getSelection(); text.setSelectionRange(selection.x, modelOffset2WidgetOffset(viewer, position) - selection.x); final Event event= new Event(); event.x= text.getSelection().x; event.y= text.getSelection().y; text.notifyListeners(SWT.Selection, event); } } } /** * Text navigation action to navigate to the previous sub-word. * * @since 3.0 */ protected abstract class PreviousSubWordAction extends TextNavigationAction { /** Collator to determine the sub-word boundaries */ private final RuleBasedCollator fCollator= (RuleBasedCollator)Collator.getInstance(); /** * Creates a new previous sub-word action. * * @param code Action code for the default operation. Must be an action code from @see org.eclipse.swt.custom.ST. */ protected PreviousSubWordAction(final int code) { super(getSourceViewer().getTextWidget(), code); // Only compare upper-/lower case fCollator.setStrength(Collator.TERTIARY); } /* * @see org.eclipse.jface.action.IAction#run() */ public void run() { try { final ISourceViewer viewer= getSourceViewer(); final IDocument document= viewer.getDocument(); int position= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset()) - 1; // Check whether we are in a java code partititon and the preference is enabled final IPreferenceStore store= getPreferenceStore(); ITypedRegion region= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, position); if (!region.getType().equals(IDocument.DEFAULT_CONTENT_TYPE) || !store.getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)) { super.run(); return; } // Ignore trailing white spaces char character= document.getChar(position); while (position > 0 && Character.isWhitespace(character)) { --position; character= document.getChar(position); } // Check whether left hand character of caret is valid identifier part if (Character.isJavaIdentifierPart(character)) { int offset= 0; int order= CollationElementIterator.NULLORDER; short previous= Short.MAX_VALUE; short next= Short.MAX_VALUE; // Acquire collator for partition around caret region= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, position); final String buffer= document.get(region.getOffset(), position - region.getOffset() + 1); final CollationElementIterator iterator= fCollator.getCollationElementIterator(buffer); // Iterate to first upper-case character iterator.setOffset(buffer.length() - 1); do { // Check whether we reached begin of word or single upper-case start offset= iterator.getOffset(); character= document.getChar(region.getOffset() + offset); if (!Character.isJavaIdentifierPart(character)) throw new BadLocationException(); else if (Character.isUpperCase(character)) { ++offset; break; } // Test next characters order= iterator.previous(); next= CollationElementIterator.tertiaryOrder(order); if (next <= previous) previous= next; else break; } while (order != CollationElementIterator.NULLORDER); // Check left character for multiple upper-case characters position= position - buffer.length() + offset - 1; character= document.getChar(position); if (!Character.isUpperCase(character)) { setCaretPosition(position + 1); return; } } } catch (BadLocationException exception) { // Use default behavior } super.run(); } /** * Sets the caret position to the sub-word boundary given with <code>position</code>. * * @param position Position where the action should move the caret */ protected abstract void setCaretPosition(int position); } /** * Text navigation action to navigate to the previous sub-word. * * @since 3.0 */ protected class NavigatePreviousSubWordAction extends PreviousSubWordAction { /** * Creates a new navigate previous sub-word action. */ public NavigatePreviousSubWordAction() { super(ST.WORD_PREVIOUS); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { final ISourceViewer viewer= getSourceViewer(); viewer.getTextWidget().setCaretOffset(modelOffset2WidgetOffset(viewer, position)); } } /** * Text operation action to delete the previous sub-word. * * @since 3.0 */ protected class DeletePreviousSubWordAction extends PreviousSubWordAction { /** * Creates a new delete previous sub-word action. */ public DeletePreviousSubWordAction() { super(ST.DELETE_WORD_PREVIOUS); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { final ISourceViewer viewer= getSourceViewer(); final int caret= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset()); try { viewer.getDocument().replace(position, caret - position, ""); //$NON-NLS-1$ } catch (BadLocationException exception) { // Should not happen } } } /** * Text operation action to select the previous sub-word. * * @since 3.0 */ protected class SelectPreviousSubWordAction extends PreviousSubWordAction { /** * Creates a new select previous sub-word action. */ public SelectPreviousSubWordAction() { super(ST.SELECT_WORD_PREVIOUS); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { final ISourceViewer viewer= getSourceViewer(); final StyledText text= viewer.getTextWidget(); if (text != null && !text.isDisposed()) { final Point selection= text.getSelection(); text.setSelectionRange(selection.y, modelOffset2WidgetOffset(viewer, position) - selection.y); final Event event= new Event(); event.x= text.getSelection().x; event.y= text.getSelection().y; text.notifyListeners(SWT.Selection, 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(new MarkerAnnotationPreferences()); } 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 } /* * @see org.eclipse.ui.texteditor.AbstractTextEditor#createNavigationActions() */ protected void createNavigationActions() { super.createNavigationActions(); final StyledText textWidget= getSourceViewer().getTextWidget(); IAction action= new SmartLineStartAction(textWidget, false); action.setActionDefinitionId(ITextEditorActionDefinitionIds.LINE_START); setAction(ITextEditorActionDefinitionIds.LINE_START, action); action= new SmartLineStartAction(textWidget, true); action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_LINE_START); setAction(ITextEditorActionDefinitionIds.SELECT_LINE_START, action); action= new NavigatePreviousSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.WORD_PREVIOUS); setAction(ITextEditorActionDefinitionIds.WORD_PREVIOUS, action); textWidget.setKeyBinding(SWT.CTRL | SWT.ARROW_LEFT, SWT.NULL); action= new NavigateNextSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.WORD_NEXT); setAction(ITextEditorActionDefinitionIds.WORD_NEXT, action); textWidget.setKeyBinding(SWT.CTRL | SWT.ARROW_RIGHT, SWT.NULL); action= new DeletePreviousSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.DELETE_PREVIOUS_WORD); setAction(ITextEditorActionDefinitionIds.DELETE_PREVIOUS_WORD, action); textWidget.setKeyBinding(SWT.CTRL | SWT.BS, SWT.NULL); action= new DeleteNextSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.DELETE_NEXT_WORD); setAction(ITextEditorActionDefinitionIds.DELETE_NEXT_WORD, action); textWidget.setKeyBinding(SWT.CTRL | SWT.DEL, SWT.NULL); action= new SelectPreviousSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS); setAction(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS, action); textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_LEFT, SWT.NULL); action= new SelectNextSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT); setAction(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT, action); textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_RIGHT, SWT.NULL); } }
41,906
Bug 41906 [typing] Code assists handles anonymous inner classes less than optimal
Type the following code and press return at the indicated cursor position. addActionListener(new ActionListener() { <<<cursor_position>>> ) You get the following code: addActionListener(new ActionListener() { ) } The normal brace and the curly brace should really be exchanged.
resolved fixed
23f27d6
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-08-25T12:18:09Z
2003-08-25T08:26:40Z
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 (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) { if (position < 1) return false; position= firstNonWhitespaceBackward(document, position - 1, 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 &lt;= <code>position</code> * and &gt; <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> &gt; <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 &gt;= <code>position</code> * and &lt; <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> &gt; <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 &gt;= <code>position</code> * and &lt; <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> &gt; <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.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 &lt;= <code>position</code> * and &gt; <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> &gt; <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 (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,872
Bug 41872 [misc] Outliner doesn't generate selection change event if method changes name
null
resolved fixed
69a5c08
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-08-25T14:49:00Z
2003-08-22T16: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); boolean fieldsOnSameLine= r.getElementType() == IJavaElement.FIELD && e.getElementType() == IJavaElement.FIELD && rng.getOffset() == start && rng.getLength() == end - start + 1; if (!fieldsOnSameLine && 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,788
Bug 41788 QuickDiff provider name has & in preference list
I20030820 Disk and Remove (from optional zrh tools plug-in) have a & in the label of the preference page.
resolved fixed
298678e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-08-25T16:03:33Z
2003-08-21T12:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/WorkInProgressPreferencePage.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.preferences; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; 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.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.texteditor.ExtendedTextEditorPreferenceConstants; import org.eclipse.ui.texteditor.quickdiff.QuickDiff; import org.eclipse.ui.texteditor.quickdiff.ReferenceProviderDescriptor; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.internal.ui.JavaPlugin; /** * Preference page for work in progress. */ public class WorkInProgressPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { /** prefix for resources */ private static final String PREFIX= "WorkInProgress."; //$NON-NLS-1$ /** * All FieldEditors except <code>smartTyping</code>, whose enable state * is controlled by the smartTyping preference. */ private Set fSmartTypingItems= new HashSet(); private List fCheckBoxes; private List fRadioButtons; private List fTextControls; /** List for the reference provider default. */ private org.eclipse.swt.widgets.List fQuickDiffProviderList; /** The reference provider default's list model. */ private String[][] fQuickDiffProviderListModel; /** Button controlling default setting of the selected reference provider. */ private Button fSetDefaultButton; /** * creates a new preference page. */ public WorkInProgressPreferencePage() { setPreferenceStore(getPreferenceStore()); fRadioButtons= new ArrayList(); fCheckBoxes= new ArrayList(); fTextControls= new ArrayList(); List providers= new QuickDiff().getReferenceProviderDescriptors(); fQuickDiffProviderListModel= createQuickDiffReferenceListModel(providers); } private String[][] createQuickDiffReferenceListModel(List providers) { ArrayList listModelItems= new ArrayList(); for (Iterator it= providers.iterator(); it.hasNext();) { ReferenceProviderDescriptor provider= (ReferenceProviderDescriptor) it.next(); listModelItems.add(new String[] { provider.getId(), provider.getLabel() }); } String[][] items= new String[listModelItems.size()][]; listModelItems.toArray(items); return items; } private void handleProviderListSelection() { int i= fQuickDiffProviderList.getSelectionIndex(); boolean b= getPreferenceStore().getString(ExtendedTextEditorPreferenceConstants.QUICK_DIFF_DEFAULT_PROVIDER).equals(fQuickDiffProviderListModel[i][0]); fSetDefaultButton.setEnabled(!b); } private Button addCheckBox(Composite parent, String label, String key) { GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); Button button= new Button(parent, SWT.CHECK); button.setText(label); button.setData(key); button.setLayoutData(gd); button.setSelection(getPreferenceStore().getBoolean(key)); fCheckBoxes.add(button); return button; } /* * @see PreferencePage#createControl(Composite) */ public void createControl(Composite parent) { super.createControl(parent); WorkbenchHelp.setHelp(getControl(), "WORK_IN_PROGRESS_PREFERENCE_PAGE"); //$NON-NLS-1$ } protected Control createContents(Composite parent) { initializeDialogUnits(parent); Composite result= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(); layout.marginHeight= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); layout.marginWidth= 0; layout.verticalSpacing= convertVerticalDLUsToPixels(10); layout.horizontalSpacing= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); result.setLayout(layout); Group group= new Group(result, SWT.NONE); group.setLayout(new GridLayout()); group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); group.setText(PreferencesMessages.getString(PREFIX + "editor")); //$NON-NLS-1$ addCheckBox(group, PreferencesMessages.getString(PREFIX + "overwriteMode"), PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE); //$NON-NLS-1$ addCheckBox(group, PreferencesMessages.getString(PREFIX + "formatComments"), "work_in_progress_enable_comment_formatting"); //$NON-NLS-1$ //$NON-NLS-2$ createSpacer(group, 1); Label label= new Label(group, SWT.NONE); label.setText(PreferencesMessages.getString(PREFIX + "smartTyping.label")); //$NON-NLS-1$ Button button= addCheckBox(group, PreferencesMessages.getString(PREFIX + "smartTyping.smartSemicolon"), PreferenceConstants.EDITOR_SMART_SEMICOLON); //$NON-NLS-1$ fSmartTypingItems.add(button); button= addCheckBox(group, PreferencesMessages.getString(PREFIX + "smartTyping.smartOpeningBrace"), PreferenceConstants.EDITOR_SMART_OPENING_BRACE); //$NON-NLS-1$ fSmartTypingItems.add(button); /* line change bar */ group= new Group(result, SWT.NONE); group.setLayout(new GridLayout()); group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); group.setText(PreferencesMessages.getString(PREFIX + "quickdiff")); //$NON-NLS-1$ Label l= new Label(group, SWT.LEFT ); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= 2; gd.heightHint= convertHeightInCharsToPixels(1) / 2; l.setLayoutData(gd); button= addCheckBox(group, PreferencesMessages.getString(PREFIX + "showQuickDiffPerDefault"), ExtendedTextEditorPreferenceConstants.QUICK_DIFF_ALWAYS_ON); //$NON-NLS-1$ button= addCheckBox(group, PreferencesMessages.getString(PREFIX + "quickdiff.characterMode"), ExtendedTextEditorPreferenceConstants.QUICK_DIFF_CHARACTER_MODE); //$NON-NLS-1$ l= new Label(group, SWT.LEFT ); gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= 2; gd.heightHint= convertHeightInCharsToPixels(1) / 2; l.setLayoutData(gd); l= new Label(group, SWT.LEFT); l.setText(PreferencesMessages.getString(PREFIX + "quickdiff.referenceprovidertitle")); //$NON-NLS-1$ gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= 2; l.setLayoutData(gd); Composite editorComposite= new Composite(group, SWT.NONE); layout= new GridLayout(); layout.numColumns= 2; layout.marginHeight= 0; layout.marginWidth= 0; editorComposite.setLayout(layout); gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.FILL_VERTICAL); gd.horizontalSpan= 2; editorComposite.setLayoutData(gd); fQuickDiffProviderList= new org.eclipse.swt.widgets.List(editorComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER); gd= new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL); gd.heightHint= convertHeightInCharsToPixels(4); fQuickDiffProviderList.setLayoutData(gd); Composite stylesComposite= new Composite(editorComposite, SWT.NONE); layout= new GridLayout(); layout.marginHeight= 0; layout.marginWidth= 0; layout.numColumns= 2; stylesComposite.setLayout(layout); stylesComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); fSetDefaultButton= new Button(stylesComposite, SWT.PUSH); fSetDefaultButton.setText(PreferencesMessages.getString(PREFIX + "quickdiff.setDefault")); //$NON-NLS-1$ gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalAlignment= GridData.BEGINNING; gd.horizontalSpan= 2; fSetDefaultButton.setLayoutData(gd); fQuickDiffProviderList.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { handleProviderListSelection(); } }); fSetDefaultButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { int i= fQuickDiffProviderList.getSelectionIndex(); for (int j= 0; j < fQuickDiffProviderListModel.length; j++) { if (getPreferenceStore().getString(ExtendedTextEditorPreferenceConstants.QUICK_DIFF_DEFAULT_PROVIDER).equals(fQuickDiffProviderListModel[j][0])) { fQuickDiffProviderList.remove(j); fQuickDiffProviderList.add(fQuickDiffProviderListModel[j][1], j); } if (i == j) { fQuickDiffProviderList.remove(j); fQuickDiffProviderList.add(fQuickDiffProviderListModel[j][1] + " " + PreferencesMessages.getString(PREFIX + "quickdiff.defaultlabel"), j); //$NON-NLS-1$//$NON-NLS-2$ } } fSetDefaultButton.setEnabled(false); fQuickDiffProviderList.setSelection(i); fQuickDiffProviderList.redraw(); getPreferenceStore().setValue(ExtendedTextEditorPreferenceConstants.QUICK_DIFF_DEFAULT_PROVIDER, fQuickDiffProviderListModel[i][0]); } }); for (int i= 0; i < fQuickDiffProviderListModel.length; i++) { String sLabel= fQuickDiffProviderListModel[i][1]; if (getPreferenceStore().getString(ExtendedTextEditorPreferenceConstants.QUICK_DIFF_DEFAULT_PROVIDER).equals(fQuickDiffProviderListModel[i][0])) sLabel += " " + PreferencesMessages.getString(PREFIX + "quickdiff.defaultlabel"); //$NON-NLS-1$ //$NON-NLS-2$ fQuickDiffProviderList.add(sLabel); } fQuickDiffProviderList.getDisplay().asyncExec(new Runnable() { public void run() { if (fQuickDiffProviderList != null && !fQuickDiffProviderList.isDisposed()) { fQuickDiffProviderList.select(0); handleProviderListSelection(); } } }); group= new Group(result, SWT.NONE); group.setLayout(new GridLayout()); group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); group.setText(PreferencesMessages.getString(PREFIX + "refactoring")); //$NON-NLS-1$ button= addCheckBox(group, PreferencesMessages.getString(PREFIX + "refactoring.participants"), "org.eclipse.jdt.refactoring.participants"); //$NON-NLS-1$ //$NON-NLS-2$ group= new Group(result, SWT.NONE); group.setLayout(new GridLayout()); group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); group.setText(PreferencesMessages.getString(PREFIX + "quickassist.group")); //$NON-NLS-1$ button= addCheckBox(group, PreferencesMessages.getString(PREFIX + "quickassist.option"), PreferenceConstants.APPEARANCE_QUICKASSIST_LIGHTBULB); //$NON-NLS-1$ //$NON-NLS-2$ return result; } /* * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench) */ public void init(IWorkbench workbench) { } protected void createSpacer(Composite composite, int columnSpan) { Label label= new Label(composite, SWT.NONE); GridData gd= new GridData(); gd.horizontalSpan= columnSpan; label.setLayoutData(gd); } /* * @see org.eclipse.jface.preference.PreferencePage#doGetPreferenceStore() */ protected IPreferenceStore doGetPreferenceStore() { return JavaPlugin.getDefault().getPreferenceStore(); } /* * @see PreferencePage#performDefaults() */ protected void performDefaults() { IPreferenceStore store= getPreferenceStore(); for (int i= 0; i < fCheckBoxes.size(); i++) { Button button= (Button) fCheckBoxes.get(i); String key= (String) button.getData(); button.setSelection(store.getDefaultBoolean(key)); } for (int i= 0; i < fRadioButtons.size(); i++) { Button button= (Button) fRadioButtons.get(i); String[] info= (String[]) button.getData(); button.setSelection(info[1].equals(store.getDefaultString(info[0]))); } for (int i= 0; i < fTextControls.size(); i++) { Text text= (Text) fTextControls.get(i); String key= (String) text.getData(); text.setText(store.getDefaultString(key)); } handleProviderListSelection(); super.performDefaults(); } /* * @see IPreferencePage#performOk() */ public boolean performOk() { IPreferenceStore store= getPreferenceStore(); for (int i= 0; i < fCheckBoxes.size(); i++) { Button button= (Button) fCheckBoxes.get(i); String key= (String) button.getData(); store.setValue(key, button.getSelection()); } for (int i= 0; i < fRadioButtons.size(); i++) { Button button= (Button) fRadioButtons.get(i); if (button.getSelection()) { String[] info= (String[]) button.getData(); store.setValue(info[0], info[1]); } } for (int i= 0; i < fTextControls.size(); i++) { Text text= (Text) fTextControls.get(i); String key= (String) text.getData(); store.setValue(key, text.getText()); } JavaPlugin.getDefault().savePluginPreferences(); return super.performOk(); } /** * @param store */ public static void initDefaults(IPreferenceStore store) { store.setDefault("work_in_progress_enable_comment_formatting", false); //$NON-NLS-1$ store.setDefault(PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE, false); store.setDefault(PreferenceConstants.EDITOR_SMART_SEMICOLON, false); store.setDefault(PreferenceConstants.EDITOR_SMART_OPENING_BRACE, false); store.setDefault(PreferenceConstants.APPEARANCE_QUICKASSIST_LIGHTBULB, false); } }
41,868
Bug 41868 Declaration View does not refresh when you change Java-code color preferences
null
verified fixed
c4a8c99
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-08-26T09:16:13Z
2003-08-22T16:33:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/infoviews/SourceView.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.infoviews; import java.io.IOException; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.util.Assert; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextOperationTarget; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.text.ITextViewerExtension; import org.eclipse.jface.text.TextViewer; import org.eclipse.jface.text.source.SourceViewer; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.texteditor.IAbstractTextEditorHelpContextIds; import org.eclipse.ui.texteditor.ITextEditorActionConstants; import org.eclipse.jdt.core.ICodeAssist; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.ISourceReference; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.IContextMenuConstants; import org.eclipse.jdt.ui.actions.JdtActionConstants; import org.eclipse.jdt.ui.actions.OpenAction; import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration; import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility; import org.eclipse.jdt.internal.corext.util.CodeFormatterUtil; import org.eclipse.jdt.internal.corext.util.Strings; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.javaeditor.JavaSourceViewer; import org.eclipse.jdt.internal.ui.text.JavaCodeReader; /** * View which shows source for a given Java element. * * @since 3.0 */ public class SourceView extends AbstractInfoView implements IMenuListener { /** Symbolic Java editor font name. */ private static final String SYMBOLIC_FONT_NAME= "org.eclipse.jdt.ui.editors.textfont"; //$NON-NLS-1$ /** * Internal property change listener for handling workbench font changes. */ class FontPropertyChangeListener implements IPropertyChangeListener { /* * @see IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent) */ public void propertyChange(PropertyChangeEvent event) { if (fViewer == null) return; String property= event.getProperty(); if (SYMBOLIC_FONT_NAME.equals(property)) setViewerFont(); } } /** * The Javadoc view's select all action. */ private static class SelectAllAction extends Action { private TextViewer fTextViewer; /** * Creates the action. */ public SelectAllAction(TextViewer textViewer) { super("selectAll"); //$NON-NLS-1$ Assert.isNotNull(textViewer); fTextViewer= textViewer; setText(InfoViewMessages.getString("SelectAllAction.label")); //$NON-NLS-1$ setToolTipText(InfoViewMessages.getString("SelectAllAction.tooltip")); //$NON-NLS-1$ setDescription(InfoViewMessages.getString("SelectAllAction.description")); //$NON-NLS-1$ WorkbenchHelp.setHelp(this, IAbstractTextEditorHelpContextIds.SELECT_ALL_ACTION); } /** * Selects all in the viewer. */ public void run() { fTextViewer.doOperation(ITextOperationTarget.SELECT_ALL); } } /** This view's source viewer */ private SourceViewer fViewer; /** The viewer's font properties change listener. */ private IPropertyChangeListener fFontPropertyChangeListener= new FontPropertyChangeListener(); /** The open action */ private OpenAction fOpen; /** The number of removed leading comment lines. */ private int fCommentLineCount; /** The select all action. */ private SelectAllAction fSelectAllAction; /** Element opened by the open action. */ private IJavaElement fLastOpenedElement; /* * @see AbstractInfoView#internalCreatePartControl(Composite) */ protected void internalCreatePartControl(Composite parent) { fViewer= new JavaSourceViewer(parent, null, null, false, SWT.V_SCROLL | SWT.H_SCROLL); fViewer.configure(new JavaSourceViewerConfiguration(JavaPlugin.getDefault().getJavaTextTools(), null)); fViewer.setEditable(false); setViewerFont(); JFaceResources.getFontRegistry().addListener(fFontPropertyChangeListener); getViewSite().setSelectionProvider(fViewer); } /* * @see AbstractInfoView#internalCreatePartControl(Composite) */ protected void createActions() { super.createActions(); fSelectAllAction= new SelectAllAction(fViewer); // Setup OpenAction fOpen= new OpenAction(getViewSite()) { /* * @see org.eclipse.jdt.ui.actions.SelectionDispatchAction#getSelection() */ public ISelection getSelection() { return convertToJavaElementSelection(fViewer.getSelection()); } /* * @see org.eclipse.jdt.ui.actions.OpenAction#run(IStructuredSelection) */ public void run(IStructuredSelection selection) { if (selection.isEmpty()) { getShell().getDisplay().beep(); return; } super.run(selection); } /* * @see org.eclipse.jdt.ui.actions.OpenAction#getElementToOpen(Object) */ public Object getElementToOpen(Object object) throws JavaModelException { if (object instanceof IJavaElement) fLastOpenedElement= (IJavaElement)object; else fLastOpenedElement= null; return super.getElementToOpen(object); } /* * @see org.eclipse.jdt.ui.actions.OpenAction#run(Object[]) */ public void run(Object[] elements) { stopListeningForSelectionChanges(); super.run(elements); startListeningForSelectionChanges(); } }; } /* * @see AbstractInfoView#fillActionBars(IActionBars) */ protected void fillActionBars(IActionBars actionBars) { super.fillActionBars(actionBars); actionBars.setGlobalActionHandler(JdtActionConstants.OPEN, fOpen); actionBars.setGlobalActionHandler(IWorkbenchActionConstants.SELECT_ALL, fSelectAllAction); } /* * @see AbstractInfoView#getControl() */ protected Control getControl() { return fViewer.getControl(); } /* * @see AbstractInfoView#menuAboutToShow(IMenuManager) */ public void menuAboutToShow(IMenuManager menu) { super.menuAboutToShow(menu); menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, fSelectAllAction); menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, fOpen); } /* * @see AbstractInfoView#setForeground(Color) */ protected void setForeground(Color color) { fViewer.getTextWidget().setForeground(color); } /* * @see AbstractInfoView#setBackground(Color) */ protected void setBackground(Color color) { fViewer.getTextWidget().setBackground(color); } /** * Converts the given selection to a structured selection * containing Java elements. * * @param selection the selection * @return a structured selection with Java elements */ private IStructuredSelection convertToJavaElementSelection(ISelection selection) { if (!(selection instanceof ITextSelection && fCurrentViewInput instanceof ISourceReference)) return StructuredSelection.EMPTY; ITextSelection textSelection= (ITextSelection)selection; Object codeAssist= fCurrentViewInput.getAncestor(IJavaElement.COMPILATION_UNIT); if (codeAssist == null) codeAssist= fCurrentViewInput.getAncestor(IJavaElement.CLASS_FILE); if (codeAssist instanceof ICodeAssist) { IJavaElement[] elements= null; try { ISourceRange range= ((ISourceReference)fCurrentViewInput).getSourceRange(); elements= ((ICodeAssist)codeAssist).codeSelect(range.getOffset() + getOffsetInUnclippedDocument(textSelection), textSelection.getLength()); } catch (JavaModelException e) { return StructuredSelection.EMPTY; } if (elements != null && elements.length > 0) { return new StructuredSelection(elements[0]); } else return StructuredSelection.EMPTY; } return StructuredSelection.EMPTY; } /** * Computes and returns the offset in the unclipped document * based on the given text selection from the clipped * document. * * @param textSelection * @return the offest in the unclipped document or <code>-1</code> if the offset cannot be computed */ private int getOffsetInUnclippedDocument(ITextSelection textSelection) { IDocument unclippedDocument= null; try { unclippedDocument= new Document(((ISourceReference)fCurrentViewInput).getSource()); } catch (JavaModelException e) { return -1; } IDocument clippedDoc= (IDocument)fViewer.getInput(); try { IRegion unclippedLineInfo= unclippedDocument.getLineInformation(fCommentLineCount + textSelection.getStartLine()); IRegion clippedLineInfo= clippedDoc.getLineInformation(textSelection.getStartLine()); int removedIndentation= unclippedLineInfo.getLength() - clippedLineInfo.getLength(); int relativeLineOffset= textSelection.getOffset() - clippedLineInfo.getOffset(); return unclippedLineInfo.getOffset() + removedIndentation + relativeLineOffset ; } catch (BadLocationException ex) { return -1; } } /* * @see AbstractInfoView#internalDispose() */ protected void internalDispose() { fViewer= null; JFaceResources.getFontRegistry().removeListener(fFontPropertyChangeListener); } /* * @see org.eclipse.ui.part.WorkbenchPart#setFocus() */ public void setFocus() { fViewer.getTextWidget().setFocus(); } /* * @see AbstractInfoView#computeInput(Object) */ protected Object computeInput(Object input) { if (fViewer == null || !(input instanceof ISourceReference)) return null; ISourceReference sourceRef= (ISourceReference)input; if (fLastOpenedElement != null && input instanceof IJavaElement && ((IJavaElement)input).getHandleIdentifier().equals(fLastOpenedElement.getHandleIdentifier())) { fLastOpenedElement= null; return null; } else { fLastOpenedElement= null; } String source; try { source= sourceRef.getSource(); } catch (JavaModelException ex) { return null; } if (source == null) return null; source= removeLeadingComments(source); String delim= null; try { if (input instanceof IJavaElement) delim= StubUtility.getLineDelimiterUsed((IJavaElement)input); } catch (JavaModelException e) { delim= System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ } String[] sourceLines= Strings.convertIntoLines(source); String firstLine= sourceLines[0]; if (!Character.isWhitespace(firstLine.charAt(0))) sourceLines[0]= ""; //$NON-NLS-1$ Strings.trimIndentation(sourceLines, CodeFormatterUtil.getTabWidth()); if (!Character.isWhitespace(firstLine.charAt(0))) sourceLines[0]= firstLine; source= Strings.concatenate(sourceLines, delim); IDocument doc= new Document(source); JavaPlugin.getDefault().getJavaTextTools().setupDocument(doc); return doc; } /* * @see AbstractInfoView#setInput(Object) */ protected void setInput(Object input) { fViewer.setInput(input); } /** * Removes the leading comments from the given source. * * @param source the string with the source * @return the source without leading comments */ private String removeLeadingComments(String source) { JavaCodeReader reader= new JavaCodeReader(); IDocument document= new Document(source); int i; try { reader.configureForwardReader(document, 0, document.getLength(), true, false); int c= reader.read(); while (c != -1 && (c == '\r' || c == '\n' || c == '\t')) { c= reader.read(); } i= reader.getOffset(); reader.close(); } catch (IOException ex) { i= 0; } finally { try { if (reader != null) reader.close(); } catch (IOException ex) { JavaPlugin.log(ex); } } try { fCommentLineCount= document.getLineOfOffset(i); } catch (BadLocationException e) { fCommentLineCount= 0; } if (i < 0) return source; return source.substring(i); } /** * Sets the font for this viewer sustaining selection and scroll position. */ private void setViewerFont() { Font font= JFaceResources.getFont(SYMBOLIC_FONT_NAME); if (fViewer.getDocument() != null) { Point selection= fViewer.getSelectedRange(); int topIndex= fViewer.getTopIndex(); StyledText styledText= fViewer.getTextWidget(); Control parent= styledText; if (fViewer instanceof ITextViewerExtension) { ITextViewerExtension extension= (ITextViewerExtension) fViewer; parent= extension.getControl(); } parent.setRedraw(false); styledText.setFont(font); fViewer.setSelectedRange(selection.x , selection.y); fViewer.setTopIndex(topIndex); if (parent instanceof Composite) { Composite composite= (Composite) parent; composite.layout(true); } parent.setRedraw(true); } else { StyledText styledText= fViewer.getTextWidget(); styledText.setFont(font); } } }
41,953
Bug 41953 [Automatic Javadoc/Comment Formatting] Gives an NPE
When enabling the automatic formatting of Javadoc/comment sections (Preferences > Java > Work in Progress) the action "Source > Format" (Ctrl+Shift+F) fails with a null pointer exception. Reason: Call to "IDocument.getPartition(int)" in "org.eclipse.jdt.internal.ui.text.comment.CommentFormatter#format(String, int, int[], String) : String" returns "IDocument.DEFAULT_CONTENT_TYPE", for which no comment factory object is available. Fix: Correct fix is to use "IDocumentExtension3#getPartition(String, int)" with IJavaPartitions.JAVA_PARTITIONING to get the correct partition type.
resolved fixed
8ebe312
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-08-26T10:30:05Z
2003-08-26T09:26:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/comment/CommentFormatter.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.comment; import org.eclipse.jdt.core.ICodeFormatter; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.source.ISourceViewer; /** * Code formatter for general source code comments. * * @since 3.0 */ public class CommentFormatter implements ICodeFormatter { /** Source viewer where to apply the formatting strategy */ private final ISourceViewer fSourceViewer; /** * Creates a new comment formatter. * * @param viewer The source viewer where to apply the formatting strategy */ public CommentFormatter(ISourceViewer viewer) { fSourceViewer= viewer; } /* * @see org.eclipse.jdt.core.ICodeFormatter#format(java.lang.String, int, int[], java.lang.String) */ public String format(String string, int indentationLevel, int[] positions, String lineSeparator) { try { final CommentRegion region= CommentObjectFactory.getRegion(fSourceViewer.getDocument(), fSourceViewer.getDocument().getPartition(0), lineSeparator); region.formatRegion(); } catch (BadLocationException e) { } // TODO Do formatting return null; } }
41,958
Bug 41958 No reaction to F2 after Java Tooltip Hover showed up
200308250800 + export 20030826_1219 Smoke Test: - open TestCase.java - hover over method call "run" in method run(TestResult) - Hover appears and tells to "Press F2 for focus." - Pressing F2 *after* the hover appeared does *not* focus the tooltip description
verified fixed
f71db63
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-08-26T14:26:17Z
2003-08-26T12:13:20Z
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.text.CollationElementIterator; import java.text.Collator; import java.text.RuleBasedCollator; 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.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.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; 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.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.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.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.swt.SWT; import org.eclipse.swt.custom.BidiSegmentEvent; import org.eclipse.swt.custom.BidiSegmentListener; import org.eclipse.swt.custom.ST; 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.Event; import org.eclipse.swt.widgets.Shell; 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.DefaultMarkerAnnotationAccess; 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.MarkerAnnotationPreferences; import org.eclipse.ui.texteditor.ResourceAction; import org.eclipse.ui.texteditor.SourceViewerDecorationSupport; import org.eclipse.ui.texteditor.TextEditorAction; import org.eclipse.ui.texteditor.TextNavigationAction; 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; /** * 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; int fontStyle= oldStyleRange== null ? SWT.NORMAL : oldStyleRange.fontStyle; StyleRange styleRange= new StyleRange(offset, length, foregroundColor, backgroundColor, fontStyle); 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; if (extension4.moveFocusToWidgetToken()) return; } 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 extends DefaultMarkerAnnotationAccess { public AnnotationAccess(MarkerAnnotationPreferences markerAnnotationPreferences) { super(markerAnnotationPreferences); } /* * @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); } } /** * This action implements smart home. * * Instead of going to the start of a line it does the following: * * - if smart home/end is enabled and the caret is after the line's first non-whitespace then the caret is moved directly before it, taking JavaDoc and multi-line comments into account. * - if the caret is before the line's first non-whitespace the caret is moved to the beginning of the line * - if the caret is at the beginning of the line see first case. * * @since 3.0 */ protected class SmartLineStartAction extends LineStartAction { /** * Creates a new smart line start action * * @param textWidget the styled text widget * @param doSelect a boolean flag which tells if the text up to the beginning of the line should be selected */ public SmartLineStartAction(final StyledText textWidget, final boolean doSelect) { super(textWidget, doSelect); } /* * @see org.eclipse.ui.texteditor.AbstractTextEditor.LineStartAction#getLineStartPosition(java.lang.String, int, java.lang.String) */ protected int getLineStartPosition(final IDocument document, final String line, final int length, final int offset) { String type= IDocument.DEFAULT_CONTENT_TYPE; try { type= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, offset).getType(); } catch (BadLocationException exception) { // Should not happen } int index= super.getLineStartPosition(document, line, length, offset); if (type.equals(IJavaPartitions.JAVA_DOC) || type.equals(IJavaPartitions.JAVA_MULTI_LINE_COMMENT)) { if (index < length - 1 && line.charAt(index) == '*' && line.charAt(index + 1) != '/') { do { ++index; } while (index < length && Character.isWhitespace(line.charAt(index))); } } else { if (index < length - 1 && line.charAt(index) == '/' && line.charAt(++index) == '/') { do { ++index; } while (index < length && Character.isWhitespace(line.charAt(index))); } } return index; } } /** * Text navigation action to navigate to the next sub-word. * * @since 3.0 */ protected abstract class NextSubWordAction extends TextNavigationAction { /** Collator to determine the sub-word boundaries */ private final RuleBasedCollator fCollator= (RuleBasedCollator)Collator.getInstance(); /** * Creates a new next sub-word action. * * @param code Action code for the default operation. Must be an action code from @see org.eclipse.swt.custom.ST. */ protected NextSubWordAction(int code) { super(getSourceViewer().getTextWidget(), code); // Only compare upper-/lower case fCollator.setStrength(Collator.TERTIARY); } /* * @see org.eclipse.jface.action.IAction#run() */ public void run() { try { final ISourceViewer viewer= getSourceViewer(); final IDocument document= viewer.getDocument(); int position= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset()); // Check whether we are in a java code partititon and the preference is enabled final IPreferenceStore store= getPreferenceStore(); final ITypedRegion region= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, position); if (!store.getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)) { super.run(); return; } // Check whether right hand character of caret is valid identifier start if (Character.isJavaIdentifierStart(document.getChar(position))) { int offset= 0; int order= CollationElementIterator.NULLORDER; short previous= Short.MAX_VALUE; short next= Short.MAX_VALUE; // Acquire collator for partition around caret final String buffer= document.get(position, region.getOffset() + region.getLength() - position); final CollationElementIterator iterator= fCollator.getCollationElementIterator(buffer); // Iterate to first upper-case character do { // Check whether we reached end of word offset= iterator.getOffset(); if (!Character.isJavaIdentifierPart(document.getChar(position + offset))) throw new BadLocationException(); // Test next characters order= iterator.next(); next= CollationElementIterator.tertiaryOrder(order); if (next <= previous) previous= next; else break; } while (order != CollationElementIterator.NULLORDER); // Check for leading underscores position += offset; if (Character.getType(document.getChar(position - 1)) != Character.CONNECTOR_PUNCTUATION) { setCaretPosition(position); return; } } } catch (BadLocationException exception) { // Use default behavior } super.run(); } /** * Sets the caret position to the sub-word boundary given with <code>position</code>. * * @param position Position where the action should move the caret */ protected abstract void setCaretPosition(int position); } /** * Text navigation action to navigate to the next sub-word. * * @since 3.0 */ protected class NavigateNextSubWordAction extends NextSubWordAction { /** * Creates a new navigate next sub-word action. */ public NavigateNextSubWordAction() { super(ST.WORD_NEXT); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { final ISourceViewer viewer= getSourceViewer(); viewer.getTextWidget().setCaretOffset(modelOffset2WidgetOffset(viewer, position)); } } /** * Text operation action to delete the next sub-word. * * @since 3.0 */ protected class DeleteNextSubWordAction extends NextSubWordAction { /** * Creates a new delete next sub-word action. */ public DeleteNextSubWordAction() { super(ST.DELETE_WORD_NEXT); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { final ISourceViewer viewer= getSourceViewer(); final int caret= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset()); try { viewer.getDocument().replace(caret, position - caret, ""); //$NON-NLS-1$ } catch (BadLocationException exception) { // Should not happen } } } /** * Text operation action to select the next sub-word. * * @since 3.0 */ protected class SelectNextSubWordAction extends NextSubWordAction { /** * Creates a new select next sub-word action. */ public SelectNextSubWordAction() { super(ST.SELECT_WORD_NEXT); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { final ISourceViewer viewer= getSourceViewer(); final StyledText text= viewer.getTextWidget(); if (text != null && !text.isDisposed()) { final Point selection= text.getSelection(); text.setSelectionRange(selection.x, modelOffset2WidgetOffset(viewer, position) - selection.x); final Event event= new Event(); event.x= text.getSelection().x; event.y= text.getSelection().y; text.notifyListeners(SWT.Selection, event); } } } /** * Text navigation action to navigate to the previous sub-word. * * @since 3.0 */ protected abstract class PreviousSubWordAction extends TextNavigationAction { /** Collator to determine the sub-word boundaries */ private final RuleBasedCollator fCollator= (RuleBasedCollator)Collator.getInstance(); /** * Creates a new previous sub-word action. * * @param code Action code for the default operation. Must be an action code from @see org.eclipse.swt.custom.ST. */ protected PreviousSubWordAction(final int code) { super(getSourceViewer().getTextWidget(), code); // Only compare upper-/lower case fCollator.setStrength(Collator.TERTIARY); } /* * @see org.eclipse.jface.action.IAction#run() */ public void run() { try { final ISourceViewer viewer= getSourceViewer(); final IDocument document= viewer.getDocument(); int position= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset()) - 1; // Check whether we are in a java code partititon and the preference is enabled final IPreferenceStore store= getPreferenceStore(); if (!store.getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)) { super.run(); return; } // Ignore trailing white spaces char character= document.getChar(position); while (position > 0 && Character.isWhitespace(character)) { --position; character= document.getChar(position); } // Check whether left hand character of caret is valid identifier part if (Character.isJavaIdentifierPart(character)) { int offset= 0; int order= CollationElementIterator.NULLORDER; short previous= Short.MAX_VALUE; short next= Short.MAX_VALUE; // Acquire collator for partition around caret final ITypedRegion region= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, position); final String buffer= document.get(region.getOffset(), position - region.getOffset() + 1); final CollationElementIterator iterator= fCollator.getCollationElementIterator(buffer); // Iterate to first upper-case character iterator.setOffset(buffer.length() - 1); do { // Check whether we reached begin of word or single upper-case start offset= iterator.getOffset(); character= document.getChar(region.getOffset() + offset); if (!Character.isJavaIdentifierPart(character)) throw new BadLocationException(); else if (Character.isUpperCase(character)) { ++offset; break; } // Test next characters order= iterator.previous(); next= CollationElementIterator.tertiaryOrder(order); if (next <= previous) previous= next; else break; } while (order != CollationElementIterator.NULLORDER); // Check left character for multiple upper-case characters position= position - buffer.length() + offset - 1; character= document.getChar(position); if (!Character.isUpperCase(character)) { setCaretPosition(position + 1); return; } } } catch (BadLocationException exception) { // Use default behavior } super.run(); } /** * Sets the caret position to the sub-word boundary given with <code>position</code>. * * @param position Position where the action should move the caret */ protected abstract void setCaretPosition(int position); } /** * Text navigation action to navigate to the previous sub-word. * * @since 3.0 */ protected class NavigatePreviousSubWordAction extends PreviousSubWordAction { /** * Creates a new navigate previous sub-word action. */ public NavigatePreviousSubWordAction() { super(ST.WORD_PREVIOUS); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { final ISourceViewer viewer= getSourceViewer(); viewer.getTextWidget().setCaretOffset(modelOffset2WidgetOffset(viewer, position)); } } /** * Text operation action to delete the previous sub-word. * * @since 3.0 */ protected class DeletePreviousSubWordAction extends PreviousSubWordAction { /** * Creates a new delete previous sub-word action. */ public DeletePreviousSubWordAction() { super(ST.DELETE_WORD_PREVIOUS); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { final ISourceViewer viewer= getSourceViewer(); final int caret= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset()); try { viewer.getDocument().replace(position, caret - position, ""); //$NON-NLS-1$ } catch (BadLocationException exception) { // Should not happen } } } /** * Text operation action to select the previous sub-word. * * @since 3.0 */ protected class SelectPreviousSubWordAction extends PreviousSubWordAction { /** * Creates a new select previous sub-word action. */ public SelectPreviousSubWordAction() { super(ST.SELECT_WORD_PREVIOUS); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { final ISourceViewer viewer= getSourceViewer(); final StyledText text= viewer.getTextWidget(); if (text != null && !text.isDisposed()) { final Point selection= text.getSelection(); text.setSelectionRange(selection.y, modelOffset2WidgetOffset(viewer, position) - selection.y); final Event event= new Event(); event.x= text.getSelection().x; event.y= text.getSelection().y; text.notifyListeners(SWT.Selection, 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(new MarkerAnnotationPreferences()); } 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 } /* * @see org.eclipse.ui.texteditor.AbstractTextEditor#createNavigationActions() */ protected void createNavigationActions() { super.createNavigationActions(); final StyledText textWidget= getSourceViewer().getTextWidget(); IAction action= new SmartLineStartAction(textWidget, false); action.setActionDefinitionId(ITextEditorActionDefinitionIds.LINE_START); setAction(ITextEditorActionDefinitionIds.LINE_START, action); action= new SmartLineStartAction(textWidget, true); action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_LINE_START); setAction(ITextEditorActionDefinitionIds.SELECT_LINE_START, action); action= new NavigatePreviousSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.WORD_PREVIOUS); setAction(ITextEditorActionDefinitionIds.WORD_PREVIOUS, action); textWidget.setKeyBinding(SWT.CTRL | SWT.ARROW_LEFT, SWT.NULL); action= new NavigateNextSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.WORD_NEXT); setAction(ITextEditorActionDefinitionIds.WORD_NEXT, action); textWidget.setKeyBinding(SWT.CTRL | SWT.ARROW_RIGHT, SWT.NULL); action= new DeletePreviousSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.DELETE_PREVIOUS_WORD); setAction(ITextEditorActionDefinitionIds.DELETE_PREVIOUS_WORD, action); textWidget.setKeyBinding(SWT.CTRL | SWT.BS, SWT.NULL); action= new DeleteNextSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.DELETE_NEXT_WORD); setAction(ITextEditorActionDefinitionIds.DELETE_NEXT_WORD, action); textWidget.setKeyBinding(SWT.CTRL | SWT.DEL, SWT.NULL); action= new SelectPreviousSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS); setAction(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS, action); textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_LEFT, SWT.NULL); action= new SelectNextSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT); setAction(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT, action); textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_RIGHT, SWT.NULL); } }
39,995
Bug 39995 [navigation] Forward history cleared after going back in navigation history
build I20030710 - select a method call to a method in the same class - hit F3 to open the declaration - use the back buttons to go back to the call site - the forward history gets cleared shortly thereafter, making it more difficult to get back to the declaration Seems to only occur for navigations within the same file.
verified fixed
0780d78
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-08-26T14:29:30Z
2003-07-13T21: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.text.CollationElementIterator; import java.text.Collator; import java.text.RuleBasedCollator; 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.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.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; 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.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.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.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.swt.SWT; import org.eclipse.swt.custom.BidiSegmentEvent; import org.eclipse.swt.custom.BidiSegmentListener; import org.eclipse.swt.custom.ST; 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.Event; import org.eclipse.swt.widgets.Shell; 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.DefaultMarkerAnnotationAccess; 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.MarkerAnnotationPreferences; import org.eclipse.ui.texteditor.ResourceAction; import org.eclipse.ui.texteditor.SourceViewerDecorationSupport; import org.eclipse.ui.texteditor.TextEditorAction; import org.eclipse.ui.texteditor.TextNavigationAction; 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; /** * 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; int fontStyle= oldStyleRange== null ? SWT.NORMAL : oldStyleRange.fontStyle; StyleRange styleRange= new StyleRange(offset, length, foregroundColor, backgroundColor, fontStyle); 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 extends DefaultMarkerAnnotationAccess { public AnnotationAccess(MarkerAnnotationPreferences markerAnnotationPreferences) { super(markerAnnotationPreferences); } /* * @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); } } /** * This action implements smart home. * * Instead of going to the start of a line it does the following: * * - if smart home/end is enabled and the caret is after the line's first non-whitespace then the caret is moved directly before it, taking JavaDoc and multi-line comments into account. * - if the caret is before the line's first non-whitespace the caret is moved to the beginning of the line * - if the caret is at the beginning of the line see first case. * * @since 3.0 */ protected class SmartLineStartAction extends LineStartAction { /** * Creates a new smart line start action * * @param textWidget the styled text widget * @param doSelect a boolean flag which tells if the text up to the beginning of the line should be selected */ public SmartLineStartAction(final StyledText textWidget, final boolean doSelect) { super(textWidget, doSelect); } /* * @see org.eclipse.ui.texteditor.AbstractTextEditor.LineStartAction#getLineStartPosition(java.lang.String, int, java.lang.String) */ protected int getLineStartPosition(final IDocument document, final String line, final int length, final int offset) { String type= IDocument.DEFAULT_CONTENT_TYPE; try { type= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, offset).getType(); } catch (BadLocationException exception) { // Should not happen } int index= super.getLineStartPosition(document, line, length, offset); if (type.equals(IJavaPartitions.JAVA_DOC) || type.equals(IJavaPartitions.JAVA_MULTI_LINE_COMMENT)) { if (index < length - 1 && line.charAt(index) == '*' && line.charAt(index + 1) != '/') { do { ++index; } while (index < length && Character.isWhitespace(line.charAt(index))); } } else { if (index < length - 1 && line.charAt(index) == '/' && line.charAt(++index) == '/') { do { ++index; } while (index < length && Character.isWhitespace(line.charAt(index))); } } return index; } } /** * Text navigation action to navigate to the next sub-word. * * @since 3.0 */ protected abstract class NextSubWordAction extends TextNavigationAction { /** Collator to determine the sub-word boundaries */ private final RuleBasedCollator fCollator= (RuleBasedCollator)Collator.getInstance(); /** * Creates a new next sub-word action. * * @param code Action code for the default operation. Must be an action code from @see org.eclipse.swt.custom.ST. */ protected NextSubWordAction(int code) { super(getSourceViewer().getTextWidget(), code); // Only compare upper-/lower case fCollator.setStrength(Collator.TERTIARY); } /* * @see org.eclipse.jface.action.IAction#run() */ public void run() { try { final ISourceViewer viewer= getSourceViewer(); final IDocument document= viewer.getDocument(); int position= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset()); // Check whether we are in a java code partititon and the preference is enabled final IPreferenceStore store= getPreferenceStore(); final ITypedRegion region= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, position); if (!store.getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)) { super.run(); return; } // Check whether right hand character of caret is valid identifier start if (Character.isJavaIdentifierStart(document.getChar(position))) { int offset= 0; int order= CollationElementIterator.NULLORDER; short previous= Short.MAX_VALUE; short next= Short.MAX_VALUE; // Acquire collator for partition around caret final String buffer= document.get(position, region.getOffset() + region.getLength() - position); final CollationElementIterator iterator= fCollator.getCollationElementIterator(buffer); // Iterate to first upper-case character do { // Check whether we reached end of word offset= iterator.getOffset(); if (!Character.isJavaIdentifierPart(document.getChar(position + offset))) throw new BadLocationException(); // Test next characters order= iterator.next(); next= CollationElementIterator.tertiaryOrder(order); if (next <= previous) previous= next; else break; } while (order != CollationElementIterator.NULLORDER); // Check for leading underscores position += offset; if (Character.getType(document.getChar(position - 1)) != Character.CONNECTOR_PUNCTUATION) { setCaretPosition(position); return; } } } catch (BadLocationException exception) { // Use default behavior } super.run(); } /** * Sets the caret position to the sub-word boundary given with <code>position</code>. * * @param position Position where the action should move the caret */ protected abstract void setCaretPosition(int position); } /** * Text navigation action to navigate to the next sub-word. * * @since 3.0 */ protected class NavigateNextSubWordAction extends NextSubWordAction { /** * Creates a new navigate next sub-word action. */ public NavigateNextSubWordAction() { super(ST.WORD_NEXT); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { final ISourceViewer viewer= getSourceViewer(); viewer.getTextWidget().setCaretOffset(modelOffset2WidgetOffset(viewer, position)); } } /** * Text operation action to delete the next sub-word. * * @since 3.0 */ protected class DeleteNextSubWordAction extends NextSubWordAction { /** * Creates a new delete next sub-word action. */ public DeleteNextSubWordAction() { super(ST.DELETE_WORD_NEXT); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { final ISourceViewer viewer= getSourceViewer(); final int caret= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset()); try { viewer.getDocument().replace(caret, position - caret, ""); //$NON-NLS-1$ } catch (BadLocationException exception) { // Should not happen } } } /** * Text operation action to select the next sub-word. * * @since 3.0 */ protected class SelectNextSubWordAction extends NextSubWordAction { /** * Creates a new select next sub-word action. */ public SelectNextSubWordAction() { super(ST.SELECT_WORD_NEXT); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { final ISourceViewer viewer= getSourceViewer(); final StyledText text= viewer.getTextWidget(); if (text != null && !text.isDisposed()) { final Point selection= text.getSelection(); text.setSelectionRange(selection.x, modelOffset2WidgetOffset(viewer, position) - selection.x); final Event event= new Event(); event.x= text.getSelection().x; event.y= text.getSelection().y; text.notifyListeners(SWT.Selection, event); } } } /** * Text navigation action to navigate to the previous sub-word. * * @since 3.0 */ protected abstract class PreviousSubWordAction extends TextNavigationAction { /** Collator to determine the sub-word boundaries */ private final RuleBasedCollator fCollator= (RuleBasedCollator)Collator.getInstance(); /** * Creates a new previous sub-word action. * * @param code Action code for the default operation. Must be an action code from @see org.eclipse.swt.custom.ST. */ protected PreviousSubWordAction(final int code) { super(getSourceViewer().getTextWidget(), code); // Only compare upper-/lower case fCollator.setStrength(Collator.TERTIARY); } /* * @see org.eclipse.jface.action.IAction#run() */ public void run() { try { final ISourceViewer viewer= getSourceViewer(); final IDocument document= viewer.getDocument(); int position= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset()) - 1; // Check whether we are in a java code partititon and the preference is enabled final IPreferenceStore store= getPreferenceStore(); if (!store.getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)) { super.run(); return; } // Ignore trailing white spaces char character= document.getChar(position); while (position > 0 && Character.isWhitespace(character)) { --position; character= document.getChar(position); } // Check whether left hand character of caret is valid identifier part if (Character.isJavaIdentifierPart(character)) { int offset= 0; int order= CollationElementIterator.NULLORDER; short previous= Short.MAX_VALUE; short next= Short.MAX_VALUE; // Acquire collator for partition around caret final ITypedRegion region= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, position); final String buffer= document.get(region.getOffset(), position - region.getOffset() + 1); final CollationElementIterator iterator= fCollator.getCollationElementIterator(buffer); // Iterate to first upper-case character iterator.setOffset(buffer.length() - 1); do { // Check whether we reached begin of word or single upper-case start offset= iterator.getOffset(); character= document.getChar(region.getOffset() + offset); if (!Character.isJavaIdentifierPart(character)) throw new BadLocationException(); else if (Character.isUpperCase(character)) { ++offset; break; } // Test next characters order= iterator.previous(); next= CollationElementIterator.tertiaryOrder(order); if (next <= previous) previous= next; else break; } while (order != CollationElementIterator.NULLORDER); // Check left character for multiple upper-case characters position= position - buffer.length() + offset - 1; character= document.getChar(position); if (!Character.isUpperCase(character)) { setCaretPosition(position + 1); return; } } } catch (BadLocationException exception) { // Use default behavior } super.run(); } /** * Sets the caret position to the sub-word boundary given with <code>position</code>. * * @param position Position where the action should move the caret */ protected abstract void setCaretPosition(int position); } /** * Text navigation action to navigate to the previous sub-word. * * @since 3.0 */ protected class NavigatePreviousSubWordAction extends PreviousSubWordAction { /** * Creates a new navigate previous sub-word action. */ public NavigatePreviousSubWordAction() { super(ST.WORD_PREVIOUS); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { final ISourceViewer viewer= getSourceViewer(); viewer.getTextWidget().setCaretOffset(modelOffset2WidgetOffset(viewer, position)); } } /** * Text operation action to delete the previous sub-word. * * @since 3.0 */ protected class DeletePreviousSubWordAction extends PreviousSubWordAction { /** * Creates a new delete previous sub-word action. */ public DeletePreviousSubWordAction() { super(ST.DELETE_WORD_PREVIOUS); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { final ISourceViewer viewer= getSourceViewer(); final int caret= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset()); try { viewer.getDocument().replace(position, caret - position, ""); //$NON-NLS-1$ } catch (BadLocationException exception) { // Should not happen } } } /** * Text operation action to select the previous sub-word. * * @since 3.0 */ protected class SelectPreviousSubWordAction extends PreviousSubWordAction { /** * Creates a new select previous sub-word action. */ public SelectPreviousSubWordAction() { super(ST.SELECT_WORD_PREVIOUS); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { final ISourceViewer viewer= getSourceViewer(); final StyledText text= viewer.getTextWidget(); if (text != null && !text.isDisposed()) { final Point selection= text.getSelection(); text.setSelectionRange(selection.y, modelOffset2WidgetOffset(viewer, position) - selection.y); final Event event= new Event(); event.x= text.getSelection().x; event.y= text.getSelection().y; text.notifyListeners(SWT.Selection, 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(new MarkerAnnotationPreferences()); } 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 } /* * @see org.eclipse.ui.texteditor.AbstractTextEditor#createNavigationActions() */ protected void createNavigationActions() { super.createNavigationActions(); final StyledText textWidget= getSourceViewer().getTextWidget(); IAction action= new SmartLineStartAction(textWidget, false); action.setActionDefinitionId(ITextEditorActionDefinitionIds.LINE_START); setAction(ITextEditorActionDefinitionIds.LINE_START, action); action= new SmartLineStartAction(textWidget, true); action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_LINE_START); setAction(ITextEditorActionDefinitionIds.SELECT_LINE_START, action); action= new NavigatePreviousSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.WORD_PREVIOUS); setAction(ITextEditorActionDefinitionIds.WORD_PREVIOUS, action); textWidget.setKeyBinding(SWT.CTRL | SWT.ARROW_LEFT, SWT.NULL); action= new NavigateNextSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.WORD_NEXT); setAction(ITextEditorActionDefinitionIds.WORD_NEXT, action); textWidget.setKeyBinding(SWT.CTRL | SWT.ARROW_RIGHT, SWT.NULL); action= new DeletePreviousSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.DELETE_PREVIOUS_WORD); setAction(ITextEditorActionDefinitionIds.DELETE_PREVIOUS_WORD, action); textWidget.setKeyBinding(SWT.CTRL | SWT.BS, SWT.NULL); action= new DeleteNextSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.DELETE_NEXT_WORD); setAction(ITextEditorActionDefinitionIds.DELETE_NEXT_WORD, action); textWidget.setKeyBinding(SWT.CTRL | SWT.DEL, SWT.NULL); action= new SelectPreviousSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS); setAction(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS, action); textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_LEFT, SWT.NULL); action= new SelectNextSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT); setAction(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT, action); textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_RIGHT, SWT.NULL); } }
42,096
Bug 42096 Open type dialog deadlocks
I20030826 - start Eclipse so that the Java perspective is shown but the JDT plugin is not initially loaded - press the "Open type" toolbar button Observe: Eclipse deadlocks (see attached thread dump)
resolved fixed
ff50e90
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-08-27T15:15:33Z
2003-08-27T13:13:20Z
org.eclipse.jdt.ui/core
42,096
Bug 42096 Open type dialog deadlocks
I20030826 - start Eclipse so that the Java perspective is shown but the JDT plugin is not initially loaded - press the "Open type" toolbar button Observe: Eclipse deadlocks (see attached thread dump)
resolved fixed
ff50e90
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-08-27T15:15:33Z
2003-08-27T13:13:20Z
extension/org/eclipse/jdt/internal/corext/util/AllTypesCache.java
42,110
Bug 42110 ClassCastException in Java Search with package working set
M3 candidate I got the following class cast exception in Java Search using a Working Set STEPS 1) Open the JavaSearch Dialog 2) Select a working set (I made one called properties which had just org.eclipse.ui.views.properties in it) 3) Enter a search string (I entered focusLost) 4) Hit Search - nothing happens and exception is printed to log: Note this is fine using the Workbench search scope java.lang.ClassCastException: org/eclipse/jdt/internal/core/PackageFragment incompatible with org/eclipse/core/resources/IFolder 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.jdt.internal.ui.search.JavaSearchScopeFactory.addJavaElements (JavaSearchScopeFactory.java:176) at org.eclipse.jdt.internal.ui.search.JavaSearchScopeFactory.addJavaElements (JavaSearchScopeFactory.java:195) at org.eclipse.jdt.internal.ui.search.JavaSearchScopeFactory.createJavaSearchScope (JavaSearchScopeFactory.java:81) at org.eclipse.jdt.internal.ui.search.JavaSearchPage.performAction (JavaSearchPage.java:183) at org.eclipse.search.internal.ui.SearchDialog.performAction (SearchDialog.java:351) at org.eclipse.search.internal.ui.util.ExtendedDialogWindow.buttonPressed (ExtendedDialogWindow.java:140) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:423) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java) 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.jface.window.Window.runEventLoop(Window.java) at org.eclipse.jface.window.Window.open(Window.java:563) at org.eclipse.search.internal.ui.OpenSearchDialogAction.run (OpenSearchDialogAction.java:60) at org.eclipse.search.internal.ui.OpenSearchDialogAction.run (OpenSearchDialogAction.java:46) at org.eclipse.ui.internal.PluginAction.runWithEvent (PluginAction.java:263) at org.eclipse.ui.internal.WWinPluginAction.runWithEvent (WWinPluginAction.java:207) at org.eclipse.ui.internal.commands.ActionHandler.execute (ActionHandler.java:38) at org.eclipse.ui.internal.Workbench.press(Workbench.java:453) at org.eclipse.ui.internal.Workbench$2.handleEvent(Workbench.java:212) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java) at org.eclipse.swt.widgets.Display.filterEvent(Display.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.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.Tree.WM_CHAR(Tree.java:1289) 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.DispatchMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2036) at org.eclipse.ui.internal.Workbench.run(Workbench.java:2019) 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:295) at org.eclipse.core.launcher.Main.run(Main.java:751) at org.eclipse.core.launcher.Main.main(Main.java:587)
verified fixed
895bea2
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-08-27T15:19:53Z
2003-08-27T13:13:20Z
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.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IPath; import org.eclipse.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.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); } public IProject[] getJavaProjects(IJavaSearchScope scope) { IPath[] paths= scope.enclosingProjectsAndJars(); HashSet temp= new HashSet(); for (int i= 0; i < paths.length; i++) { IResource resource= ResourcesPlugin.getWorkspace().getRoot().findMember(paths[i]); if (resource != null && resource.getType() == IResource.PROJECT) temp.add(resource); } return (IProject[]) temp.toArray(new IProject[temp.size()]); } 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 } } javaElements.add(javaElement); } private void addJavaElements(Set javaElements, IJavaElement javaElement) { javaElements.add(javaElement); } private void addJavaElements(Set javaElements, IWorkingSet workingSet) { if (workingSet == null) return; IAdaptable[] elements= workingSet.getElements(); for (int i= 0; i < elements.length; i++) { 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]); } }
42,109
Bug 42109 Go to Previous target not acting like Go to Next target
Go to Previous target is searching through unselected targets such as warnings. The behavior is dissimilar from Go to Next target whose action is reflecting the selection of the drop down to configure targets. The checkmarks for the two are the same, but the behavior differs.
verified fixed
b2e4824
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-08-27T15:32:58Z
2003-08-27T13:13:20Z
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.text.CollationElementIterator; import java.text.Collator; import java.text.RuleBasedCollator; 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.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.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; 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.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.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.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.swt.SWT; import org.eclipse.swt.custom.BidiSegmentEvent; import org.eclipse.swt.custom.BidiSegmentListener; import org.eclipse.swt.custom.ST; 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.Event; import org.eclipse.swt.widgets.Shell; 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.DefaultMarkerAnnotationAccess; 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.MarkerAnnotationPreferences; import org.eclipse.ui.texteditor.ResourceAction; import org.eclipse.ui.texteditor.SourceViewerDecorationSupport; import org.eclipse.ui.texteditor.TextEditorAction; import org.eclipse.ui.texteditor.TextNavigationAction; 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; /** * 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; int fontStyle= oldStyleRange== null ? SWT.NORMAL : oldStyleRange.fontStyle; StyleRange styleRange= new StyleRange(offset, length, foregroundColor, backgroundColor, fontStyle); 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 extends DefaultMarkerAnnotationAccess { public AnnotationAccess(MarkerAnnotationPreferences markerAnnotationPreferences) { super(markerAnnotationPreferences); } /* * @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); } } /** * This action implements smart home. * * Instead of going to the start of a line it does the following: * * - if smart home/end is enabled and the caret is after the line's first non-whitespace then the caret is moved directly before it, taking JavaDoc and multi-line comments into account. * - if the caret is before the line's first non-whitespace the caret is moved to the beginning of the line * - if the caret is at the beginning of the line see first case. * * @since 3.0 */ protected class SmartLineStartAction extends LineStartAction { /** * Creates a new smart line start action * * @param textWidget the styled text widget * @param doSelect a boolean flag which tells if the text up to the beginning of the line should be selected */ public SmartLineStartAction(final StyledText textWidget, final boolean doSelect) { super(textWidget, doSelect); } /* * @see org.eclipse.ui.texteditor.AbstractTextEditor.LineStartAction#getLineStartPosition(java.lang.String, int, java.lang.String) */ protected int getLineStartPosition(final IDocument document, final String line, final int length, final int offset) { String type= IDocument.DEFAULT_CONTENT_TYPE; try { type= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, offset).getType(); } catch (BadLocationException exception) { // Should not happen } int index= super.getLineStartPosition(document, line, length, offset); if (type.equals(IJavaPartitions.JAVA_DOC) || type.equals(IJavaPartitions.JAVA_MULTI_LINE_COMMENT)) { if (index < length - 1 && line.charAt(index) == '*' && line.charAt(index + 1) != '/') { do { ++index; } while (index < length && Character.isWhitespace(line.charAt(index))); } } else { if (index < length - 1 && line.charAt(index) == '/' && line.charAt(++index) == '/') { do { ++index; } while (index < length && Character.isWhitespace(line.charAt(index))); } } return index; } } /** * Text navigation action to navigate to the next sub-word. * * @since 3.0 */ protected abstract class NextSubWordAction extends TextNavigationAction { /** Collator to determine the sub-word boundaries */ private final RuleBasedCollator fCollator= (RuleBasedCollator)Collator.getInstance(); /** * Creates a new next sub-word action. * * @param code Action code for the default operation. Must be an action code from @see org.eclipse.swt.custom.ST. */ protected NextSubWordAction(int code) { super(getSourceViewer().getTextWidget(), code); // Only compare upper-/lower case fCollator.setStrength(Collator.TERTIARY); } /* * @see org.eclipse.jface.action.IAction#run() */ public void run() { try { final ISourceViewer viewer= getSourceViewer(); final IDocument document= viewer.getDocument(); int position= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset()); // Check whether we are in a java code partititon and the preference is enabled final IPreferenceStore store= getPreferenceStore(); final ITypedRegion region= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, position); if (!store.getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)) { super.run(); return; } // Check whether right hand character of caret is valid identifier start if (Character.isJavaIdentifierStart(document.getChar(position))) { int offset= 0; int order= CollationElementIterator.NULLORDER; short previous= Short.MAX_VALUE; short next= Short.MAX_VALUE; // Acquire collator for partition around caret final String buffer= document.get(position, region.getOffset() + region.getLength() - position); final CollationElementIterator iterator= fCollator.getCollationElementIterator(buffer); // Iterate to first upper-case character do { // Check whether we reached end of word offset= iterator.getOffset(); if (!Character.isJavaIdentifierPart(document.getChar(position + offset))) throw new BadLocationException(); // Test next characters order= iterator.next(); next= CollationElementIterator.tertiaryOrder(order); if (next <= previous) previous= next; else break; } while (order != CollationElementIterator.NULLORDER); // Check for leading underscores position += offset; if (Character.getType(document.getChar(position - 1)) != Character.CONNECTOR_PUNCTUATION) { setCaretPosition(position); return; } } } catch (BadLocationException exception) { // Use default behavior } super.run(); } /** * Sets the caret position to the sub-word boundary given with <code>position</code>. * * @param position Position where the action should move the caret */ protected abstract void setCaretPosition(int position); } /** * Text navigation action to navigate to the next sub-word. * * @since 3.0 */ protected class NavigateNextSubWordAction extends NextSubWordAction { /** * Creates a new navigate next sub-word action. */ public NavigateNextSubWordAction() { super(ST.WORD_NEXT); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { final ISourceViewer viewer= getSourceViewer(); viewer.getTextWidget().setCaretOffset(modelOffset2WidgetOffset(viewer, position)); } } /** * Text operation action to delete the next sub-word. * * @since 3.0 */ protected class DeleteNextSubWordAction extends NextSubWordAction { /** * Creates a new delete next sub-word action. */ public DeleteNextSubWordAction() { super(ST.DELETE_WORD_NEXT); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { final ISourceViewer viewer= getSourceViewer(); final int caret= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset()); try { viewer.getDocument().replace(caret, position - caret, ""); //$NON-NLS-1$ } catch (BadLocationException exception) { // Should not happen } } } /** * Text operation action to select the next sub-word. * * @since 3.0 */ protected class SelectNextSubWordAction extends NextSubWordAction { /** * Creates a new select next sub-word action. */ public SelectNextSubWordAction() { super(ST.SELECT_WORD_NEXT); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { final ISourceViewer viewer= getSourceViewer(); final StyledText text= viewer.getTextWidget(); if (text != null && !text.isDisposed()) { final Point selection= text.getSelection(); text.setSelectionRange(selection.x, modelOffset2WidgetOffset(viewer, position) - selection.x); final Event event= new Event(); event.x= text.getSelection().x; event.y= text.getSelection().y; text.notifyListeners(SWT.Selection, event); } } } /** * Text navigation action to navigate to the previous sub-word. * * @since 3.0 */ protected abstract class PreviousSubWordAction extends TextNavigationAction { /** Collator to determine the sub-word boundaries */ private final RuleBasedCollator fCollator= (RuleBasedCollator)Collator.getInstance(); /** * Creates a new previous sub-word action. * * @param code Action code for the default operation. Must be an action code from @see org.eclipse.swt.custom.ST. */ protected PreviousSubWordAction(final int code) { super(getSourceViewer().getTextWidget(), code); // Only compare upper-/lower case fCollator.setStrength(Collator.TERTIARY); } /* * @see org.eclipse.jface.action.IAction#run() */ public void run() { try { final ISourceViewer viewer= getSourceViewer(); final IDocument document= viewer.getDocument(); int position= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset()) - 1; // Check whether we are in a java code partititon and the preference is enabled final IPreferenceStore store= getPreferenceStore(); if (!store.getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)) { super.run(); return; } // Ignore trailing white spaces char character= document.getChar(position); while (position > 0 && Character.isWhitespace(character)) { --position; character= document.getChar(position); } // Check whether left hand character of caret is valid identifier part if (Character.isJavaIdentifierPart(character)) { int offset= 0; int order= CollationElementIterator.NULLORDER; short previous= Short.MAX_VALUE; short next= Short.MAX_VALUE; // Acquire collator for partition around caret final ITypedRegion region= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, position); final String buffer= document.get(region.getOffset(), position - region.getOffset() + 1); final CollationElementIterator iterator= fCollator.getCollationElementIterator(buffer); // Iterate to first upper-case character iterator.setOffset(buffer.length() - 1); do { // Check whether we reached begin of word or single upper-case start offset= iterator.getOffset(); character= document.getChar(region.getOffset() + offset); if (!Character.isJavaIdentifierPart(character)) throw new BadLocationException(); else if (Character.isUpperCase(character)) { ++offset; break; } // Test next characters order= iterator.previous(); next= CollationElementIterator.tertiaryOrder(order); if (next <= previous) previous= next; else break; } while (order != CollationElementIterator.NULLORDER); // Check left character for multiple upper-case characters position= position - buffer.length() + offset - 1; character= document.getChar(position); if (!Character.isUpperCase(character)) { setCaretPosition(position + 1); return; } } } catch (BadLocationException exception) { // Use default behavior } super.run(); } /** * Sets the caret position to the sub-word boundary given with <code>position</code>. * * @param position Position where the action should move the caret */ protected abstract void setCaretPosition(int position); } /** * Text navigation action to navigate to the previous sub-word. * * @since 3.0 */ protected class NavigatePreviousSubWordAction extends PreviousSubWordAction { /** * Creates a new navigate previous sub-word action. */ public NavigatePreviousSubWordAction() { super(ST.WORD_PREVIOUS); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { final ISourceViewer viewer= getSourceViewer(); viewer.getTextWidget().setCaretOffset(modelOffset2WidgetOffset(viewer, position)); } } /** * Text operation action to delete the previous sub-word. * * @since 3.0 */ protected class DeletePreviousSubWordAction extends PreviousSubWordAction { /** * Creates a new delete previous sub-word action. */ public DeletePreviousSubWordAction() { super(ST.DELETE_WORD_PREVIOUS); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { final ISourceViewer viewer= getSourceViewer(); final int caret= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset()); try { viewer.getDocument().replace(position, caret - position, ""); //$NON-NLS-1$ } catch (BadLocationException exception) { // Should not happen } } } /** * Text operation action to select the previous sub-word. * * @since 3.0 */ protected class SelectPreviousSubWordAction extends PreviousSubWordAction { /** * Creates a new select previous sub-word action. */ public SelectPreviousSubWordAction() { super(ST.SELECT_WORD_PREVIOUS); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { final ISourceViewer viewer= getSourceViewer(); final StyledText text= viewer.getTextWidget(); if (text != null && !text.isDisposed()) { final Point selection= text.getSelection(); text.setSelectionRange(selection.y, modelOffset2WidgetOffset(viewer, position) - selection.y); final Event event= new Event(); event.x= text.getSelection().x; event.y= text.getSelection().y; text.notifyListeners(SWT.Selection, 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(new MarkerAnnotationPreferences()); } 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; // PR 39995: [navigation] Forward history cleared after going back in navigation history: // mark only in navigation history if the cursor is being moved (which it isn't if // this is called from a PostSelectionEvent that should only update the magnet) if (moveCursor && (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 } /* * @see org.eclipse.ui.texteditor.AbstractTextEditor#createNavigationActions() */ protected void createNavigationActions() { super.createNavigationActions(); final StyledText textWidget= getSourceViewer().getTextWidget(); IAction action= new SmartLineStartAction(textWidget, false); action.setActionDefinitionId(ITextEditorActionDefinitionIds.LINE_START); setAction(ITextEditorActionDefinitionIds.LINE_START, action); action= new SmartLineStartAction(textWidget, true); action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_LINE_START); setAction(ITextEditorActionDefinitionIds.SELECT_LINE_START, action); action= new NavigatePreviousSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.WORD_PREVIOUS); setAction(ITextEditorActionDefinitionIds.WORD_PREVIOUS, action); textWidget.setKeyBinding(SWT.CTRL | SWT.ARROW_LEFT, SWT.NULL); action= new NavigateNextSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.WORD_NEXT); setAction(ITextEditorActionDefinitionIds.WORD_NEXT, action); textWidget.setKeyBinding(SWT.CTRL | SWT.ARROW_RIGHT, SWT.NULL); action= new DeletePreviousSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.DELETE_PREVIOUS_WORD); setAction(ITextEditorActionDefinitionIds.DELETE_PREVIOUS_WORD, action); textWidget.setKeyBinding(SWT.CTRL | SWT.BS, SWT.NULL); action= new DeleteNextSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.DELETE_NEXT_WORD); setAction(ITextEditorActionDefinitionIds.DELETE_NEXT_WORD, action); textWidget.setKeyBinding(SWT.CTRL | SWT.DEL, SWT.NULL); action= new SelectPreviousSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS); setAction(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS, action); textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_LEFT, SWT.NULL); action= new SelectNextSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT); setAction(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT, action); textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_RIGHT, SWT.NULL); } }
41,988
Bug 41988 Select Next/Previous Word strange for CamelCase java words
I20030820 + export20030826_1219 - Ctrl+T, type "TestCase", press Enter - Arrow_Left - Ctrl+Shift+Arrow_Right - Ctrl+Shift+Arrow_Right - Ctrl+Shift+Arrow_Left => I would expect that "Test" is selected, but "Case " is. BTW: Try walking around with Ctrl+Shift+Arrow_Left/Arrow_Right ;-)
verified fixed
f3939d3
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-08-27T15:43:59Z
2003-08-26T15: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.text.CollationElementIterator; import java.text.Collator; import java.text.RuleBasedCollator; 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.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.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; 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.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.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.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.swt.SWT; import org.eclipse.swt.custom.BidiSegmentEvent; import org.eclipse.swt.custom.BidiSegmentListener; import org.eclipse.swt.custom.ST; 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.Event; import org.eclipse.swt.widgets.Shell; 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.DefaultMarkerAnnotationAccess; 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.MarkerAnnotationPreferences; import org.eclipse.ui.texteditor.ResourceAction; import org.eclipse.ui.texteditor.SourceViewerDecorationSupport; import org.eclipse.ui.texteditor.TextEditorAction; import org.eclipse.ui.texteditor.TextNavigationAction; 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; /** * 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; int fontStyle= oldStyleRange== null ? SWT.NORMAL : oldStyleRange.fontStyle; StyleRange styleRange= new StyleRange(offset, length, foregroundColor, backgroundColor, fontStyle); 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 extends DefaultMarkerAnnotationAccess { public AnnotationAccess(MarkerAnnotationPreferences markerAnnotationPreferences) { super(markerAnnotationPreferences); } /* * @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); } } /** * This action implements smart home. * * Instead of going to the start of a line it does the following: * * - if smart home/end is enabled and the caret is after the line's first non-whitespace then the caret is moved directly before it, taking JavaDoc and multi-line comments into account. * - if the caret is before the line's first non-whitespace the caret is moved to the beginning of the line * - if the caret is at the beginning of the line see first case. * * @since 3.0 */ protected class SmartLineStartAction extends LineStartAction { /** * Creates a new smart line start action * * @param textWidget the styled text widget * @param doSelect a boolean flag which tells if the text up to the beginning of the line should be selected */ public SmartLineStartAction(final StyledText textWidget, final boolean doSelect) { super(textWidget, doSelect); } /* * @see org.eclipse.ui.texteditor.AbstractTextEditor.LineStartAction#getLineStartPosition(java.lang.String, int, java.lang.String) */ protected int getLineStartPosition(final IDocument document, final String line, final int length, final int offset) { String type= IDocument.DEFAULT_CONTENT_TYPE; try { type= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, offset).getType(); } catch (BadLocationException exception) { // Should not happen } int index= super.getLineStartPosition(document, line, length, offset); if (type.equals(IJavaPartitions.JAVA_DOC) || type.equals(IJavaPartitions.JAVA_MULTI_LINE_COMMENT)) { if (index < length - 1 && line.charAt(index) == '*' && line.charAt(index + 1) != '/') { do { ++index; } while (index < length && Character.isWhitespace(line.charAt(index))); } } else { if (index < length - 1 && line.charAt(index) == '/' && line.charAt(++index) == '/') { do { ++index; } while (index < length && Character.isWhitespace(line.charAt(index))); } } return index; } } /** * Text navigation action to navigate to the next sub-word. * * @since 3.0 */ protected abstract class NextSubWordAction extends TextNavigationAction { /** Collator to determine the sub-word boundaries */ private final RuleBasedCollator fCollator= (RuleBasedCollator)Collator.getInstance(); /** * Creates a new next sub-word action. * * @param code Action code for the default operation. Must be an action code from @see org.eclipse.swt.custom.ST. */ protected NextSubWordAction(int code) { super(getSourceViewer().getTextWidget(), code); // Only compare upper-/lower case fCollator.setStrength(Collator.TERTIARY); } /* * @see org.eclipse.jface.action.IAction#run() */ public void run() { try { final ISourceViewer viewer= getSourceViewer(); final IDocument document= viewer.getDocument(); int position= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset()); // Check whether we are in a java code partititon and the preference is enabled final IPreferenceStore store= getPreferenceStore(); final ITypedRegion region= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, position); if (!store.getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)) { super.run(); return; } // Check whether right hand character of caret is valid identifier start if (Character.isJavaIdentifierStart(document.getChar(position))) { int offset= 0; int order= CollationElementIterator.NULLORDER; short previous= Short.MAX_VALUE; short next= Short.MAX_VALUE; // Acquire collator for partition around caret final String buffer= document.get(position, region.getOffset() + region.getLength() - position); final CollationElementIterator iterator= fCollator.getCollationElementIterator(buffer); // Iterate to first upper-case character do { // Check whether we reached end of word offset= iterator.getOffset(); if (!Character.isJavaIdentifierPart(document.getChar(position + offset))) throw new BadLocationException(); // Test next characters order= iterator.next(); next= CollationElementIterator.tertiaryOrder(order); if (next <= previous) previous= next; else break; } while (order != CollationElementIterator.NULLORDER); // Check for leading underscores position += offset; if (Character.getType(document.getChar(position - 1)) != Character.CONNECTOR_PUNCTUATION) { setCaretPosition(position); return; } } } catch (BadLocationException exception) { // Use default behavior } super.run(); } /** * Sets the caret position to the sub-word boundary given with <code>position</code>. * * @param position Position where the action should move the caret */ protected abstract void setCaretPosition(int position); } /** * Text navigation action to navigate to the next sub-word. * * @since 3.0 */ protected class NavigateNextSubWordAction extends NextSubWordAction { /** * Creates a new navigate next sub-word action. */ public NavigateNextSubWordAction() { super(ST.WORD_NEXT); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { final ISourceViewer viewer= getSourceViewer(); viewer.getTextWidget().setCaretOffset(modelOffset2WidgetOffset(viewer, position)); } } /** * Text operation action to delete the next sub-word. * * @since 3.0 */ protected class DeleteNextSubWordAction extends NextSubWordAction { /** * Creates a new delete next sub-word action. */ public DeleteNextSubWordAction() { super(ST.DELETE_WORD_NEXT); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { final ISourceViewer viewer= getSourceViewer(); final int caret= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset()); try { viewer.getDocument().replace(caret, position - caret, ""); //$NON-NLS-1$ } catch (BadLocationException exception) { // Should not happen } } } /** * Text operation action to select the next sub-word. * * @since 3.0 */ protected class SelectNextSubWordAction extends NextSubWordAction { /** * Creates a new select next sub-word action. */ public SelectNextSubWordAction() { super(ST.SELECT_WORD_NEXT); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { final ISourceViewer viewer= getSourceViewer(); final StyledText text= viewer.getTextWidget(); if (text != null && !text.isDisposed()) { final Point selection= text.getSelection(); text.setSelectionRange(selection.x, modelOffset2WidgetOffset(viewer, position) - selection.x); final Event event= new Event(); event.x= text.getSelection().x; event.y= text.getSelection().y; text.notifyListeners(SWT.Selection, event); } } } /** * Text navigation action to navigate to the previous sub-word. * * @since 3.0 */ protected abstract class PreviousSubWordAction extends TextNavigationAction { /** Collator to determine the sub-word boundaries */ private final RuleBasedCollator fCollator= (RuleBasedCollator)Collator.getInstance(); /** * Creates a new previous sub-word action. * * @param code Action code for the default operation. Must be an action code from @see org.eclipse.swt.custom.ST. */ protected PreviousSubWordAction(final int code) { super(getSourceViewer().getTextWidget(), code); // Only compare upper-/lower case fCollator.setStrength(Collator.TERTIARY); } /* * @see org.eclipse.jface.action.IAction#run() */ public void run() { try { final ISourceViewer viewer= getSourceViewer(); final IDocument document= viewer.getDocument(); int position= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset()) - 1; // Check whether we are in a java code partititon and the preference is enabled final IPreferenceStore store= getPreferenceStore(); if (!store.getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)) { super.run(); return; } // Ignore trailing white spaces char character= document.getChar(position); while (position > 0 && Character.isWhitespace(character)) { --position; character= document.getChar(position); } // Check whether left hand character of caret is valid identifier part if (Character.isJavaIdentifierPart(character)) { int offset= 0; int order= CollationElementIterator.NULLORDER; short previous= Short.MAX_VALUE; short next= Short.MAX_VALUE; // Acquire collator for partition around caret final ITypedRegion region= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, position); final String buffer= document.get(region.getOffset(), position - region.getOffset() + 1); final CollationElementIterator iterator= fCollator.getCollationElementIterator(buffer); // Iterate to first upper-case character iterator.setOffset(buffer.length() - 1); do { // Check whether we reached begin of word or single upper-case start offset= iterator.getOffset(); character= document.getChar(region.getOffset() + offset); if (!Character.isJavaIdentifierPart(character)) throw new BadLocationException(); else if (Character.isUpperCase(character)) { ++offset; break; } // Test next characters order= iterator.previous(); next= CollationElementIterator.tertiaryOrder(order); if (next <= previous) previous= next; else break; } while (order != CollationElementIterator.NULLORDER); // Check left character for multiple upper-case characters position= position - buffer.length() + offset - 1; character= document.getChar(position); if (!Character.isUpperCase(character)) { setCaretPosition(position + 1); return; } } } catch (BadLocationException exception) { // Use default behavior } super.run(); } /** * Sets the caret position to the sub-word boundary given with <code>position</code>. * * @param position Position where the action should move the caret */ protected abstract void setCaretPosition(int position); } /** * Text navigation action to navigate to the previous sub-word. * * @since 3.0 */ protected class NavigatePreviousSubWordAction extends PreviousSubWordAction { /** * Creates a new navigate previous sub-word action. */ public NavigatePreviousSubWordAction() { super(ST.WORD_PREVIOUS); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { final ISourceViewer viewer= getSourceViewer(); viewer.getTextWidget().setCaretOffset(modelOffset2WidgetOffset(viewer, position)); } } /** * Text operation action to delete the previous sub-word. * * @since 3.0 */ protected class DeletePreviousSubWordAction extends PreviousSubWordAction { /** * Creates a new delete previous sub-word action. */ public DeletePreviousSubWordAction() { super(ST.DELETE_WORD_PREVIOUS); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { final ISourceViewer viewer= getSourceViewer(); final int caret= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset()); try { viewer.getDocument().replace(position, caret - position, ""); //$NON-NLS-1$ } catch (BadLocationException exception) { // Should not happen } } } /** * Text operation action to select the previous sub-word. * * @since 3.0 */ protected class SelectPreviousSubWordAction extends PreviousSubWordAction { /** * Creates a new select previous sub-word action. */ public SelectPreviousSubWordAction() { super(ST.SELECT_WORD_PREVIOUS); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { final ISourceViewer viewer= getSourceViewer(); final StyledText text= viewer.getTextWidget(); if (text != null && !text.isDisposed()) { final Point selection= text.getSelection(); text.setSelectionRange(selection.y, modelOffset2WidgetOffset(viewer, position) - selection.y); final Event event= new Event(); event.x= text.getSelection().x; event.y= text.getSelection().y; text.notifyListeners(SWT.Selection, 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(new MarkerAnnotationPreferences()); } 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; // PR 39995: [navigation] Forward history cleared after going back in navigation history: // mark only in navigation history if the cursor is being moved (which it isn't if // this is called from a PostSelectionEvent that should only update the magnet) if (moveCursor && (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; /* * Fixes bug 41689 * This code can be simplified if we decide that * we don't allow to use different settings for go to * previous and go to next annotation. */ key= annotationPref.getIsGoToNextNavigationTargetKey(); // 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 } /* * @see org.eclipse.ui.texteditor.AbstractTextEditor#createNavigationActions() */ protected void createNavigationActions() { super.createNavigationActions(); final StyledText textWidget= getSourceViewer().getTextWidget(); IAction action= new SmartLineStartAction(textWidget, false); action.setActionDefinitionId(ITextEditorActionDefinitionIds.LINE_START); setAction(ITextEditorActionDefinitionIds.LINE_START, action); action= new SmartLineStartAction(textWidget, true); action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_LINE_START); setAction(ITextEditorActionDefinitionIds.SELECT_LINE_START, action); action= new NavigatePreviousSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.WORD_PREVIOUS); setAction(ITextEditorActionDefinitionIds.WORD_PREVIOUS, action); textWidget.setKeyBinding(SWT.CTRL | SWT.ARROW_LEFT, SWT.NULL); action= new NavigateNextSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.WORD_NEXT); setAction(ITextEditorActionDefinitionIds.WORD_NEXT, action); textWidget.setKeyBinding(SWT.CTRL | SWT.ARROW_RIGHT, SWT.NULL); action= new DeletePreviousSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.DELETE_PREVIOUS_WORD); setAction(ITextEditorActionDefinitionIds.DELETE_PREVIOUS_WORD, action); textWidget.setKeyBinding(SWT.CTRL | SWT.BS, SWT.NULL); action= new DeleteNextSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.DELETE_NEXT_WORD); setAction(ITextEditorActionDefinitionIds.DELETE_NEXT_WORD, action); textWidget.setKeyBinding(SWT.CTRL | SWT.DEL, SWT.NULL); action= new SelectPreviousSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS); setAction(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS, action); textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_LEFT, SWT.NULL); action= new SelectNextSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT); setAction(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT, action); textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_RIGHT, SWT.NULL); } }
42,159
Bug 42159 Searching for references ignores selected working set [search]
In build I20030826 (M3 candidate), if I select a java method and perform a Search>References and select a working set, the search is still performed on the entire workspace.
verified fixed
57d6c81
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-08-28T10:14:23Z
2003-08-27T18:46:40Z
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.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IPath; import org.eclipse.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.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); } public IProject[] getJavaProjects(IJavaSearchScope scope) { IPath[] paths= scope.enclosingProjectsAndJars(); HashSet temp= new HashSet(); for (int i= 0; i < paths.length; i++) { IResource resource= ResourcesPlugin.getWorkspace().getRoot().findMember(paths[i]); if (resource != null && resource.getType() == IResource.PROJECT) temp.add(resource); } return (IProject[]) temp.toArray(new IProject[temp.size()]); } 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, IResource 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 } } javaElements.add(javaElement); } private void addJavaElements(Set javaElements, IJavaElement javaElement) { javaElements.add(javaElement); } private void addJavaElements(Set javaElements, IWorkingSet workingSet) { if (workingSet == null) return; IAdaptable[] elements= workingSet.getElements(); for (int i= 0; i < elements.length; i++) { IJavaElement javaElement=(IJavaElement) elements[i].getAdapter(IJavaElement.class); if (javaElement != null) { addJavaElements(javaElements, javaElement); continue; } IResource resource= (IResource)elements[i].getAdapter(IResource.class); if (resource != null) { addJavaElements(javaElements, resource); } // else we don't know what to do with it, ignore. } } public void addJavaElements(Set javaElements, LogicalPackage selectedElement) { IPackageFragment[] packages= selectedElement.getFragments(); for (int i= 0; i < packages.length; i++) addJavaElements(javaElements, packages[i]); } }
42,199
Bug 42199 Select Next/Previous Word is broken when navigating over sequence of upper-case letters
I20030827: When positioning the caret to the right of sequences with pattern a* A+ a*, where A+ consists of more than two upper-case letters, the caret is moved to the beginning instead in front of the first A when using Ctrl+Arrow_Left.
resolved fixed
b7d9226
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-08-28T10:21:57Z
2003-08-28T08: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.text.CollationElementIterator; import java.text.Collator; import java.text.RuleBasedCollator; 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.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.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; 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.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.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.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.swt.SWT; import org.eclipse.swt.custom.BidiSegmentEvent; import org.eclipse.swt.custom.BidiSegmentListener; import org.eclipse.swt.custom.ST; 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.Event; import org.eclipse.swt.widgets.Shell; 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.DefaultMarkerAnnotationAccess; 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.MarkerAnnotationPreferences; import org.eclipse.ui.texteditor.ResourceAction; import org.eclipse.ui.texteditor.SourceViewerDecorationSupport; import org.eclipse.ui.texteditor.TextEditorAction; import org.eclipse.ui.texteditor.TextNavigationAction; 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; /** * 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; int fontStyle= oldStyleRange== null ? SWT.NORMAL : oldStyleRange.fontStyle; StyleRange styleRange= new StyleRange(offset, length, foregroundColor, backgroundColor, fontStyle); 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 extends DefaultMarkerAnnotationAccess { public AnnotationAccess(MarkerAnnotationPreferences markerAnnotationPreferences) { super(markerAnnotationPreferences); } /* * @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); } } /** * This action implements smart home. * * Instead of going to the start of a line it does the following: * * - if smart home/end is enabled and the caret is after the line's first non-whitespace then the caret is moved directly before it, taking JavaDoc and multi-line comments into account. * - if the caret is before the line's first non-whitespace the caret is moved to the beginning of the line * - if the caret is at the beginning of the line see first case. * * @since 3.0 */ protected class SmartLineStartAction extends LineStartAction { /** * Creates a new smart line start action * * @param textWidget the styled text widget * @param doSelect a boolean flag which tells if the text up to the beginning of the line should be selected */ public SmartLineStartAction(final StyledText textWidget, final boolean doSelect) { super(textWidget, doSelect); } /* * @see org.eclipse.ui.texteditor.AbstractTextEditor.LineStartAction#getLineStartPosition(java.lang.String, int, java.lang.String) */ protected int getLineStartPosition(final IDocument document, final String line, final int length, final int offset) { String type= IDocument.DEFAULT_CONTENT_TYPE; try { type= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, offset).getType(); } catch (BadLocationException exception) { // Should not happen } int index= super.getLineStartPosition(document, line, length, offset); if (type.equals(IJavaPartitions.JAVA_DOC) || type.equals(IJavaPartitions.JAVA_MULTI_LINE_COMMENT)) { if (index < length - 1 && line.charAt(index) == '*' && line.charAt(index + 1) != '/') { do { ++index; } while (index < length && Character.isWhitespace(line.charAt(index))); } } else { if (index < length - 1 && line.charAt(index) == '/' && line.charAt(++index) == '/') { do { ++index; } while (index < length && Character.isWhitespace(line.charAt(index))); } } return index; } } /** * Text navigation action to navigate to the next sub-word. * * @since 3.0 */ protected abstract class NextSubWordAction extends TextNavigationAction { /** Collator to determine the sub-word boundaries */ private final RuleBasedCollator fCollator= (RuleBasedCollator)Collator.getInstance(); /** * Creates a new next sub-word action. * * @param code Action code for the default operation. Must be an action code from @see org.eclipse.swt.custom.ST. */ protected NextSubWordAction(int code) { super(getSourceViewer().getTextWidget(), code); // Only compare upper-/lower case fCollator.setStrength(Collator.TERTIARY); } /* * @see org.eclipse.jface.action.IAction#run() */ public void run() { try { final ISourceViewer viewer= getSourceViewer(); final IDocument document= viewer.getDocument(); int position= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset()); // Check whether we are in a java code partititon and the preference is enabled final IPreferenceStore store= getPreferenceStore(); final ITypedRegion region= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, position); if (!store.getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)) { super.run(); return; } // Check whether right hand character of caret is valid identifier start if (Character.isJavaIdentifierStart(document.getChar(position))) { int offset= 0; int order= CollationElementIterator.NULLORDER; short previous= Short.MAX_VALUE; short next= Short.MAX_VALUE; // Acquire collator for partition around caret final String buffer= document.get(position, region.getOffset() + region.getLength() - position); final CollationElementIterator iterator= fCollator.getCollationElementIterator(buffer); // Iterate to first upper-case character do { // Check whether we reached end of word offset= iterator.getOffset(); if (!Character.isJavaIdentifierPart(document.getChar(position + offset))) throw new BadLocationException(); // Test next characters order= iterator.next(); next= CollationElementIterator.tertiaryOrder(order); if (next <= previous) previous= next; else break; } while (order != CollationElementIterator.NULLORDER); // Check for leading underscores position += offset; if (Character.getType(document.getChar(position - 1)) != Character.CONNECTOR_PUNCTUATION) { setCaretPosition(position); return; } } } catch (BadLocationException exception) { // Use default behavior } super.run(); } /** * Sets the caret position to the sub-word boundary given with <code>position</code>. * * @param position Position where the action should move the caret */ protected abstract void setCaretPosition(int position); } /** * Text navigation action to navigate to the next sub-word. * * @since 3.0 */ protected class NavigateNextSubWordAction extends NextSubWordAction { /** * Creates a new navigate next sub-word action. */ public NavigateNextSubWordAction() { super(ST.WORD_NEXT); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { final ISourceViewer viewer= getSourceViewer(); viewer.getTextWidget().setCaretOffset(modelOffset2WidgetOffset(viewer, position)); } } /** * Text operation action to delete the next sub-word. * * @since 3.0 */ protected class DeleteNextSubWordAction extends NextSubWordAction { /** * Creates a new delete next sub-word action. */ public DeleteNextSubWordAction() { super(ST.DELETE_WORD_NEXT); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { final ISourceViewer viewer= getSourceViewer(); final int caret= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset()); try { viewer.getDocument().replace(caret, position - caret, ""); //$NON-NLS-1$ } catch (BadLocationException exception) { // Should not happen } } } /** * Text operation action to select the next sub-word. * * @since 3.0 */ protected class SelectNextSubWordAction extends NextSubWordAction { /** * Creates a new select next sub-word action. */ public SelectNextSubWordAction() { super(ST.SELECT_WORD_NEXT); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { final ISourceViewer viewer= getSourceViewer(); final StyledText text= viewer.getTextWidget(); if (text != null && !text.isDisposed()) { final Point selection= text.getSelection(); final int caret= text.getCaretOffset(); final int offset= modelOffset2WidgetOffset(viewer, position); if (caret == selection.x) text.setSelectionRange(selection.y, offset - selection.y); else text.setSelectionRange(selection.x, offset - selection.x); final Event event= new Event(); event.x= text.getSelection().x; event.y= text.getSelection().y; text.notifyListeners(SWT.Selection, event); } } } /** * Text navigation action to navigate to the previous sub-word. * * @since 3.0 */ protected abstract class PreviousSubWordAction extends TextNavigationAction { /** Collator to determine the sub-word boundaries */ private final RuleBasedCollator fCollator= (RuleBasedCollator)Collator.getInstance(); /** * Creates a new previous sub-word action. * * @param code Action code for the default operation. Must be an action code from @see org.eclipse.swt.custom.ST. */ protected PreviousSubWordAction(final int code) { super(getSourceViewer().getTextWidget(), code); // Only compare upper-/lower case fCollator.setStrength(Collator.TERTIARY); } /* * @see org.eclipse.jface.action.IAction#run() */ public void run() { try { final ISourceViewer viewer= getSourceViewer(); final IDocument document= viewer.getDocument(); int position= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset()) - 1; // Check whether we are in a java code partititon and the preference is enabled final IPreferenceStore store= getPreferenceStore(); if (!store.getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)) { super.run(); return; } // Ignore trailing white spaces char character= document.getChar(position); while (position > 0 && Character.isWhitespace(character)) { --position; character= document.getChar(position); } // Check whether left hand character of caret is valid identifier part if (Character.isJavaIdentifierPart(character)) { int offset= 0; int order= CollationElementIterator.NULLORDER; short previous= Short.MAX_VALUE; short next= Short.MAX_VALUE; // Acquire collator for partition around caret final ITypedRegion region= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, position); final String buffer= document.get(region.getOffset(), position - region.getOffset() + 1); final CollationElementIterator iterator= fCollator.getCollationElementIterator(buffer); // Iterate to first upper-case character iterator.setOffset(buffer.length() - 1); do { // Check whether we reached begin of word or single upper-case start offset= iterator.getOffset(); character= document.getChar(region.getOffset() + offset); if (!Character.isJavaIdentifierPart(character)) throw new BadLocationException(); else if (Character.isUpperCase(character)) { ++offset; break; } // Test next characters order= iterator.previous(); next= CollationElementIterator.tertiaryOrder(order); if (next <= previous) previous= next; else break; } while (order != CollationElementIterator.NULLORDER); // Check left character for multiple upper-case characters position= position - buffer.length() + offset - 1; character= document.getChar(position); if (!Character.isUpperCase(character)) { setCaretPosition(position + 1); return; } } } catch (BadLocationException exception) { // Use default behavior } super.run(); } /** * Sets the caret position to the sub-word boundary given with <code>position</code>. * * @param position Position where the action should move the caret */ protected abstract void setCaretPosition(int position); } /** * Text navigation action to navigate to the previous sub-word. * * @since 3.0 */ protected class NavigatePreviousSubWordAction extends PreviousSubWordAction { /** * Creates a new navigate previous sub-word action. */ public NavigatePreviousSubWordAction() { super(ST.WORD_PREVIOUS); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { final ISourceViewer viewer= getSourceViewer(); viewer.getTextWidget().setCaretOffset(modelOffset2WidgetOffset(viewer, position)); } } /** * Text operation action to delete the previous sub-word. * * @since 3.0 */ protected class DeletePreviousSubWordAction extends PreviousSubWordAction { /** * Creates a new delete previous sub-word action. */ public DeletePreviousSubWordAction() { super(ST.DELETE_WORD_PREVIOUS); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { final ISourceViewer viewer= getSourceViewer(); final int caret= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset()); try { viewer.getDocument().replace(position, caret - position, ""); //$NON-NLS-1$ } catch (BadLocationException exception) { // Should not happen } } } /** * Text operation action to select the previous sub-word. * * @since 3.0 */ protected class SelectPreviousSubWordAction extends PreviousSubWordAction { /** * Creates a new select previous sub-word action. */ public SelectPreviousSubWordAction() { super(ST.SELECT_WORD_PREVIOUS); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { final ISourceViewer viewer= getSourceViewer(); final StyledText text= viewer.getTextWidget(); if (text != null && !text.isDisposed()) { final Point selection= text.getSelection(); final int caret= text.getCaretOffset(); final int offset= modelOffset2WidgetOffset(viewer, position); if (caret == selection.x) text.setSelectionRange(selection.y, offset - selection.y); else text.setSelectionRange(selection.x, offset - selection.x); final Event event= new Event(); event.x= text.getSelection().x; event.y= text.getSelection().y; text.notifyListeners(SWT.Selection, 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(new MarkerAnnotationPreferences()); } 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; // PR 39995: [navigation] Forward history cleared after going back in navigation history: // mark only in navigation history if the cursor is being moved (which it isn't if // this is called from a PostSelectionEvent that should only update the magnet) if (moveCursor && (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; /* * Fixes bug 41689 * This code can be simplified if we decide that * we don't allow to use different settings for go to * previous and go to next annotation. */ key= annotationPref.getIsGoToNextNavigationTargetKey(); // 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 } /* * @see org.eclipse.ui.texteditor.AbstractTextEditor#createNavigationActions() */ protected void createNavigationActions() { super.createNavigationActions(); final StyledText textWidget= getSourceViewer().getTextWidget(); IAction action= new SmartLineStartAction(textWidget, false); action.setActionDefinitionId(ITextEditorActionDefinitionIds.LINE_START); setAction(ITextEditorActionDefinitionIds.LINE_START, action); action= new SmartLineStartAction(textWidget, true); action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_LINE_START); setAction(ITextEditorActionDefinitionIds.SELECT_LINE_START, action); action= new NavigatePreviousSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.WORD_PREVIOUS); setAction(ITextEditorActionDefinitionIds.WORD_PREVIOUS, action); textWidget.setKeyBinding(SWT.CTRL | SWT.ARROW_LEFT, SWT.NULL); action= new NavigateNextSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.WORD_NEXT); setAction(ITextEditorActionDefinitionIds.WORD_NEXT, action); textWidget.setKeyBinding(SWT.CTRL | SWT.ARROW_RIGHT, SWT.NULL); action= new DeletePreviousSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.DELETE_PREVIOUS_WORD); setAction(ITextEditorActionDefinitionIds.DELETE_PREVIOUS_WORD, action); textWidget.setKeyBinding(SWT.CTRL | SWT.BS, SWT.NULL); action= new DeleteNextSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.DELETE_NEXT_WORD); setAction(ITextEditorActionDefinitionIds.DELETE_NEXT_WORD, action); textWidget.setKeyBinding(SWT.CTRL | SWT.DEL, SWT.NULL); action= new SelectPreviousSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS); setAction(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS, action); textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_LEFT, SWT.NULL); action= new SelectNextSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT); setAction(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT, action); textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_RIGHT, SWT.NULL); } }
42,208
Bug 42208 Source hover affordance text is black
Source hover affordance text is black, but should be gray.
resolved fixed
e1b8842
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-08-28T13:49:03Z
2003-08-28T14:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/hover/SourceViewerInformationControl.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.hover; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; 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.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IInformationControl; import org.eclipse.jface.text.IInformationControlExtension; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.jface.text.source.SourceViewer; import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.javaeditor.JavaSourceViewer; /** * Source viewer based implementation of <code>IInformationControl</code>. * Displays information in a source viewer. * * @since 3.0 */ public class SourceViewerInformationControl implements IInformationControl, IInformationControlExtension { /** Border thickness in pixels. */ private static final int BORDER= 1; /** The control's shell */ private Shell fShell; /** The control's text widget */ private StyledText fText; /** The control's source viewer */ private SourceViewer fViewer; /** * The optional status field. * * @since 3.0 */ private Label fStatusField; /** * The separator for the optional status field. * * @since 3.0 */ private Label fSeparator; /** * The font of the optional status text label. * * @since 3.0 */ private Font fStatusTextFont; /** * Creates a default information control with the given shell as parent. The given * information presenter is used to process the information to be displayed. The given * styles are applied to the created styled text widget. * * @param parent the parent shell * @param shellStyle the additional styles for the shell * @param style the additional styles for the styled text widget */ public SourceViewerInformationControl(Shell parent, int shellStyle, int style) { this(parent, shellStyle, style, null); } /** * Creates a default information control with the given shell as parent. The given * information presenter is used to process the information to be displayed. The given * styles are applied to the created styled text widget. * * @param parent the parent shell * @param shellStyle the additional styles for the shell * @param style the additional styles for the styled text widget * @param statusFieldText the text to be used in the optional status field * or <code>null</code> if the status field should be hidden * @since 3.0 */ public SourceViewerInformationControl(Shell parent, int shellStyle, int style, String statusFieldText) { GridLayout layout; GridData gd; fShell= new Shell(parent, SWT.NO_FOCUS | SWT.ON_TOP | shellStyle); Display display= fShell.getDisplay(); fShell.setBackground(display.getSystemColor(SWT.COLOR_BLACK)); Composite composite= fShell; layout= new GridLayout(1, false); int border= ((shellStyle & SWT.NO_TRIM) == 0) ? 0 : BORDER; layout.marginHeight= border; layout.marginWidth= border; composite.setLayout(layout); gd= new GridData(GridData.FILL_HORIZONTAL); composite.setLayoutData(gd); if (statusFieldText != null) { composite= new Composite(composite, SWT.NONE); layout= new GridLayout(1, false); layout.marginHeight= 0; layout.marginWidth= 0; composite.setLayout(layout); gd= new GridData(GridData.FILL_BOTH); composite.setLayoutData(gd); composite.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND)); composite.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); } // Source viewer fViewer= new JavaSourceViewer(composite, null, null, false, style); fViewer.configure(new JavaSourceViewerConfiguration(JavaPlugin.getDefault().getJavaTextTools(), null)); fViewer.setEditable(false); fText= fViewer.getTextWidget(); gd= new GridData(GridData.BEGINNING | GridData.FILL_BOTH); fText.setLayoutData(gd); fText.setForeground(parent.getDisplay().getSystemColor(SWT.COLOR_INFO_FOREGROUND)); fText.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_INFO_BACKGROUND)); fText.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { if (e.character == 0x1B) // ESC fShell.dispose(); } public void keyReleased(KeyEvent e) {} }); // Status field if (statusFieldText != null) { // Horizontal separator line fSeparator= new Label(composite, SWT.SEPARATOR | SWT.HORIZONTAL | SWT.LINE_DOT); fSeparator.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); // Status field label fStatusField= new Label(composite, SWT.RIGHT); fStatusField.setText(statusFieldText); Font font= fStatusField.getFont(); FontData[] fontDatas= font.getFontData(); for (int i= 0; i < fontDatas.length; i++) fontDatas[i].setHeight(fontDatas[i].getHeight() * 9 / 10); fStatusTextFont= new Font(fStatusField.getDisplay(), fontDatas); fStatusField.setFont(fStatusTextFont); GridData gd2= new GridData(GridData.FILL_VERTICAL | GridData.FILL_HORIZONTAL | GridData.HORIZONTAL_ALIGN_BEGINNING | GridData.VERTICAL_ALIGN_BEGINNING); fStatusField.setLayoutData(gd2); fStatusField.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND)); fStatusField.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); } } /** * Creates a default information control with the given shell as parent. The given * information presenter is used to process the information to be displayed. The given * styles are applied to the created styled text widget. * * @param parent the parent shell * @param style the additional styles for the styled text widget * @param presenter the presenter to be used */ public SourceViewerInformationControl(Shell parent,int style) { this(parent, SWT.NO_TRIM, style); } /** * Creates a default information control with the given shell as parent. The given * information presenter is used to process the information to be displayed. The given * styles are applied to the created styled text widget. * * @param parent the parent shell * @param style the additional styles for the styled text widget * @param presenter the presenter to be used * @param statusFieldText the text to be used in the optional status field * or <code>null</code> if the status field should be hidden * @since 3.0 */ public SourceViewerInformationControl(Shell parent,int style, String statusFieldText) { this(parent, SWT.NO_TRIM, style, statusFieldText); } /** * Creates a default information control with the given shell as parent. * No information presenter is used to process the information * to be displayed. No additional styles are applied to the styled text widget. * * @param parent the parent shell */ public SourceViewerInformationControl(Shell parent) { this(parent, SWT.NONE); } /** * Creates a default information control with the given shell as parent. * No information presenter is used to process the information * to be displayed. No additional styles are applied to the styled text widget. * * @param parent the parent shell * @param statusFieldText the text to be used in the optional status field * or <code>null</code> if the status field should be hidden * @since 3.0 */ public SourceViewerInformationControl(Shell parent, String statusFieldText) { this(parent, SWT.NONE, statusFieldText); } /* * @see org.eclipse.jface.text.IInformationControlExtension2#setInput(java.lang.Object) */ public void setInput(Object input) { if (input instanceof String) setInformation((String)input); else setInformation(null); } /* * @see IInformationControl#setInformation(String) */ public void setInformation(String content) { if (content == null) { fViewer.setInput(null); return; } IDocument doc= new Document(content); JavaPlugin.getDefault().getJavaTextTools().setupDocument(doc); fViewer.setInput(doc); } /* * @see IInformationControl#setVisible(boolean) */ public void setVisible(boolean visible) { fShell.setVisible(visible); } /* * @see IInformationControl#dispose() */ public void dispose() { if (fStatusTextFont != null && !fStatusTextFont.isDisposed()) fStatusTextFont.dispose(); if (fShell != null) { if (!fShell.isDisposed()) fShell.dispose(); fShell= null; fText= null; } } /* * @see IInformationControl#setSize(int, int) */ public void setSize(int width, int height) { if (fStatusField != null) { GridData gd= (GridData)fViewer.getTextWidget().getLayoutData(); Point statusSize= fStatusField.computeSize(SWT.DEFAULT, SWT.DEFAULT, true); Point separatorSize= fSeparator.computeSize(SWT.DEFAULT, SWT.DEFAULT, true); gd.heightHint= height - statusSize.y - separatorSize.y; } fShell.setSize(width, height); if (fStatusField != null) fShell.pack(true); } /* * @see IInformationControl#setLocation(Point) */ public void setLocation(Point location) { Rectangle trim= fShell.computeTrim(0, 0, 0, 0); Point textLocation= fText.getLocation(); location.x += trim.x - textLocation.x; location.y += trim.y - textLocation.y; fShell.setLocation(location); } /* * @see IInformationControl#setSizeConstraints(int, int) */ public void setSizeConstraints(int maxWidth, int maxHeight) { maxWidth= maxHeight; } /* * @see IInformationControl#computeSizeHint() */ public Point computeSizeHint() { return fShell.computeSize(SWT.DEFAULT, SWT.DEFAULT); } /* * @see IInformationControl#addDisposeListener(DisposeListener) */ public void addDisposeListener(DisposeListener listener) { fShell.addDisposeListener(listener); } /* * @see IInformationControl#removeDisposeListener(DisposeListener) */ public void removeDisposeListener(DisposeListener listener) { fShell.removeDisposeListener(listener); } /* * @see IInformationControl#setForegroundColor(Color) */ public void setForegroundColor(Color foreground) { fText.setForeground(foreground); } /* * @see IInformationControl#setBackgroundColor(Color) */ public void setBackgroundColor(Color background) { fText.setBackground(background); } /* * @see IInformationControl#isFocusControl() */ public boolean isFocusControl() { return fText.isFocusControl(); } /* * @see IInformationControl#setFocus() */ public void setFocus() { fShell.forceFocus(); fText.setFocus(); } /* * @see IInformationControl#addFocusListener(FocusListener) */ public void addFocusListener(FocusListener listener) { fText.addFocusListener(listener); } /* * @see IInformationControl#removeFocusListener(FocusListener) */ public void removeFocusListener(FocusListener listener) { fText.removeFocusListener(listener); } /* * @see IInformationControlExtension#hasContents() */ public boolean hasContents() { return fText.getCharCount() > 0; } protected ISourceViewer getViewer() { return fViewer; } }
41,849
Bug 41849 [typing] LinkedPositionManager sets illegal positions
Eclipse: 200308201005 on Mac OS X Jaguar Files I'm editing and saving are not being saved to disk. There are no errors in the logs. It appears that this is an editor problem, because the compiler compiles what is on disk. Chang
resolved fixed
5ccefd3
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-08-29T10:48:08Z
2003-08-22T11:00:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/link/LinkedPositionManager.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.link; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import org.eclipse.jface.text.Assert; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.BadPositionCategoryException; import org.eclipse.jface.text.DocumentCommand; import org.eclipse.jface.text.DocumentEvent; import org.eclipse.jface.text.IAutoEditStrategy; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocumentExtension; import org.eclipse.jface.text.IDocumentListener; import org.eclipse.jface.text.IPositionUpdater; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.TypedPosition; import org.eclipse.jface.text.contentassist.ICompletionProposal; import org.eclipse.jdt.internal.ui.JavaPlugin; /** * This class manages linked positions in a document. Positions are linked * by type names. If positions have the same type name, they are considered * as <em>linked</em>. * * The manager remains active on a document until any of the following actions * occurs: * * <ul> * <li>A document change is performed which would invalidate any of the * above constraints.</li> * * <li>The method <code>uninstall()</code> is called.</li> * * <li>Another instance of <code>LinkedPositionManager</code> tries to * gain control of the same document. * </ul> */ public class LinkedPositionManager implements IDocumentListener, IPositionUpdater, IAutoEditStrategy { // This class still exists to properly handle code assist. // This is due to the fact that it cannot be distinguished betweeen document changes which are // issued by code assist and document changes which origin from another text viewer. // There is a conflict in interest since in the latter case the linked mode should be left, but in the former case // the linked mode should remain. // To support content assist, document changes have to be propagated to connected positions // by registering replace commands using IDocumentExtension. // if it wasn't for the support of content assist, the documentChanged() method could be reduced to // a simple call to leave(true) private class Replace implements IDocumentExtension.IReplace { private Position fReplacePosition; private int fReplaceDeltaOffset; private int fReplaceLength; private String fReplaceText; public Replace(Position position, int deltaOffset, int length, String text) { fReplacePosition= position; fReplaceDeltaOffset= deltaOffset; fReplaceLength= length; fReplaceText= text; } public void perform(IDocument document, IDocumentListener owner) { document.removeDocumentListener(owner); try { document.replace(fReplacePosition.getOffset() + fReplaceDeltaOffset, fReplaceLength, fReplaceText); } catch (BadLocationException e) { JavaPlugin.log(e); // TBD } document.addDocumentListener(owner); } } private static class PositionComparator implements Comparator { /* * @see Comparator#compare(Object, Object) */ public int compare(Object object0, Object object1) { Position position0= (Position) object0; Position position1= (Position) object1; return position0.getOffset() - position1.getOffset(); } } private static final String LINKED_POSITION_PREFIX= "LinkedPositionManager.linked.position"; //$NON-NLS-1$ private static final Comparator fgPositionComparator= new PositionComparator(); private static final Map fgActiveManagers= new HashMap(); private static int fgCounter= 0; private IDocument fDocument; private ILinkedPositionListener fListener; private String fPositionCategoryName; /** * Creates a <code>LinkedPositionManager</code> for a <code>IDocument</code>. * * @param document the document to use with linked positions. * @param canCoexist <code>true</code> if this manager can coexist with an already existing one */ public LinkedPositionManager(IDocument document, boolean canCoexist) { Assert.isNotNull(document); fDocument= document; fPositionCategoryName= LINKED_POSITION_PREFIX + (fgCounter++); install(canCoexist); } /** * Creates a <code>LinkedPositionManager</code> for a <code>IDocument</code>. * * @param document the document to use with linked positions. */ public LinkedPositionManager(IDocument document) { this(document, false); } /** * Sets a listener to notify changes of current linked position. */ public void setLinkedPositionListener(ILinkedPositionListener listener) { fListener= listener; } /** * Adds a linked position to the manager with the type being the content of * the document at the specified range. * There are the following constraints for linked positions: * * <ul> * <li>Any two positions have spacing of at least one character. * This implies that two positions must not overlap.</li> * * <li>The string at any position must not contain line delimiters.</li> * </ul> * * @param offset the offset of the position. * @param length the length of the position. */ public void addPosition(int offset, int length) throws BadLocationException { String type= fDocument.get(offset, length); addPosition(offset, length, type); } /** * Adds a linked position of the specified position type to the manager. * There are the following constraints for linked positions: * * <ul> * <li>Any two positions have spacing of at least one character. * This implies that two positions must not overlap.</li> * * <li>The string at any position must not contain line delimiters.</li> * </ul> * * @param offset the offset of the position. * @param length the length of the position. * @param type the position type name - any positions with the same type are linked. */ public void addPosition(int offset, int length, String type) throws BadLocationException { Position[] positions= getPositions(fDocument); if (positions != null) { for (int i = 0; i < positions.length; i++) if (collides(positions[i], offset, length)) throw new BadLocationException(LinkedPositionMessages.getString(("LinkedPositionManager.error.position.collision"))); //$NON-NLS-1$ } String content= fDocument.get(offset, length); if (containsLineDelimiters(content)) throw new BadLocationException(LinkedPositionMessages.getString(("LinkedPositionManager.error.contains.line.delimiters"))); //$NON-NLS-1$ try { fDocument.addPosition(fPositionCategoryName, new TypedPosition(offset, length, type)); } catch (BadPositionCategoryException e) { JavaPlugin.log(e); Assert.isTrue(false); } } /** * Adds a linked position to the manager. The current document content at the specified range is * taken as the position type. * <p> * There are the following constraints for linked positions: * * <ul> * <li>Any two positions have spacing of at least one character. * This implies that two positions must not overlap.</li> * * <li>The string at any position must not contain line delimiters.</li> * </ul> * * It is usually best to set the first item in <code>additionalChoices</code> to be equal with * the text inserted at the current position. * </p> * * @param offset the offset of the position. * @param length the length of the position. * @param additionalChoices a number of additional choices to be displayed when selecting * a position of this <code>type</code>. */ public void addPosition(int offset, int length, ICompletionProposal[] additionalChoices) throws BadLocationException { String type= fDocument.get(offset, length); addPosition(offset, length, type, additionalChoices); } /** * Adds a linked position of the specified position type to the manager. * There are the following constraints for linked positions: * * <ul> * <li>Any two positions have spacing of at least one character. * This implies that two positions must not overlap.</li> * * <li>The string at any position must not contain line delimiters.</li> * </ul> * * It is usually best to set the first item in <code>additionalChoices</code> to be equal with * the text inserted at the current position. * * @param offset the offset of the position. * @param length the length of the position. * @param type the position type name - any positions with the same type are linked. * @param additionalChoices a number of additional choices to be displayed when selecting * a position of this <code>type</code>. */ public void addPosition(int offset, int length, String type, ICompletionProposal[] additionalChoices) throws BadLocationException { Position[] positions= getPositions(fDocument); if (positions != null) { for (int i = 0; i < positions.length; i++) if (collides(positions[i], offset, length)) throw new BadLocationException(LinkedPositionMessages.getString(("LinkedPositionManager.error.position.collision"))); //$NON-NLS-1$ } String content= fDocument.get(offset, length); if (containsLineDelimiters(content)) throw new BadLocationException(LinkedPositionMessages.getString(("LinkedPositionManager.error.contains.line.delimiters"))); //$NON-NLS-1$ try { fDocument.addPosition(fPositionCategoryName, new ProposalPosition(offset, length, type, additionalChoices)); } catch (BadPositionCategoryException e) { JavaPlugin.log(e); Assert.isTrue(false); } } /** * Tests if a manager is already active for a document. */ public static boolean hasActiveManager(IDocument document) { return fgActiveManagers.get(document) != null; } private void install(boolean canCoexist) { if (!canCoexist){ LinkedPositionManager manager= (LinkedPositionManager) fgActiveManagers.get(fDocument); if (manager != null) manager.leave(true); } fgActiveManagers.put(fDocument, this); fDocument.addPositionCategory(fPositionCategoryName); fDocument.addPositionUpdater(this); fDocument.addDocumentListener(this); } /** * Leaves the linked mode. If unsuccessful, the linked positions * are restored to the values at the time they were added. */ public void uninstall(boolean success) { fDocument.removeDocumentListener(this); try { Position[] positions= getPositions(fDocument); if ((!success) && (positions != null)) { // restore for (int i= 0; i != positions.length; i++) { TypedPosition position= (TypedPosition) positions[i]; fDocument.replace(position.getOffset(), position.getLength(), position.getType()); } } fDocument.removePositionCategory(fPositionCategoryName); } catch (BadLocationException e) { JavaPlugin.log(e); Assert.isTrue(false); } catch (BadPositionCategoryException e) { JavaPlugin.log(e); Assert.isTrue(false); } finally { fDocument.removePositionUpdater(this); fgActiveManagers.remove(fDocument); } } /** * Returns the position at the given offset, <code>null</code> if there is no position. * @since 2.1 */ public Position getPosition(int offset) { Position[] positions= getPositions(fDocument); if (positions == null) return null; for (int i= positions.length - 1; i >= 0; i--) { Position position= positions[i]; if (offset >= position.getOffset() && offset <= position.getOffset() + position.getLength()) return positions[i]; } return null; } /** * Returns the first linked position. * * @return returns <code>null</code> if no linked position exist. */ public Position getFirstPosition() { return getNextPosition(-1); } public Position getLastPosition() { Position[] positions= getPositions(fDocument); for (int i= positions.length - 1; i >= 0; i--) { String type= ((TypedPosition) positions[i]).getType(); int j; for (j = 0; j != i; j++) if (((TypedPosition) positions[j]).getType().equals(type)) break; if (j == i) return positions[i]; } return null; } /** * Returns the next linked position with an offset greater than <code>offset</code>. * If another position with the same type and offset lower than <code>offset</code> * exists, the position is skipped. * * @return returns <code>null</code> if no linked position exist. */ public Position getNextPosition(int offset) { Position[] positions= getPositions(fDocument); return findNextPosition(positions, offset); } private static Position findNextPosition(Position[] positions, int offset) { // skip already visited types for (int i= 0; i != positions.length; i++) { if (positions[i].getOffset() > offset) { String type= ((TypedPosition) positions[i]).getType(); int j; for (j = 0; j != i; j++) if (((TypedPosition) positions[j]).getType().equals(type)) break; if (j == i) return positions[i]; } } return null; } /** * Returns the position with the greatest offset smaller than <code>offset</code>. * * @return returns <code>null</code> if no linked position exist. */ public Position getPreviousPosition(int offset) { Position[] positions= getPositions(fDocument); if (positions == null) return null; TypedPosition currentPosition= (TypedPosition) findCurrentPosition(positions, offset); String currentType= currentPosition == null ? null : currentPosition.getType(); Position lastPosition= null; Position position= getFirstPosition(); while (position != null && position.getOffset() < offset) { if (!((TypedPosition) position).getType().equals(currentType)) lastPosition= position; position= findNextPosition(positions, position.getOffset()); } return lastPosition; } private Position[] getPositions(IDocument document) { try { Position[] positions= document.getPositions(fPositionCategoryName); Arrays.sort(positions, fgPositionComparator); return positions; } catch (BadPositionCategoryException e) { JavaPlugin.log(e); Assert.isTrue(false); } return null; } public static boolean includes(Position position, int offset, int length) { return (offset >= position.getOffset()) && (offset + length <= position.getOffset() + position.getLength()); } public static boolean excludes(Position position, int offset, int length) { return (offset + length <= position.getOffset()) || (position.getOffset() + position.getLength() <= offset); } /* * Collides if spacing if positions intersect each other or are adjacent. */ private static boolean collides(Position position, int offset, int length) { return (offset <= position.getOffset() + position.getLength()) && (position.getOffset() <= offset + length); } private void leave(boolean success) { uninstall(success); if (fListener != null) fListener.exit(success); } /* * @see IDocumentListener#documentAboutToBeChanged(DocumentEvent) */ public void documentAboutToBeChanged(DocumentEvent event) { IDocument document= event.getDocument(); Position[] positions= getPositions(document); Position position= findCurrentPosition(positions, event.getOffset()); // modification outside editable position if (position == null) { // check for destruction of constraints (spacing of at least 1) if ((event.getText() == null || event.getText().length() == 0) && (findCurrentPosition(positions, event.getOffset()) != null) && // will never become true, see condition above (findCurrentPosition(positions, event.getOffset() + event.getLength()) != null)) { leave(true); } // modification intersects editable position } else { // modificaction inside editable position if (includes(position, event.getOffset(), event.getLength())) { if (containsLineDelimiters(event.getText())) leave(true); // modificaction exceeds editable position } else { leave(true); } } } /* * @see IDocumentListener#documentChanged(DocumentEvent) */ public void documentChanged(DocumentEvent event) { // have to handle code assist, so can't just leave the linked mode // leave(true); IDocument document= event.getDocument(); Position[] positions= getPositions(document); TypedPosition currentPosition= (TypedPosition) findCurrentPosition(positions, event.getOffset()); // ignore document changes (assume it won't invalidate constraints) if (currentPosition == null) return; int deltaOffset= event.getOffset() - currentPosition.getOffset(); if (fListener != null) { int length= event.getText() == null ? 0 : event.getText().length(); fListener.setCurrentPosition(currentPosition, deltaOffset + length); } for (int i= 0; i != positions.length; i++) { TypedPosition p= (TypedPosition) positions[i]; if (p.getType().equals(currentPosition.getType()) && !p.equals(currentPosition)) { Replace replace= new Replace(p, deltaOffset, event.getLength(), event.getText()); ((IDocumentExtension) document).registerPostNotificationReplace(this, replace); } } } /* * @see IPositionUpdater#update(DocumentEvent) */ public void update(DocumentEvent event) { int deltaLength= (event.getText() == null ? 0 : event.getText().length()) - event.getLength(); Position[] positions= getPositions(event.getDocument()); TypedPosition currentPosition= (TypedPosition) findCurrentPosition(positions, event.getOffset()); // document change outside positions if (currentPosition == null) { for (int i= 0; i != positions.length; i++) { TypedPosition position= (TypedPosition) positions[i]; int offset= position.getOffset(); if (offset >= event.getOffset()) position.setOffset(offset + deltaLength); } // document change within a position } else { int length= currentPosition.getLength(); for (int i= 0; i != positions.length; i++) { TypedPosition position= (TypedPosition) positions[i]; int offset= position.getOffset(); if (position.equals(currentPosition)) { position.setLength(length + deltaLength); } else if (offset > currentPosition.getOffset()) { position.setOffset(offset + deltaLength); } } } } private static Position findCurrentPosition(Position[] positions, int offset) { for (int i= 0; i != positions.length; i++) if (includes(positions[i], offset, 0)) return positions[i]; return null; } private boolean containsLineDelimiters(String string) { if (string == null) return false; String[] delimiters= fDocument.getLegalLineDelimiters(); for (int i= 0; i != delimiters.length; i++) if (string.indexOf(delimiters[i]) != -1) return true; return false; } /** * Test if ok to modify through UI. */ public boolean anyPositionIncludes(int offset, int length) { Position[] positions= getPositions(fDocument); Position position= findCurrentPosition(positions, offset); if (position == null) return false; return includes(position, offset, length); } /** * Returns the position that includes the given range. * @param offset * @param length * @return position that includes the given range */ public Position getEmbracingPosition(int offset, int length) { Position[] positions= getPositions(fDocument); Position position= findCurrentPosition(positions, offset); if (position != null && includes(position, offset, length)) return position; return null; } /* * @see org.eclipse.jface.text.IAutoIndentStrategy#customizeDocumentCommand(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.DocumentCommand) */ public void customizeDocumentCommand(IDocument document, DocumentCommand command) { // don't interfere with preceding auto edit strategies if (command.getCommandCount() != 1) { leave(true); return; } Position[] positions= getPositions(document); TypedPosition currentPosition= (TypedPosition) findCurrentPosition(positions, command.offset); // handle edits outside of a position if (currentPosition == null) { leave(true); return; } if (! command.doit) return; command.doit= false; command.owner= this; command.caretOffset= command.offset + command.length; int deltaOffset= command.offset - currentPosition.getOffset(); if (fListener != null) fListener.setCurrentPosition(currentPosition, deltaOffset + command.text.length()); for (int i= 0; i != positions.length; i++) { TypedPosition position= (TypedPosition) positions[i]; try { if (position.getType().equals(currentPosition.getType()) && !position.equals(currentPosition)) command.addCommand(position.getOffset() + deltaOffset, command.length, command.text, true, this); } catch (BadLocationException e) { JavaPlugin.log(e); } } } }
42,279
Bug 42279 unwanted indents after if()/for()/while()....
Since 3.0m3 (and one or two integration builds before it) i get an automatic indent after controll statements like if()+new line. So my code looks like this (only automatic indents): public class Main { void someMethod() { if(true) { // this doesn't look good } else if(1==1) { // this is getting even worse } // oh my god :( } } After running the code formater the code looks like expected public class Main { void someMethod() { if (true) { // this doesn't look good } else if (1 == 1) { // this is getting even worse } // oh my god :( } } If there is a switch i didn't didn't find: sorry. If not: please fix it asap
verified fixed
396fa77
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T09:47:16Z
2003-08-29T20:46:40Z
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 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 (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 (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) { if (position < 1) return false; position= firstNonWhitespaceBackward(document, position - 1, 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 &lt;= <code>position</code> * and &gt; <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> &gt; <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 &gt;= <code>position</code> * and &lt; <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> &gt; <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 &gt;= <code>position</code> * and &lt; <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> &gt; <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.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 &lt;= <code>position</code> * and &gt; <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> &gt; <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 (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); } 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,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
org.eclipse.jdt.ui.tests.refactoring/test
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
cases/org/eclipse/jdt/ui/tests/actions/StructureSelectionActionTests.java
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
org.eclipse.jdt.ui.tests.refactoring/test
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
cases/org/eclipse/jdt/ui/tests/refactoring/ChangeSignatureTests.java
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
org.eclipse.jdt.ui.tests.refactoring/test
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
cases/org/eclipse/jdt/ui/tests/refactoring/ConvertAnonymousToNestedTests.java
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
org.eclipse.jdt.ui.tests.refactoring/test
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
cases/org/eclipse/jdt/ui/tests/refactoring/ExtractConstantTests.java
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
org.eclipse.jdt.ui.tests.refactoring/test
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
cases/org/eclipse/jdt/ui/tests/refactoring/ExtractInterfaceTests.java
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
org.eclipse.jdt.ui.tests.refactoring/test
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
cases/org/eclipse/jdt/ui/tests/refactoring/ExtractTempTests.java
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
org.eclipse.jdt.ui.tests.refactoring/test
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
cases/org/eclipse/jdt/ui/tests/refactoring/InlineConstantTests.java
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
org.eclipse.jdt.ui.tests.refactoring/test
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
cases/org/eclipse/jdt/ui/tests/refactoring/InlineTempTests.java
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
org.eclipse.jdt.ui.tests.refactoring/test
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
cases/org/eclipse/jdt/ui/tests/refactoring/MoveInnerToTopLevelTests.java
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
org.eclipse.jdt.ui.tests.refactoring/test
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
cases/org/eclipse/jdt/ui/tests/refactoring/MoveInstanceMethodTests.java
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
org.eclipse.jdt.ui.tests.refactoring/test
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
cases/org/eclipse/jdt/ui/tests/refactoring/MoveMembersTests.java
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
org.eclipse.jdt.ui.tests.refactoring/test
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
cases/org/eclipse/jdt/ui/tests/refactoring/PromoteTempToFieldTests.java
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
org.eclipse.jdt.ui.tests.refactoring/test
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
cases/org/eclipse/jdt/ui/tests/refactoring/PullUpTests.java
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
org.eclipse.jdt.ui.tests.refactoring/test
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
cases/org/eclipse/jdt/ui/tests/refactoring/PushDownTests.java
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
org.eclipse.jdt.ui.tests.refactoring/test
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
cases/org/eclipse/jdt/ui/tests/refactoring/RefactoringTest.java
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
org.eclipse.jdt.ui.tests.refactoring/test
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
cases/org/eclipse/jdt/ui/tests/refactoring/RenameMethodInInterfaceTests.java
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
org.eclipse.jdt.ui.tests.refactoring/test
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
cases/org/eclipse/jdt/ui/tests/refactoring/RenameNonPrivateFieldTests.java
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
org.eclipse.jdt.ui.tests.refactoring/test
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
cases/org/eclipse/jdt/ui/tests/refactoring/RenamePackageTests.java
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
org.eclipse.jdt.ui.tests.refactoring/test
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
cases/org/eclipse/jdt/ui/tests/refactoring/RenameParametersTests.java
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
org.eclipse.jdt.ui.tests.refactoring/test
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
cases/org/eclipse/jdt/ui/tests/refactoring/RenamePrivateFieldTests.java
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
org.eclipse.jdt.ui.tests.refactoring/test
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
cases/org/eclipse/jdt/ui/tests/refactoring/RenamePrivateMethodTests.java
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
org.eclipse.jdt.ui.tests.refactoring/test
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
cases/org/eclipse/jdt/ui/tests/refactoring/RenameStaticMethodTests.java
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
org.eclipse.jdt.ui.tests.refactoring/test
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
cases/org/eclipse/jdt/ui/tests/refactoring/RenameTempTests.java
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
org.eclipse.jdt.ui.tests.refactoring/test
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
cases/org/eclipse/jdt/ui/tests/refactoring/RenameTypeTests.java
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
org.eclipse.jdt.ui.tests.refactoring/test
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
cases/org/eclipse/jdt/ui/tests/refactoring/RenameVirtualMethodInClassTests.java
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
org.eclipse.jdt.ui.tests.refactoring/test
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
cases/org/eclipse/jdt/ui/tests/refactoring/UseSupertypeWherePossibleTests.java
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
org.eclipse.jdt.ui.tests.refactoring/test
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
cases/org/eclipse/jdt/ui/tests/refactoring/infra/SourceCompareUtil.java
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
org.eclipse.jdt.ui.tests.refactoring/test
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
cases/org/eclipse/jdt/ui/tests/reorg/CopyTest.java
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
org.eclipse.jdt.ui.tests.refactoring/test
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
cases/org/eclipse/jdt/ui/tests/reorg/DeleteTest.java
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
org.eclipse.jdt.ui.tests.refactoring/test
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
cases/org/eclipse/jdt/ui/tests/reorg/MoveTest.java
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
org.eclipse.jdt.ui.tests.refactoring/test
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
cases/org/eclipse/jdt/ui/tests/reorg/MultiMoveTest.java
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
org.eclipse.jdt.ui.tests.refactoring/test
41,932
Bug 41932 Refactoring tests should use SourceCompareUtil [refactoring]
I20030825 Some of the refactoring tests still use assertEquals to compare source code. This asked for trouble if the two file have different line delimiters. All code should compare source code using SourceCompareUtil.compare. Note: I would like to see the method on RefactoringTest. AbstractCUTestCase already has such a method and having the method on RefactoringTest instead of in SourceCompareUtil gives us the possibility to merge the two classes in the long term.
resolved fixed
8c63f2f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T11:56:42Z
2003-08-25T16:46:40Z
cases/org/eclipse/jdt/ui/tests/reorg/PasteActionTest.java
41,912
Bug 41912 Pull Up fails while creating method stub in subclass
200308201005 + export 20030825_1222 Pull Up fails while creating method stub in subclass due to bug in ASTNodeFactory#newDefaultExpression. I'll add a fix. Steps: pull up "getCount", declare abstract in destination, create stubs checked - file A.java: public class A extends Root { private int fCount; public int getCount() { return fCount; } } - file B.java: public class B extends Root { } - file Root.java: public class Root { }
resolved fixed
f5ca45a
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T12:04:48Z
2003-08-25T11:13:20Z
org.eclipse.jdt.ui/core
41,912
Bug 41912 Pull Up fails while creating method stub in subclass
200308201005 + export 20030825_1222 Pull Up fails while creating method stub in subclass due to bug in ASTNodeFactory#newDefaultExpression. I'll add a fix. Steps: pull up "getCount", declare abstract in destination, create stubs checked - file A.java: public class A extends Root { private int fCount; public int getCount() { return fCount; } } - file B.java: public class B extends Root { } - file Root.java: public class Root { }
resolved fixed
f5ca45a
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-01T12:04:48Z
2003-08-25T11:13:20Z
extension/org/eclipse/jdt/internal/corext/dom/ASTNodeFactory.java
42,143
Bug 42143 Dialogs for source actions do not use dialog font [dialogs]
select a cu in package explorer context menu "Source": "Override/Implement methods..." "Generate Getters and Setters..." "Generate Delegate methods..." "Add constructor from superclass..." "Generate constructor using fields..."
closed fixed
72436fe
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-02T15:44:08Z
2003-08-27T16:00:00Z
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.ArrayList; 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.Group; 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.core.dom.Modifier; import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings; 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.refactoring.IVisibilityChangeListener; import org.eclipse.jdt.internal.ui.refactoring.RefactoringMessages; 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 int fVisibilityModifier; private boolean fFinal; private boolean fSynchronized; private final String SETTINGS_SECTION= "SourceActionDialog"; //$NON-NLS-1$ public final String SETTINGS_INSERTPOSITION= "InsertPosition"; //$NON-NLS-1$ private final String VISIBILITY_MODIFIER= "VisibilityModifier"; //$NON-NLS-1$ private final String FINAL_MODIFIER= "FinalModifier"; //$NON-NLS-1$ private final String SYNCHRONIZED_MODIFIER= "SynchronizedModifier"; //$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(); fGenerateComment= settings.createComments; IDialogSettings dialogSettings= JavaPlugin.getDefault().getDialogSettings(); fSettings= dialogSettings.getSection(SETTINGS_SECTION); if (fSettings == null) { fSettings= dialogSettings.addNewSection(SETTINGS_SECTION); fSettings.put(VISIBILITY_MODIFIER, Modifier.PUBLIC); //$NON-NLS-1$ fSettings.put(FINAL_MODIFIER, false); //$NON-NLS-1$ fSettings.put(SYNCHRONIZED_MODIFIER, false); //$NON-NLS-1$ fSettings.put(SETTINGS_INSERTPOSITION, 1); //$NON-NLS-1$ } try { fVisibilityModifier= fSettings.getInt(VISIBILITY_MODIFIER); fFinal= fSettings.getBoolean(FINAL_MODIFIER); fSynchronized= fSettings.getBoolean(SYNCHRONIZED_MODIFIER); fInsertPosition= fSettings.getInt(SETTINGS_INSERTPOSITION); } catch (NumberFormatException e) { fSettings= dialogSettings.addNewSection(SETTINGS_SECTION); fSettings.put(VISIBILITY_MODIFIER, Modifier.PUBLIC); //$NON-NLS-1$ fSettings.put(FINAL_MODIFIER, false); //$NON-NLS-1$ fSettings.put(SYNCHRONIZED_MODIFIER, false); //$NON-NLS-1$ fSettings.put(SETTINGS_INSERTPOSITION, 1); //$NON-NLS-1$ } } /*** * 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; } public int getVisibilityModifier() { return fVisibilityModifier; } 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; } public void setVisibility(int visibility) { if (fVisibilityModifier != visibility) { fVisibilityModifier= visibility; fSettings.put(VISIBILITY_MODIFIER, visibility); } } public void setFinal(boolean value) { if (fFinal != value) { fFinal= value; fSettings.put(FINAL_MODIFIER, value); } } public void setSynchronized(boolean value) { if (fSynchronized != value) { fSynchronized= value; fSettings.put(SYNCHRONIZED_MODIFIER, value); } } 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 addVisibilityAndModifiersChoices(Composite buttonComposite) { // Add visibility and modifiers buttons: http://bugs.eclipse.org/bugs/show_bug.cgi?id=35870 // Add persistence of options: http://bugs.eclipse.org/bugs/show_bug.cgi?id=38400 IVisibilityChangeListener visibilityChangeListener= new IVisibilityChangeListener(){ public void visibilityChanged(int newVisibility) { setVisibility(newVisibility); } public void modifierChanged(int modifier, boolean isChecked) { switch (modifier) { case Modifier.FINAL: { setFinal(isChecked); return; } case Modifier.SYNCHRONIZED: { setSynchronized(isChecked); return; } default: return; } } }; int initialVisibility= getVisibilityModifier(); int[] availableVisibilities= new int[]{Modifier.PUBLIC, Modifier.PROTECTED, Modifier.PRIVATE, Modifier.NONE}; Composite visibilityComposite= createVisibilityControlAndModifiers(buttonComposite, visibilityChangeListener, availableVisibilities, initialVisibility); return visibilityComposite; } private List convertToIntegerList(int[] array) { List result= new ArrayList(array.length); for (int i= 0; i < array.length; i++) { result.add(new Integer(array[i])); } return result; } protected Composite createVisibilityControl(Composite parent, final IVisibilityChangeListener visibilityChangeListener, int[] availableVisibilities, int correctVisibility) { List allowedVisibilities= convertToIntegerList(availableVisibilities); if (allowedVisibilities.size() == 1) return null; Group group= new Group(parent, SWT.NONE); group.setText(RefactoringMessages.getString("VisibilityControlUtil.Access_modifier")); //$NON-NLS-1$ GridData gd= new GridData(GridData.FILL_BOTH); group.setLayoutData(gd); GridLayout layout= new GridLayout(); layout.makeColumnsEqualWidth= true; layout.numColumns= 4; group.setLayout(layout); String[] labels= new String[] { "&public", //$NON-NLS-1$ "pro&tected", //$NON-NLS-1$ RefactoringMessages.getString("VisibilityControlUtil.defa&ult_4"), //$NON-NLS-1$ "pri&vate" //$NON-NLS-1$ }; Integer[] data= new Integer[] { new Integer(Modifier.PUBLIC), new Integer(Modifier.PROTECTED), new Integer(Modifier.NONE), new Integer(Modifier.PRIVATE)}; Integer initialVisibility= new Integer(correctVisibility); for (int i= 0; i < labels.length; i++) { Button radio= new Button(group, SWT.RADIO); Integer visibilityCode= data[i]; radio.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); radio.setText(labels[i]); radio.setData(visibilityCode); radio.setSelection(visibilityCode.equals(initialVisibility)); radio.setEnabled(allowedVisibilities.contains(visibilityCode)); radio.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { visibilityChangeListener.visibilityChanged(((Integer)event.widget.getData()).intValue()); } }); } return group; } protected Composite createVisibilityControlAndModifiers(Composite parent, final IVisibilityChangeListener visibilityChangeListener, int[] availableVisibilities, int correctVisibility) { Composite visibilityComposite= createVisibilityControl(parent, visibilityChangeListener, availableVisibilities, correctVisibility); Button finalCheckboxButton= new Button(visibilityComposite, SWT.CHECK); finalCheckboxButton.setText(RefactoringMessages.getString("VisibilityControlUtil.final")); //$NON-NLS-1$ GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); finalCheckboxButton.setLayoutData(gd); finalCheckboxButton.setData(new Integer(Modifier.FINAL)); finalCheckboxButton.setEnabled(true); finalCheckboxButton.setSelection(isFinal()); finalCheckboxButton.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent event) { visibilityChangeListener.modifierChanged(((Integer)event.widget.getData()).intValue(), ((Button) event.widget).getSelection()); } public void widgetDefaultSelected(SelectionEvent event) { widgetSelected(event); } }); Button syncCheckboxButton= new Button(visibilityComposite, SWT.CHECK); syncCheckboxButton.setText(RefactoringMessages.getString("VisibilityControlUtil.synchronized")); //$NON-NLS-1$ gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); syncCheckboxButton.setLayoutData(gd); syncCheckboxButton.setData(new Integer(Modifier.SYNCHRONIZED)); syncCheckboxButton.setEnabled(true); syncCheckboxButton.setSelection(isSynchronized()); syncCheckboxButton.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent event) { visibilityChangeListener.modifierChanged(((Integer)event.widget.getData()).intValue(), ((Button) event.widget).getSelection()); } public void widgetDefaultSelected(SelectionEvent event) { widgetSelected(event); } }); return visibilityComposite; } 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) { } } public boolean getFinal() { return fFinal; } public boolean getSynchronized() { return fSynchronized; } public boolean isFinal() { return fFinal; } public boolean isSynchronized() { return fSynchronized; } /* * 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; } }
42,143
Bug 42143 Dialogs for source actions do not use dialog font [dialogs]
select a cu in package explorer context menu "Source": "Override/Implement methods..." "Generate Getters and Setters..." "Generate Delegate methods..." "Add constructor from superclass..." "Generate constructor using fields..."
closed fixed
72436fe
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-02T15:44:08Z
2003-08-27T16:00:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/AddGetterSetterAction.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.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; 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.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.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.resource.ImageDescriptor; import org.eclipse.jface.text.IRewriteTarget; import org.eclipse.jface.text.ITextSelection; 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.Flags; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IField; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.ui.JavaElementImageDescriptor; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.ui.JavaElementSorter; import org.eclipse.jdt.internal.corext.codemanipulation.AddGetterSetterOperation; import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings; import org.eclipse.jdt.internal.corext.codemanipulation.GetterSetterUtil; import org.eclipse.jdt.internal.corext.codemanipulation.IRequestQuery; 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.JavaElementImageProvider; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels; /** * Creates getter and setter methods for a type's fields. Opens a dialog * with a list of fields for which a setter or getter can be generated. * User is able to check or uncheck items before setters or getters * are generated. * <p> * Will open the parent compilation unit in a Java editor. 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>IField</code> or <code>IType</code>. * * <p> * This class may be instantiated; it is not intended to be subclassed. * </p> * * @since 2.0 */ public class AddGetterSetterAction extends SelectionDispatchAction { private boolean fSort; private boolean fSynchronized; private boolean fFinal; private int fVisibility; private boolean fGenerateComment; private int fNumEntries; private CompilationUnitEditor fEditor; private static final String dialogTitle= ActionMessages.getString("AddGetterSetterAction.error.title"); //$NON-NLS-1$ /** * Creates a new <code>AddGetterSetterAction</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 AddGetterSetterAction(IWorkbenchSite site) { super(site); setText(ActionMessages.getString("AddGetterSetterAction.label")); //$NON-NLS-1$ setDescription(ActionMessages.getString("AddGetterSetterAction.description")); //$NON-NLS-1$ setToolTipText(ActionMessages.getString("AddGetterSetterAction.tooltip")); //$NON-NLS-1$ WorkbenchHelp.setHelp(this, IJavaHelpContextIds.GETTERSETTER_ACTION); } /** * Note: This constructor is for internal use only. Clients should not call this constructor. */ public AddGetterSetterAction(CompilationUnitEditor editor) { this(editor.getEditorSite()); fEditor= editor; setEnabled(SelectionConverter.getInputAsCompilationUnit(editor) != null); fEditor.getEditorSite(); } //---- 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); } } /* (non-Javadoc) * Method declared on SelectionDispatchAction */ public void run(IStructuredSelection selection) { try { IField[] selectedFields= getSelectedFields(selection); if (canRunOn(selectedFields)){ run(selectedFields[0].getDeclaringType(), selectedFields, false); return; } Object firstElement= selection.getFirstElement(); if (firstElement instanceof IType) run((IType)firstElement, new IField[0], false); else if (firstElement instanceof ICompilationUnit) { // http://bugs.eclipse.org/bugs/show_bug.cgi?id=38500 IType type= ((ICompilationUnit) firstElement).findPrimaryType(); if (type.isInterface()) { MessageDialog.openInformation(getShell(), dialogTitle, ActionMessages.getString("AddGetterSetterAction.interface_not_applicable")); //$NON-NLS-1$ return; } else run(((ICompilationUnit) firstElement).findPrimaryType(), new IField[0], false); } } catch (CoreException e) { ExceptionHandler.handle(e, getShell(), dialogTitle, ActionMessages.getString("AddGetterSetterAction.error.actionfailed")); //$NON-NLS-1$ } } 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; } private static boolean canRunOn(IField[] fields) throws JavaModelException { return fields != null && fields.length > 0; } private void resetNumEntries() { fNumEntries= 0; } private void incNumEntries() { fNumEntries++; } private void run(IType type, IField[] preselected, boolean editor) throws CoreException { if (type.isInterface()) { MessageDialog.openInformation(getShell(), dialogTitle, ActionMessages.getString("AddGetterSetterAction.interface_not_applicable")); //$NON-NLS-1$ return; } if (!ElementValidator.check(type, getShell(), dialogTitle, editor)) return; if (!ActionUtil.isProcessable(getShell(), type)) return; ILabelProvider lp= new AddGetterSetterLabelProvider(); resetNumEntries(); Map entries= createGetterSetterMapping(type); if (entries.isEmpty()){ MessageDialog.openInformation(getShell(), dialogTitle, ActionMessages.getString("AddGettSetterAction.typeContainsNoFields.message")); //$NON-NLS-1$ return; } AddGetterSetterContentProvider cp= new AddGetterSetterContentProvider(entries); GetterSetterTreeSelectionDialog dialog= new GetterSetterTreeSelectionDialog(getShell(), lp, cp, fEditor, type); dialog.setSorter(new JavaElementSorter()); dialog.setTitle(dialogTitle); String message= ActionMessages.getString("AddGetterSetterAction.dialog.label");//$NON-NLS-1$ dialog.setMessage(message); dialog.setValidator(createValidator(fNumEntries)); dialog.setContainerMode(true); dialog.setSize(60, 18); dialog.setInput(type); if (preselected.length > 0) { dialog.setInitialSelections(preselected); // http://bugs.eclipse.org/bugs/show_bug.cgi?id=38400 cp.setPreselected(preselected[0]); } int dialogResult= dialog.open(); if (dialogResult == Window.OK) { Object[] result= dialog.getResult(); if (result == null) return; fSort= dialog.getSortOrder(); fSynchronized= dialog.getSynchronized(); fFinal= dialog.getFinal(); fVisibility= dialog.getVisibilityModifier(); fGenerateComment= dialog.getGenerateComment(); IField[] getterFields, setterFields, getterSetterFields; if (fSort) { getterFields= getGetterFields(result); setterFields= getSetterFields(result); getterSetterFields= new IField[0]; } else { getterFields= getGetterOnlyFields(result); setterFields= getSetterOnlyFields(result); getterSetterFields= getGetterSetterFields(result); } IJavaElement elementPosition= dialog.getElementPosition(); generate(getterFields, setterFields, getterSetterFields, elementPosition); } } private static class AddGetterSetterSelectionStatusValidator implements ISelectionStatusValidator { private static int fEntries; AddGetterSetterSelectionStatusValidator(int entries) { fEntries= entries; } public IStatus validate(Object[] selection) { // https://bugs.eclipse.org/bugs/show_bug.cgi?id=38478 HashSet map= null; if ((selection != null) && (selection.length > 1)) { map= new HashSet(selection.length); } int count= 0; for (int i = 0; i < selection.length; i++) { try { if (selection[i] instanceof GetterSetterEntry) { Object key = selection[i]; IField getsetField= ((GetterSetterEntry) selection[i]).fField; if (((GetterSetterEntry) selection[i]).fGetterEntry) { if (!map.add(GetterSetterUtil.getGetterName(getsetField, null))) return new StatusInfo(IStatus.WARNING, ActionMessages.getString("AddGetterSetterAction.error.duplicate_methods")); //$NON-NLS-1$ } else { key= createSignatureKey(GetterSetterUtil.getSetterName(getsetField, null), getsetField); if (!map.add(key)) return new StatusInfo(IStatus.WARNING, ActionMessages.getString("AddGetterSetterAction.error.duplicate_methods")); //$NON-NLS-1$ } } count++; } } catch (JavaModelException e) { } } if (count == 0) return new StatusInfo(IStatus.ERROR, ""); //$NON-NLS-1$ String message= ActionMessages.getFormattedString("AddGetterSetterAction.methods_selected", //$NON-NLS-1$ new Object[] { String.valueOf(count), String.valueOf(fEntries)} ); return new StatusInfo(IStatus.INFO, message); } } /*** * Creates a key used for hashmaps for a method signature (gettersettername+arguments(fqn)) */ private static String createSignatureKey(String methodName, IField field) throws JavaModelException { StringBuffer buffer = new StringBuffer(); buffer.append(methodName); String fieldType= field.getTypeSignature(); String signature= Signature.getSimpleName(Signature.toString(fieldType)); buffer.append("#"); //$NON-NLS-1$ buffer.append(signature); return buffer.toString(); } private static ISelectionStatusValidator createValidator(int entries) { AddGetterSetterSelectionStatusValidator validator= new AddGetterSetterSelectionStatusValidator(entries); return validator; } // returns a list of fields with setter entries checked private static IField[] getSetterFields(Object[] result){ Collection list= new ArrayList(0); Object each= null; GetterSetterEntry entry= null; for (int i = 0; i < result.length; i++) { each= result[i]; if ((each instanceof GetterSetterEntry)){ entry= (GetterSetterEntry)each; if (! entry.fGetterEntry) { list.add(entry.fField); } } } return (IField[]) list.toArray(new IField[list.size()]); } // returns a list of fields with getter entries checked private static IField[] getGetterFields(Object[] result){ Collection list= new ArrayList(0); Object each= null; GetterSetterEntry entry= null; for (int i = 0; i < result.length; i++) { each= result[i]; if ((each instanceof GetterSetterEntry)){ entry= (GetterSetterEntry)each; if (entry.fGetterEntry) { list.add(entry.fField); } } } return (IField[]) list.toArray(new IField[list.size()]); } // returns a list of fields with only getter entires checked private static IField[] getGetterOnlyFields(Object[] result){ Collection list= new ArrayList(0); Object each= null; GetterSetterEntry entry= null; boolean getterSet= false; for (int i = 0; i < result.length; i++) { each= result[i]; if ((each instanceof GetterSetterEntry)){ entry= (GetterSetterEntry)each; if (entry.fGetterEntry) { list.add(entry.fField); getterSet= true; } if ((! entry.fGetterEntry) && (getterSet == true)) { list.remove(entry.fField); getterSet= false; } } else getterSet= false; } return (IField[]) list.toArray(new IField[list.size()]); } // returns a list of fields with only setter entries checked private static IField[] getSetterOnlyFields(Object[] result){ Collection list= new ArrayList(0); Object each= null; GetterSetterEntry entry= null; boolean getterSet= false; for (int i = 0; i < result.length; i++) { each= result[i]; if ((each instanceof GetterSetterEntry)){ entry= (GetterSetterEntry)each; if (entry.fGetterEntry) { getterSet= true; } if ((! entry.fGetterEntry) && (getterSet != true)) { list.add(entry.fField); getterSet= false; } } else getterSet= false; } return (IField[]) list.toArray(new IField[list.size()]); } // returns a list of fields with both entries checked private static IField[] getGetterSetterFields(Object[] result){ Collection list= new ArrayList(0); Object each= null; GetterSetterEntry entry= null; boolean getterSet= false; for (int i = 0; i < result.length; i++) { each= result[i]; if ((each instanceof GetterSetterEntry)){ entry= (GetterSetterEntry)each; if (entry.fGetterEntry) { getterSet= true; } if ((! entry.fGetterEntry) && (getterSet == true)) { list.add(entry.fField); getterSet= false; } } else getterSet= false; } return (IField[]) list.toArray(new IField[list.size()]); } private void generate(IField[] getterFields, IField[] setterFields, IField[] getterSetterFields, IJavaElement elementPosition) throws CoreException{ if (getterFields.length == 0 && setterFields.length == 0 && getterSetterFields.length == 0) return; ICompilationUnit cu= null; if (getterFields.length != 0) cu= getterFields[0].getCompilationUnit(); else if (setterFields.length != 0) cu= setterFields[0].getCompilationUnit(); else cu= getterSetterFields[0].getCompilationUnit(); //open the editor, forces the creation of a working copy IEditorPart editor= EditorUtility.openInEditor(cu); IField[] workingCopyGetterFields= getWorkingCopyFields(getterFields); IField[] workingCopySetterFields= getWorkingCopyFields(setterFields); IField[] workingCopyGetterSetterFields= getWorkingCopyFields(getterSetterFields); IJavaElement workingCopyElementPosition= getWorkingCopy(elementPosition); if (workingCopyGetterFields != null && workingCopySetterFields != null && workingCopyGetterSetterFields != null) run(workingCopyGetterFields, workingCopySetterFields, workingCopyGetterSetterFields, editor, workingCopyElementPosition); } private static IJavaElement getWorkingCopy(IJavaElement elementPosition) { if(elementPosition instanceof IMember) return JavaModelUtil.toWorkingCopy((IMember)elementPosition); return elementPosition; } private IField[] getWorkingCopyFields(IField[] fields) throws CoreException{ if (fields.length == 0) return new IField[0]; ICompilationUnit cu= fields[0].getCompilationUnit(); ICompilationUnit workingCopyCU; IField[] workingCopyFields; if (cu.isWorkingCopy()) { workingCopyCU= cu; workingCopyFields= fields; } else { workingCopyCU= EditorUtility.getWorkingCopy(cu); if (workingCopyCU == null) { showError(ActionMessages.getString("AddGetterSetterAction.error.actionfailed")); //$NON-NLS-1$ return null; } workingCopyFields= new IField[fields.length]; for (int i= 0; i < fields.length; i++) { IField field= fields[i]; IField workingCopyField= (IField) JavaModelUtil.findMemberInCompilationUnit(workingCopyCU, field); if (workingCopyField == null) { showError(ActionMessages.getFormattedString("AddGetterSetterAction.error.fieldNotExisting", field.getElementName())); //$NON-NLS-1$ return null; } workingCopyFields[i]= workingCopyField; } } return workingCopyFields; } //---- 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 input= SelectionConverter.getInput(fEditor); if (!ActionUtil.isProcessable(getShell(), input)) return; IJavaElement[] elements= SelectionConverter.codeResolve(fEditor); if (elements.length == 1 && (elements[0] instanceof IField)) { IField field= (IField)elements[0]; run(field.getDeclaringType(), new IField[] {field}, true); 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], true); return; } } } MessageDialog.openInformation(getShell(), dialogTitle, ActionMessages.getString("AddGetterSetterAction.not_applicable")); //$NON-NLS-1$ } catch (CoreException e) { ExceptionHandler.handle(e, getShell(), dialogTitle, ActionMessages.getString("AddGetterSetterAction.error.actionfailed")); //$NON-NLS-1$ } } //---- Helpers ------------------------------------------------------------------- private void run(IField[] getterFields, IField[] setterFields, IField[] getterSetterFields, IEditorPart editor, IJavaElement elementPosition) { IRewriteTarget target= (IRewriteTarget) editor.getAdapter(IRewriteTarget.class); if (target != null) { target.beginCompoundChange(); } try { AddGetterSetterOperation op= createAddGetterSetterOperation(getterFields, setterFields, getterSetterFields, elementPosition); setOperationStatusFields(op); IRunnableContext context= JavaPlugin.getActiveWorkbenchWindow(); if (context == null) { context= new BusyIndicatorRunnableContext(); } context.run(false, true, new WorkbenchRunnableAdapter(op)); IMethod[] createdMethods= op.getCreatedAccessors(); if (createdMethods.length > 0) { EditorUtility.revealInEditor(editor, createdMethods[0]); } } catch (InvocationTargetException e) { String message= ActionMessages.getString("AddGetterSetterAction.error.actionfailed"); //$NON-NLS-1$ ExceptionHandler.handle(e, getShell(), dialogTitle, message); } catch (InterruptedException e) { // operation cancelled } finally { if (target != null) { target.endCompoundChange(); } } } private void setOperationStatusFields(AddGetterSetterOperation op) { // Set the status fields corresponding to the visibility and modifiers set op.setSort(fSort); op.setVisibility(fVisibility); op.setSynchronized(fSynchronized); op.setFinal(fFinal); } private AddGetterSetterOperation createAddGetterSetterOperation(IField[] getterFields, IField[] setterFields, IField[] getterSetterFields, IJavaElement elementPosition) { IRequestQuery skipSetterForFinalQuery= skipSetterForFinalQuery(); IRequestQuery skipReplaceQuery= skipReplaceQuery(); CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(); settings.createComments= fGenerateComment; return new AddGetterSetterOperation(getterFields, setterFields, getterSetterFields, settings, skipSetterForFinalQuery, skipReplaceQuery, elementPosition); } private IRequestQuery skipSetterForFinalQuery() { return new IRequestQuery() { public int doQuery(IMember field) { // Fix for http://dev.eclipse.org/bugs/show_bug.cgi?id=19367 int[] returnCodes= {IRequestQuery.YES, IRequestQuery.YES_ALL, IRequestQuery.NO, IRequestQuery.CANCEL}; String[] options= {IDialogConstants.YES_LABEL, IDialogConstants.YES_TO_ALL_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL}; String fieldName= JavaElementLabels.getElementLabel(field, 0); String formattedMessage= ActionMessages.getFormattedString("AddGetterSetterAction.SkipSetterForFinalDialog.message", fieldName); //$NON-NLS-1$ return showQueryDialog(formattedMessage, options, returnCodes); } }; } private IRequestQuery skipReplaceQuery() { return new IRequestQuery() { public int doQuery(IMember method) { int[] returnCodes= {IRequestQuery.YES, IRequestQuery.NO, IRequestQuery.YES_ALL, IRequestQuery.CANCEL}; String skipLabel= ActionMessages.getString("AddGetterSetterAction.SkipExistingDialog.skip.label"); //$NON-NLS-1$ String replaceLabel= ActionMessages.getString("AddGetterSetterAction.SkipExistingDialog.replace.label"); //$NON-NLS-1$ String skipAllLabel= ActionMessages.getString("AddGetterSetterAction.SkipExistingDialog.skipAll.label"); //$NON-NLS-1$ String[] options= { skipLabel, replaceLabel, skipAllLabel, IDialogConstants.CANCEL_LABEL}; String methodName= JavaElementLabels.getElementLabel(method, JavaElementLabels.M_PARAMETER_TYPES); String formattedMessage= ActionMessages.getFormattedString("AddGetterSetterAction.SkipExistingDialog.message", methodName); //$NON-NLS-1$ return showQueryDialog(formattedMessage, options, returnCodes); } }; } private int showQueryDialog(final String message, final String[] buttonLabels, int[] returnCodes) { final Shell shell= getShell(); if (shell == null) { JavaPlugin.logErrorMessage("AddGetterSetterAction.showQueryDialog: No active shell found"); //$NON-NLS-1$ return IRequestQuery.CANCEL; } final int[] result= { Window.CANCEL }; shell.getDisplay().syncExec(new Runnable() { public void run() { String title= ActionMessages.getString("AddGetterSetterAction.QueryDialog.title"); //$NON-NLS-1$ MessageDialog dialog= new MessageDialog(shell, title, null, message, MessageDialog.QUESTION, buttonLabels, 0); result[0]= dialog.open(); } }); int returnVal= result[0]; return returnVal < 0 ? IRequestQuery.CANCEL : returnCodes[returnVal]; } private void showError(String message) { MessageDialog.openError(getShell(), dialogTitle, message); } /* * 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 setters/getters for interfaces return null; } } catch (JavaModelException e) { JavaPlugin.log(e); return null; } res[i]= fld; } else { return null; } } return res; } return null; } private static class AddGetterSetterLabelProvider extends JavaElementLabelProvider { AddGetterSetterLabelProvider() { } /* * @see ILabelProvider#getText(Object) */ public String getText(Object element) { if (element instanceof GetterSetterEntry) { GetterSetterEntry entry= (GetterSetterEntry) element; try { if (entry.fGetterEntry) { return GetterSetterUtil.getGetterName(entry.fField, null) + "()"; //$NON-NLS-1$ } else { return GetterSetterUtil.getSetterName(entry.fField, null) + '(' + Signature.getSimpleName(Signature.toString(entry.fField.getTypeSignature())) + ')'; } } catch (JavaModelException e) { return ""; //$NON-NLS-1$ } } return super.getText(element); } /* * @see ILabelProvider#getImage(Object) */ public Image getImage(Object element) { if (element instanceof GetterSetterEntry) { int flags= 0; try { flags= ((GetterSetterEntry) element).fField.getFlags(); } catch (JavaModelException e) { JavaPlugin.log(e); } ImageDescriptor desc= JavaElementImageProvider.getFieldImageDescriptor(false, Flags.AccPublic); int adornmentFlags= Flags.isStatic(flags) ? JavaElementImageDescriptor.STATIC : 0; desc= new JavaElementImageDescriptor(desc, adornmentFlags, JavaElementImageProvider.BIG_SIZE); return JavaPlugin.getImageDescriptorRegistry().get(desc); } return super.getImage(element); } } /** * @return map IField -> GetterSetterEntry[] */ private Map createGetterSetterMapping(IType type) throws JavaModelException{ IField[] fields= type.getFields(); Map result= new HashMap(); for (int i= 0; i < fields.length; i++) { List l= new ArrayList(2); if (GetterSetterUtil.getGetter(fields[i]) == null) { l.add(new GetterSetterEntry(fields[i], true)); incNumEntries(); } if (GetterSetterUtil.getSetter(fields[i]) == null) { l.add(new GetterSetterEntry(fields[i], false)); incNumEntries(); } if (! l.isEmpty()) result.put(fields[i], l.toArray(new GetterSetterEntry[l.size()])); } return result; } private static class AddGetterSetterContentProvider implements ITreeContentProvider { private static final Object[] EMPTY= new Object[0]; private Viewer fViewer; private Map fGetterSetterEntries; //IField -> Object[] (with 0 to 2 elements of type GetterSetterEntry) private IField fPreselected; public AddGetterSetterContentProvider(Map entries) throws JavaModelException { fGetterSetterEntries= entries; } public IField getPreselected() { return fPreselected; } public void setPreselected(IField preselected) { fPreselected= preselected; } /* * @see IContentProvider#inputChanged(Viewer, Object, Object) */ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { fViewer= viewer; } public Viewer getViewer() { return fViewer; } /* * @see ITreeContentProvider#getChildren(Object) */ public Object[] getChildren(Object parentElement) { if (parentElement instanceof IField) return (Object[])fGetterSetterEntries.get(parentElement); return EMPTY; } /* * @see ITreeContentProvider#getParent(Object) */ public Object getParent(Object element) { if (element instanceof IMember) return ((IMember)element).getDeclaringType(); if (element instanceof GetterSetterEntry) return ((GetterSetterEntry)element).fField; 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 fGetterSetterEntries.keySet().toArray(); } /* * @see IContentProvider#dispose() */ public void dispose() { fGetterSetterEntries.clear(); fGetterSetterEntries= null; } } private static class GetterSetterTreeSelectionDialog extends SourceActionDialog { private IType fType; private AddGetterSetterContentProvider fContentProvider; private static final int SELECT_GETTERS_ID= IDialogConstants.CLIENT_ID + 1; private static final int SELECT_SETTERS_ID= IDialogConstants.CLIENT_ID + 2; private IDialogSettings fSettings; private boolean fSortOrder; private final String SETTINGS_SECTION= "AddGetterSetterDialog"; //$NON-NLS-1$ private final String SORT_ORDER= "SortOrdering"; //$NON-NLS-1$ public GetterSetterTreeSelectionDialog(Shell parent, ILabelProvider labelProvider, AddGetterSetterContentProvider contentProvider, CompilationUnitEditor editor, IType type) { super(parent, labelProvider, contentProvider, editor, type); fContentProvider= contentProvider; fType= type; // http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253 IDialogSettings dialogSettings= JavaPlugin.getDefault().getDialogSettings(); fSettings= dialogSettings.getSection(SETTINGS_SECTION); if (fSettings == null) { fSettings= dialogSettings.addNewSection(SETTINGS_SECTION); fSettings.put(SORT_ORDER, false); //$NON-NLS-1$ } fSortOrder= fSettings.getBoolean(SORT_ORDER); } public boolean getSortOrder() { return fSortOrder; } public void setSortOrder(boolean sort) { if (fSortOrder != sort) { fSortOrder= sort; fSettings.put(SORT_ORDER, sort); if (fContentProvider.fViewer != null) { fContentProvider.fViewer.refresh(); } } } protected void createGetterSetterButtons(Composite buttonComposite) { createButton(buttonComposite, SELECT_GETTERS_ID, ActionMessages.getString("GetterSetterTreeSelectionDialog.select_getters"), false); //$NON-NLS-1$ createButton(buttonComposite, SELECT_SETTERS_ID, ActionMessages.getString("GetterSetterTreeSelectionDialog.select_setters"), false); //$NON-NLS-1$ } protected void buttonPressed(int buttonId) { super.buttonPressed(buttonId); switch(buttonId) { case SELECT_GETTERS_ID: { getTreeViewer().setCheckedElements(getGetterSetterElements(true)); updateOKStatus(); break; } case SELECT_SETTERS_ID: { getTreeViewer().setCheckedElements(getGetterSetterElements(false)); updateOKStatus(); break; } } } protected Composite createEntryPtCombo(Composite composite) { Composite entryComposite= super.createEntryPtCombo(composite); addSortOrder(entryComposite); addVisibilityAndModifiersChoices(entryComposite); return entryComposite; } private Composite addSortOrder(Composite composite) { Label label= new Label(composite, SWT.NONE); label.setText(ActionMessages.getString("GetterSetterTreeSelectionDialog.sort_label")); //$NON-NLS-1$ GridData gd= new GridData(GridData.FILL_BOTH); label.setLayoutData(gd); final Combo combo= new Combo(composite, SWT.READ_ONLY); combo.setItems(new String[]{ActionMessages.getString("GetterSetterTreeSelectionDialog.alpha_pair_sort"), //$NON-NLS-1$ ActionMessages.getString("GetterSetterTreeSelectionDialog.alpha_method_sort")}); //$NON-NLS-1$ final int methodIndex= 1; // Hard-coded. Change this if the list gets more complicated. // http://bugs.eclipse.org/bugs/show_bug.cgi?id=38400 int sort= getSortOrder() ? 1 : 0; combo.setText(combo.getItem(sort)); gd= new GridData(GridData.FILL_BOTH); combo.setLayoutData(gd); combo.addSelectionListener(new SelectionAdapter(){ public void widgetSelected(SelectionEvent e) { setSortOrder(combo.getSelectionIndex() == methodIndex); } }); return composite; } private Object[] getGetterSetterElements(boolean isGetter){ Object[] allFields= fContentProvider.getElements(null); Set result= new HashSet(); for (int i = 0; i < allFields.length; i++) { IField field= (IField)allFields[i]; GetterSetterEntry[] entries= getEntries(field); for (int j = 0; j < entries.length; j++) { AddGetterSetterAction.GetterSetterEntry entry= entries[j]; if (entry.fGetterEntry == isGetter) result.add(entry); } } return result.toArray(); } private GetterSetterEntry[] getEntries(IField field) { List result= Arrays.asList(fContentProvider.getChildren(field)); return (GetterSetterEntry[]) result.toArray(new GetterSetterEntry[result.size()]); } protected Composite createSelectionButtons(Composite composite) { Composite buttonComposite= super.createSelectionButtons(composite); GridLayout layout = new GridLayout(); buttonComposite.setLayout(layout); createGetterSetterButtons(buttonComposite); layout.marginHeight= 0; layout.marginWidth= 0; layout.numColumns= 1; return buttonComposite; } /* * @see Dialog#createDialogArea(Composite) */ protected Control createDialogArea(Composite parent) { Control control= super.createDialogArea(parent); try { // http://bugs.eclipse.org/bugs/show_bug.cgi?id=38400 getTreeViewer().setExpandedElements(fType.getFields()); getTreeViewer().reveal(fContentProvider.getPreselected()); getTreeViewer().refresh(); } catch (JavaModelException e) { } return control; } } private static class GetterSetterEntry { public final IField fField; public final boolean fGetterEntry; GetterSetterEntry(IField field, boolean isGetterEntry){ fField= field; fGetterEntry= isGetterEntry; } } }
42,143
Bug 42143 Dialogs for source actions do not use dialog font [dialogs]
select a cu in package explorer context menu "Source": "Override/Implement methods..." "Generate Getters and Setters..." "Generate Delegate methods..." "Add constructor from superclass..." "Generate constructor using fields..."
closed fixed
72436fe
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-02T15:44:08Z
2003-08-27T16:00:00Z
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(ActionMessages.getString("AddUnimplementedConstructorsAction.dialog.title")); //$NON-NLS-1$ 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; } } }
42,143
Bug 42143 Dialogs for source actions do not use dialog font [dialogs]
select a cu in package explorer context menu "Source": "Override/Implement methods..." "Generate Getters and Setters..." "Generate Delegate methods..." "Add constructor from superclass..." "Generate constructor using fields..."
closed fixed
72436fe
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-02T15:44:08Z
2003-08-27T16:00:00Z
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.ITypeHierarchy; 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.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.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; 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; } IMethod[] superConstructors= getSuperConstructors(type); if (superConstructors.length == 0) { MessageDialog.openInformation(getShell(), getDialogTitle(), ActionMessages.getString("GenerateConstructorUsingFieldsAction.error.nothing_found")); //$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, superConstructors); dialog.setCommentString(ActionMessages.getString("SourceActionDialog.createConstructorComment")); //$NON-NLS-1$ dialog.setTitle(ActionMessages.getString("GenerateConstructorUsingFieldsAction.dialog.title")); //$NON-NLS-1$ 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)); 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(); IMethod selectedConstructor= dialog.getSuperConstructorChoice(); AddCustomConstructorOperation op= new AddCustomConstructorOperation(type, settings, selected, false, elementPosition, selectedConstructor); op.setVisbility(dialog.getVisibilityModifier()); // Ignore the omit super() checkbox if the default constructor is not chosen if (selectedConstructor.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(); } } } } public static IMethod[] getSuperConstructors(IType type) throws CoreException { List constructorMethods= new ArrayList(); ITypeHierarchy hierarchy= type.newSupertypeHierarchy(null); IType supertype= hierarchy.getSuperclass(type); if (supertype != null) { IMethod[] superMethods= supertype.getMethods(); boolean constuctorFound= false; for (int i= 0; i < superMethods.length; i++) { IMethod curr= superMethods[i]; if (curr.isConstructor()) { constuctorFound= true; if (JavaModelUtil.isVisibleInHierarchy(curr, type.getPackageFragment())) { constructorMethods.add(curr); } } } if (!constuctorFound) { IType objectType= type.getJavaProject().findType("java.lang.Object"); //$NON-NLS-1$ IMethod curr= objectType.getMethod("Object", new String[0]); //$NON-NLS-1$ constructorMethods.add(curr); } } return (IMethod[]) constructorMethods.toArray(new IMethod[constructorMethods.size()]); } 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 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$ private Button fOmitSuperButton; public GenerateConstructorUsingFieldsSelectionDialog(Shell parent, ILabelProvider labelProvider, GenerateConstructorUsingFieldsContentProvider contentProvider, CompilationUnitEditor editor, IType type, IMethod[] superConstructors) { super(parent, labelProvider, contentProvider, editor, type); fContentProvider= contentProvider; fTreeViewerAdapter= new GenerateConstructorUsingFieldsTreeViewerAdapter(); fSuperConstructors= superConstructors; 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 Composite createVisibilityControlAndModifiers(Composite parent, final IVisibilityChangeListener visibilityChangeListener, int[] availableVisibilities, int correctVisibility) { Composite visibilityComposite= createVisibilityControl(parent, visibilityChangeListener, availableVisibilities, correctVisibility); return visibilityComposite; } 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()); fOmitSuperButton= new Button(omitSuperComposite, SWT.CHECK); fOmitSuperButton.setText(ActionMessages.getString("GenerateConstructorUsingFieldsSelectionDialog.omit.super")); //$NON-NLS-1$ fOmitSuperButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); fOmitSuperButton.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { boolean isSelected= (((Button) e.widget).getSelection()); setOmitSuper(isSelected); } public void widgetDefaultSelected(SelectionEvent e) { widgetSelected(e); } }); fOmitSuperButton.setSelection(isOmitSuper()); // Disable omit super checkbox unless default constructor fOmitSuperButton.setEnabled(getSuperConstructorChoice().getNumberOfParameters() == 0); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= 2; fOmitSuperButton.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); addVisibilityAndModifiersChoices(entryComposite); 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(); // Disable omit super checkbox unless default constructor fOmitSuperButton.setEnabled(getSuperConstructorChoice().getNumberOfParameters() == 0); updateOKStatus(); } }); return composite; } public CheckboxTreeViewer getTreeViewer() { return fTreeViewer; } public IMethod getSuperConstructorChoice() { return fSuperConstructors[fSuperIndex]; } 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 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,501
Bug 41501 type hierarchy: history dialog, button enablement incorrect [type hierarchy]
null
resolved fixed
35d712b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-06T13:22:27Z
2003-08-13T15:53:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/HistoryListAction.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.typehierarchy; import java.util.Arrays; import java.util.List; import org.eclipse.core.runtime.IStatus; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.action.Action; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.window.Window; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.ui.JavaElementLabelProvider; 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.dialogs.StatusDialog; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField; public class HistoryListAction extends Action { private class HistoryListDialog extends StatusDialog { private ListDialogField fHistoryList; private IStatus fHistoryStatus; private IJavaElement fResult; private HistoryListDialog(Shell shell, IJavaElement[] elements) { super(shell); setTitle(TypeHierarchyMessages.getString("HistoryListDialog.title")); //$NON-NLS-1$ String[] buttonLabels= new String[] { /* 0 */ TypeHierarchyMessages.getString("HistoryListDialog.remove.button"), //$NON-NLS-1$ }; IListAdapter adapter= new IListAdapter() { public void customButtonPressed(ListDialogField field, int index) { doCustomButtonPressed(); } public void selectionChanged(ListDialogField field) { doSelectionChanged(); } public void doubleClicked(ListDialogField field) { doDoubleClicked(); } }; JavaElementLabelProvider labelProvider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_QUALIFIED | JavaElementLabelProvider.SHOW_ROOT); fHistoryList= new ListDialogField(adapter, buttonLabels, labelProvider); fHistoryList.setLabelText(TypeHierarchyMessages.getString("HistoryListDialog.label")); //$NON-NLS-1$ fHistoryList.setElements(Arrays.asList(elements)); ISelection sel; if (elements.length > 0) { sel= new StructuredSelection(elements[0]); } else { sel= new StructuredSelection(); } fHistoryList.selectElements(sel); } /* * @see Dialog#createDialogArea(Composite) */ protected Control createDialogArea(Composite parent) { initializeDialogUnits(parent); Composite composite= (Composite) super.createDialogArea(parent); Composite inner= new Composite(composite, SWT.NONE); inner.setLayoutData(new GridData(GridData.FILL_BOTH)); LayoutUtil.doDefaultLayout(inner, new DialogField[] { fHistoryList }, true, 0, 0); LayoutUtil.setHeightHint(fHistoryList.getListControl(null), convertHeightInCharsToPixels(12)); LayoutUtil.setHorizontalGrabbing(fHistoryList.getListControl(null)); applyDialogFont(composite); return composite; } /** * Method doCustomButtonPressed. */ private void doCustomButtonPressed() { fHistoryList.removeElements(fHistoryList.getSelectedElements()); } private void doDoubleClicked() { if (fHistoryStatus.isOK()) { okPressed(); } } private void doSelectionChanged() { StatusInfo status= new StatusInfo(); List selected= fHistoryList.getSelectedElements(); if (selected.size() != 1) { status.setError(""); //$NON-NLS-1$ fResult= null; } else { fResult= (IJavaElement) selected.get(0); } fHistoryList.enableButton(0, fHistoryList.getSize() > selected.size()); fHistoryStatus= status; updateStatus(status); } public IJavaElement getResult() { return fResult; } public IJavaElement[] getRemaining() { List elems= fHistoryList.getElements(); return (IJavaElement[]) elems.toArray(new IJavaElement[elems.size()]); } /* * @see org.eclipse.jface.window.Window#configureShell(Shell) */ protected void configureShell(Shell newShell) { super.configureShell(newShell); WorkbenchHelp.setHelp(newShell, IJavaHelpContextIds.HISTORY_LIST_DIALOG); } /* (non-Javadoc) * @see org.eclipse.jface.window.Window#create() */ public void create() { setShellStyle(getShellStyle() | SWT.RESIZE); super.create(); } } private TypeHierarchyViewPart fView; public HistoryListAction(TypeHierarchyViewPart view) { fView= view; setText(TypeHierarchyMessages.getString("HistoryListAction.label")); //$NON-NLS-1$ JavaPluginImages.setLocalImageDescriptors(this, "history_list.gif"); //$NON-NLS-1$ WorkbenchHelp.setHelp(this, IJavaHelpContextIds.HISTORY_LIST_ACTION); } /* * @see IAction#run() */ public void run() { IJavaElement[] historyEntries= fView.getHistoryEntries(); HistoryListDialog dialog= new HistoryListDialog(JavaPlugin.getActiveWorkbenchShell(), historyEntries); if (dialog.open() == Window.OK) { fView.setHistoryEntries(dialog.getRemaining()); fView.setInputElement(dialog.getResult()); } } }
42,751
Bug 42751 TrackPositionTest uses "assert" as method name
Invalid for JDK 1.4. I'll attach a patch.
resolved fixed
8bf1c38
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-09T09:32:02Z
2003-09-09T06:46:40Z
org.eclipse.jdt.ui.tests.refactoring/test
42,751
Bug 42751 TrackPositionTest uses "assert" as method name
Invalid for JDK 1.4. I'll attach a patch.
resolved fixed
8bf1c38
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-09T09:32:02Z
2003-09-09T06:46:40Z
cases/org/eclipse/jdt/ui/tests/changes/TrackPositionTest.java
41,500
Bug 41500 call hierarchy: history dialog, button enablement incorrect [call hierarchy]
20030806 in the history dialog, the 'Remove' button is enabled when nothing is selected and disabled when everything is selected both are wrong
resolved fixed
f85b1e0
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-09T09:44:19Z
2003-08-13T15:53:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/callhierarchy/HistoryListAction.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: * Jesper Kamstrup Linnet (eclipse@kamstrup-linnet.dk) - initial API and implementation * (report 36180: Callers/Callees view) ******************************************************************************/ package org.eclipse.jdt.internal.ui.callhierarchy; import java.util.Arrays; import java.util.List; import org.eclipse.core.runtime.IStatus; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.action.Action; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.window.Window; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.ui.JavaElementLabelProvider; 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.dialogs.StatusDialog; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField; public class HistoryListAction extends Action { private class HistoryListDialog extends StatusDialog { private ListDialogField fHistoryList; private IStatus fHistoryStatus; private IMethod fResult; private HistoryListDialog(Shell shell, IMethod[] elements) { super(shell); setTitle(CallHierarchyMessages.getString("HistoryListDialog.title")); //$NON-NLS-1$ String[] buttonLabels= new String[] { /* 0 */ CallHierarchyMessages.getString("HistoryListDialog.remove.button"), //$NON-NLS-1$ }; IListAdapter adapter= new IListAdapter() { public void customButtonPressed(ListDialogField field, int index) { doCustomButtonPressed(); } public void selectionChanged(ListDialogField field) { doSelectionChanged(); } public void doubleClicked(ListDialogField field) { doDoubleClicked(); } }; JavaElementLabelProvider labelProvider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_QUALIFIED | JavaElementLabelProvider.SHOW_ROOT); fHistoryList= new ListDialogField(adapter, buttonLabels, labelProvider); fHistoryList.setLabelText(CallHierarchyMessages.getString("HistoryListDialog.label")); //$NON-NLS-1$ fHistoryList.setElements(Arrays.asList(elements)); ISelection sel; if (elements.length > 0) { sel= new StructuredSelection(elements[0]); } else { sel= new StructuredSelection(); } fHistoryList.selectElements(sel); } /* * @see Dialog#createDialogArea(Composite) */ protected Control createDialogArea(Composite parent) { initializeDialogUnits(parent); Composite composite= (Composite) super.createDialogArea(parent); Composite inner= new Composite(composite, SWT.NONE); inner.setLayoutData(new GridData(GridData.FILL_BOTH)); LayoutUtil.doDefaultLayout(inner, new DialogField[] { fHistoryList }, true, 0, 0); LayoutUtil.setHeightHint(fHistoryList.getListControl(null), convertHeightInCharsToPixels(12)); LayoutUtil.setHorizontalGrabbing(fHistoryList.getListControl(null)); applyDialogFont(composite); return composite; } /** * Method doCustomButtonPressed. */ private void doCustomButtonPressed() { fHistoryList.removeElements(fHistoryList.getSelectedElements()); } private void doDoubleClicked() { if (fHistoryStatus.isOK()) { okPressed(); } } private void doSelectionChanged() { StatusInfo status= new StatusInfo(); List selected= fHistoryList.getSelectedElements(); if (selected.size() != 1) { status.setError(""); //$NON-NLS-1$ fResult= null; } else { fResult= (IMethod) selected.get(0); } fHistoryList.enableButton(0, fHistoryList.getSize() > selected.size()); fHistoryStatus= status; updateStatus(status); } public IMethod getResult() { return fResult; } public IMethod[] getRemaining() { List elems= fHistoryList.getElements(); return (IMethod[]) elems.toArray(new IMethod[elems.size()]); } /* * @see org.eclipse.jface.window.Window#configureShell(Shell) */ protected void configureShell(Shell newShell) { super.configureShell(newShell); WorkbenchHelp.setHelp(newShell, IJavaHelpContextIds.HISTORY_LIST_DIALOG); } /* (non-Javadoc) * @see org.eclipse.jface.window.Window#create() */ public void create() { setShellStyle(getShellStyle() | SWT.RESIZE); super.create(); } } private CallHierarchyViewPart fView; public HistoryListAction(CallHierarchyViewPart view) { fView= view; setText(CallHierarchyMessages.getString("HistoryListAction.label")); //$NON-NLS-1$ JavaPluginImages.setLocalImageDescriptors(this, "history_list.gif"); //$NON-NLS-1$ WorkbenchHelp.setHelp(this, IJavaHelpContextIds.HISTORY_LIST_ACTION); } /* * @see IAction#run() */ public void run() { IMethod[] historyEntries= fView.getHistoryEntries(); HistoryListDialog dialog= new HistoryListDialog(JavaPlugin.getActiveWorkbenchShell(), historyEntries); if (dialog.open() == Window.OK) { fView.setHistoryEntries(dialog.getRemaining()); fView.setMethod(dialog.getResult()); } } }
42,700
Bug 42700 Add support for editing values in Externalize Strings wizard
null
resolved fixed
dddfb15
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-10T14:49:41Z
2003-09-08T14:06:40Z
org.eclipse.jdt.ui.tests.refactoring/test
42,700
Bug 42700 Add support for editing values in Externalize Strings wizard
null
resolved fixed
dddfb15
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-10T14:49:41Z
2003-09-08T14:06:40Z
cases/org/eclipse/jdt/ui/tests/nls/AllTests.java