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
43,437
Bug 43437 Scanner does not like string literals
20030922 1. Create a scanner and initalize it with the string "\"hello\"" 2. Read two tokens: You get a TokenNameStringLiteral and a InvalidInputException: Unterminated_String I'd expect to get - TokenNameStringLiteral and a - TokenNameEOF
verified fixed
4774113
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-24T08:26:34Z
2003-09-22T17:00:00Z
org.eclipse.jdt.ui/core
43,437
Bug 43437 Scanner does not like string literals
20030922 1. Create a scanner and initalize it with the string "\"hello\"" 2. Read two tokens: You get a TokenNameStringLiteral and a InvalidInputException: Unterminated_String I'd expect to get - TokenNameStringLiteral and a - TokenNameEOF
verified fixed
4774113
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-24T08:26:34Z
2003-09-22T17:00:00Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/reorg/SourceRangeComputer.java
43,437
Bug 43437 Scanner does not like string literals
20030922 1. Create a scanner and initalize it with the string "\"hello\"" 2. Read two tokens: You get a TokenNameStringLiteral and a InvalidInputException: Unterminated_String I'd expect to get - TokenNameStringLiteral and a - TokenNameEOF
verified fixed
4774113
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-24T08:26:34Z
2003-09-22T17:00:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/TaskMarkerProposal.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.text.correction; import org.eclipse.text.edits.ReplaceEdit; import org.eclipse.text.edits.TextEdit; import org.eclipse.core.runtime.CoreException; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.ToolFactory; import org.eclipse.jdt.core.compiler.IScanner; import org.eclipse.jdt.core.compiler.ITerminalSymbols; import org.eclipse.jdt.core.compiler.InvalidInputException; import org.eclipse.jface.text.Position; import org.eclipse.jdt.internal.corext.dom.TokenScanner; import org.eclipse.jdt.internal.corext.refactoring.changes.CompilationUnitChange; import org.eclipse.jdt.internal.corext.textmanipulation.TextBuffer; import org.eclipse.jdt.internal.corext.textmanipulation.TextRegion; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.ui.text.java.IProblemLocation; /** */ public class TaskMarkerProposal extends CUCorrectionProposal { private IProblemLocation fLocation; public TaskMarkerProposal(ICompilationUnit cu, IProblemLocation location, int relevance) { super("", cu, relevance, null); //$NON-NLS-1$ fLocation= location; setDisplayName(CorrectionMessages.getString("TaskMarkerProposal.description")); //$NON-NLS-1$ setImage(JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE)); } /* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal#createCompilationUnitChange(java.lang.String, org.eclipse.jdt.core.ICompilationUnit, org.eclipse.jdt.internal.corext.textmanipulation.TextEdit) */ protected CompilationUnitChange createCompilationUnitChange(String name, ICompilationUnit cu, TextEdit rootEdit) throws CoreException { CompilationUnitChange change= super.createCompilationUnitChange(name, cu, rootEdit); Position pos= null; TextBuffer buffer= null; try { buffer= TextBuffer.acquire(change.getFile()); pos= getUpdatedPosition(buffer); } finally { if (buffer != null) { TextBuffer.release(buffer); } } if (pos != null) { rootEdit.addChild(new ReplaceEdit(pos.getOffset(), pos.getLength(), "")); //$NON-NLS-1$ } else { rootEdit.addChild(new ReplaceEdit(fLocation.getOffset(), fLocation.getLength(), "")); //$NON-NLS-1$ } return change; } private Position getUpdatedPosition(TextBuffer buffer) { IScanner scanner= getSurroundingComment(buffer); if (scanner == null) { return null; } int commentStart= scanner.getCurrentTokenStartPosition(); int commentEnd= scanner.getCurrentTokenEndPosition() + 1; TextRegion startRegion= buffer.getLineInformationOfOffset(commentStart); int start= startRegion.getOffset(); if (hasContent(buffer.getContent(start, fLocation.getOffset() - start))) { return null; } int end; if (buffer.getChar(commentStart) == '/' && buffer.getChar(commentStart + 1) == '/') { end= commentEnd; } else { int endLine= buffer.getLineOfOffset(commentEnd - 1); if (endLine + 1 == buffer.getNumberOfLines()) { TextRegion endRegion= buffer.getLineInformation(endLine); end= endRegion.getOffset() + endRegion.getLength(); } else { TextRegion endRegion= buffer.getLineInformation(endLine + 1); end= endRegion.getOffset(); } } int posEnd= fLocation.getOffset() + fLocation.getLength(); if (hasContent(buffer.getContent(posEnd, end - posEnd))) { return null; } return new Position(start, end - start); } private IScanner getSurroundingComment(TextBuffer buffer) { try { IScanner scanner= ToolFactory.createScanner(true, false, false, false); scanner.setSource(buffer.getContent().toCharArray()); scanner.resetTo(0, buffer.getLength()); int start= fLocation.getOffset(); int end= start + fLocation.getLength(); int token= scanner.getNextToken(); while (token != ITerminalSymbols.TokenNameEOF) { if (TokenScanner.isComment(token)) { int currStart= scanner.getCurrentTokenStartPosition(); int currEnd= scanner.getCurrentTokenEndPosition() + 1; if (currStart <= start && end <= currEnd) { return scanner; } } token= scanner.getNextToken(); } } catch (InvalidInputException e) { // ignore } return null; } private boolean hasContent(String string) { for (int i= 0; i < string.length(); i++) { char ch= string.charAt(i); if (Character.isLetter(ch)) { return true; } } return false; } }
43,437
Bug 43437 Scanner does not like string literals
20030922 1. Create a scanner and initalize it with the string "\"hello\"" 2. Read two tokens: You get a TokenNameStringLiteral and a InvalidInputException: Unterminated_String I'd expect to get - TokenNameStringLiteral and a - TokenNameEOF
verified fixed
4774113
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-24T08:26:34Z
2003-09-22T17:00:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/ClassPathDetector.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.wizards; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceProxy; import org.eclipse.core.resources.IResourceProxyVisitor; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.JavaConventions; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.ToolFactory; import org.eclipse.jdt.core.compiler.CharOperation; 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.util.IClassFileReader; import org.eclipse.jdt.core.util.ISourceAttribute; import org.eclipse.jdt.ui.PreferenceConstants; /** */ public class ClassPathDetector implements IResourceProxyVisitor { private HashMap fSourceFolders; private List fClassFiles; private HashSet fJARFiles; private IProject fProject; private IPath fResultOutputFolder; private IClasspathEntry[] fResultClasspath; public ClassPathDetector(IProject project) throws CoreException { fSourceFolders= new HashMap(); fJARFiles= new HashSet(10); fClassFiles= new ArrayList(100); fProject= project; project.accept(this, IResource.NONE); fResultClasspath= null; fResultOutputFolder= null; detectClasspath(); } private boolean isNested(IPath path, Iterator iter) { while (iter.hasNext()) { IPath other= (IPath) iter.next(); if (other.isPrefixOf(path)) { return true; } } return false; } /** * Method detectClasspath. */ private void detectClasspath() { ArrayList cpEntries= new ArrayList(); detectSourceFolders(cpEntries); IPath outputLocation= detectOutputFolder(cpEntries); detectLibraries(cpEntries, outputLocation); if (cpEntries.isEmpty() && fClassFiles.isEmpty()) { return; } IClasspathEntry[] jreEntries= PreferenceConstants.getDefaultJRELibrary(); for (int i= 0; i < jreEntries.length; i++) { cpEntries.add(jreEntries[i]); } IClasspathEntry[] entries= (IClasspathEntry[]) cpEntries.toArray(new IClasspathEntry[cpEntries.size()]); if (!JavaConventions.validateClasspath(JavaCore.create(fProject), entries, outputLocation).isOK()) { return; } fResultClasspath= entries; fResultOutputFolder= outputLocation; } private IPath findInSourceFolders(IPath path) { Iterator iter= fSourceFolders.keySet().iterator(); while (iter.hasNext()) { Object key= iter.next(); List cus= (List) fSourceFolders.get(key); if (cus.contains(path)) { return (IPath) key; } } return null; } private IPath detectOutputFolder(List entries) { HashSet classFolders= new HashSet(); for (Iterator iter= fClassFiles.iterator(); iter.hasNext();) { IFile file= (IFile) iter.next(); IPath location= file.getLocation(); if (location == null) { continue; } IClassFileReader reader= ToolFactory.createDefaultClassFileReader(location.toOSString(), IClassFileReader.CLASSFILE_ATTRIBUTES); if (reader == null) { continue; // problematic class file } char[] className= reader.getClassName(); ISourceAttribute sourceAttribute= reader.getSourceFileAttribute(); if (className != null && sourceAttribute != null && sourceAttribute.getSourceFileName() != null) { IPath packPath= file.getParent().getFullPath(); int idx= CharOperation.lastIndexOf('/', className) + 1; IPath relPath= new Path(new String(className, 0, idx)); IPath cuPath= relPath.append(new String(sourceAttribute.getSourceFileName())); IPath resPath= null; if (idx == 0) { resPath= packPath; } else { IPath folderPath= getFolderPath(packPath, relPath); if (folderPath != null) { resPath= folderPath; } } if (resPath != null) { IPath path= findInSourceFolders(cuPath); if (path != null) { return resPath; } else { classFolders.add(resPath); } } } } IPath projPath= fProject.getFullPath(); if (fSourceFolders.size() == 1 && classFolders.isEmpty() && fSourceFolders.get(projPath) != null) { return projPath; } else { IPath path= projPath.append(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.SRCBIN_BINNAME)); while (classFolders.contains(path)) { path= new Path(path.toString() + '1'); } return path; } } private void detectLibraries(ArrayList cpEntries, IPath outputLocation) { Set sourceFolderSet= fSourceFolders.keySet(); for (Iterator iter= fJARFiles.iterator(); iter.hasNext();) { IPath path= (IPath) iter.next(); if (isNested(path, sourceFolderSet.iterator())) { continue; } if (outputLocation != null && outputLocation.isPrefixOf(path)) { continue; } IClasspathEntry entry= JavaCore.newLibraryEntry(path, null, null); cpEntries.add(entry); } } private void detectSourceFolders(ArrayList resEntries) { Set sourceFolderSet= fSourceFolders.keySet(); for (Iterator iter= sourceFolderSet.iterator(); iter.hasNext();) { IPath path= (IPath) iter.next(); ArrayList excluded= new ArrayList(); for (Iterator inner= sourceFolderSet.iterator(); inner.hasNext();) { IPath other= (IPath) inner.next(); if (!path.equals(other) && path.isPrefixOf(other)) { IPath pathToExclude= other.removeFirstSegments(path.segmentCount()).addTrailingSeparator(); excluded.add(pathToExclude); } } IPath[] excludedPaths= (IPath[]) excluded.toArray(new IPath[excluded.size()]); IClasspathEntry entry= JavaCore.newSourceEntry(path, excludedPaths); resEntries.add(entry); } } private void visitCompilationUnit(IFile file) { ICompilationUnit cu= JavaCore.createCompilationUnitFrom(file); if (cu != null) { ICompilationUnit workingCopy= null; try { workingCopy= (ICompilationUnit) cu.getWorkingCopy(); IPath relPath= getPackagePath(workingCopy.getSource()); IPath packPath= file.getParent().getFullPath(); String cuName= file.getName(); if (relPath == null) { addToMap(fSourceFolders, packPath, new Path(cuName)); } else { IPath folderPath= getFolderPath(packPath, relPath); if (folderPath != null) { addToMap(fSourceFolders, folderPath, relPath.append(cuName)); } } } catch (JavaModelException e) { // ignore } catch (InvalidInputException e) { // ignore } finally { if (workingCopy != null) { workingCopy.destroy(); } } } } private IPath getPackagePath(String source) throws InvalidInputException { IScanner scanner= ToolFactory.createScanner(false, false, false, false); scanner.setSource(source.toCharArray()); scanner.resetTo(0, scanner.getSource().length); int tok= scanner.getNextToken(); if (tok != ITerminalSymbols.TokenNamepackage) { return null; } IPath res= Path.EMPTY; do { tok= scanner.getNextToken(); if (tok == ITerminalSymbols.TokenNameIdentifier) { res= res.append(new String(scanner.getCurrentTokenSource())); } else { return res; } tok= scanner.getNextToken(); } while (tok == ITerminalSymbols.TokenNameDOT); return res; } private void addToMap(HashMap map, IPath folderPath, IPath relPath) { List list= (List) map.get(folderPath); if (list == null) { list= new ArrayList(50); map.put(folderPath, list); } list.add(relPath); } private IPath getFolderPath(IPath packPath, IPath relpath) { int remainingSegments= packPath.segmentCount() - relpath.segmentCount(); if (remainingSegments >= 0) { IPath common= packPath.removeFirstSegments(remainingSegments); if (common.equals(relpath)) { return packPath.uptoSegment(remainingSegments); } } return null; } private boolean hasExtension(String name, String ext) { return name.endsWith(ext) && (ext.length() != name.length()); } private boolean isValidCUName(String name) { return !JavaConventions.validateCompilationUnitName(name).matches(IStatus.ERROR); } /* (non-Javadoc) * @see org.eclipse.core.resources.IResourceProxyVisitor#visit(org.eclipse.core.resources.IResourceProxy) */ public boolean visit(IResourceProxy proxy) { if (proxy.getType() == IResource.FILE) { String name= proxy.getName(); if (hasExtension(name, ".java") && isValidCUName(name)) { //$NON-NLS-1$ visitCompilationUnit((IFile) proxy.requestResource()); } else if (hasExtension(name, ".class")) { //$NON-NLS-1$ fClassFiles.add(proxy.requestResource()); } else if (hasExtension(name, ".jar")) { //$NON-NLS-1$ fJARFiles.add(proxy.requestFullPath()); } return false; } return true; } public IPath getOutputLocation() { return fResultOutputFolder; } public IClasspathEntry[] getClasspath() { return fResultClasspath; } }
43,489
Bug 43489 Conflicts between "Segmented Java Editor" and "Correct Indentation"
I20030917 + plugin export for smoke test Correct Indentation (Ctrl+I) causes problems in segmented java editor (Toolbar > click "Show Source of selected element only"). - org.junit as source - open TestCase.java - enable "Show Source of selected element only" - select method "run()" in outline - set cursor to 1:1 - Ctrl+I -> whole type becomes visible in editor - select method "run()" in outline again - manually mangle indentation by insterting/deleting tabs - Ctrl+A, Ctrl+I -> whole type becomes visible in editor - Ctrl+Z (Undo) -> the undo TextEdits are applied to the wrong offset and destroy +/- arbitrary parts of my source!
resolved fixed
c68c682
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-24T10:19:44Z
2003-09-23T09:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/actions/IndentAction.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.actions; import java.util.ResourceBundle; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.swt.custom.BusyIndicator; import org.eclipse.swt.widgets.Display; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.text.Assert; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.DocumentCommand; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.IRewriteTarget; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.text.ITypedRegion; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.TextSelection; import org.eclipse.jface.text.TextUtilities; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.texteditor.IDocumentProvider; import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.ui.texteditor.ITextEditorExtension3; import org.eclipse.ui.texteditor.TextEditorAction; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.text.IJavaPartitions; import org.eclipse.jdt.internal.ui.text.JavaHeuristicScanner; import org.eclipse.jdt.internal.ui.text.JavaIndenter; import org.eclipse.jdt.internal.ui.text.javadoc.JavaDocAutoIndentStrategy; /** * Indents a line or range of lines in a Java document to its correct position. No complete * AST must be present, the indentation is computed using heuristics. The algorith used is fast for * single lines, but does not store any information and therefore not so efficient for large line * ranges. * * @see org.eclipse.jdt.internal.ui.text.JavaHeuristicScanner * @see org.eclipse.jdt.internal.ui.text.JavaIndenter * @since 3.0 */ public class IndentAction extends TextEditorAction { /** The caret offset after an indent operation. */ private int fCaretOffset; /** * Whether this is the action invoked by TAB. When <code>true</code>, indentation behaves * differently to accomodate normal TAB operation. */ private final boolean fIsTabAction; /** * Creates a new instance. * * @param bundle the resource bundle * @param prefix the prefix to use for keys in <code>bundle</code> * @param editor the text editor */ public IndentAction(ResourceBundle bundle, String prefix, ITextEditor editor, boolean isTabAction) { super(bundle, prefix, editor); fIsTabAction= isTabAction; } /* * @see org.eclipse.jface.action.Action#run() */ public void run() { // update has been called by the framework if (!isEnabled() || !validateEdit()) return; ITextSelection selection= getSelection(); final IDocument document= getDocument(); if (document != null) { final int offset= selection.getOffset(); final int length= selection.getLength(); final Position end= new Position(offset + length); final int firstLine, nLines; try { document.addPosition(end); firstLine= document.getLineOfOffset(offset); // check for marginal (zero-length) lines int minusOne= length == 0 ? 0 : 1; nLines= document.getLineOfOffset(offset + length - minusOne) - firstLine + 1; } catch (BadLocationException e) { // will only happen on concurrent modification JavaPlugin.log(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.OK, null, e)); return; } Runnable runnable= new Runnable() { public void run() { IRewriteTarget target= (IRewriteTarget)getTextEditor().getAdapter(IRewriteTarget.class); if (target != null) { target.beginCompoundChange(); target.setRedraw(false); } try { JavaHeuristicScanner scanner= new JavaHeuristicScanner(document); JavaIndenter indenter= new JavaIndenter(document, scanner); boolean hasChanged= false; for (int i= 0; i < nLines; i++) { hasChanged |= indentLine(document, firstLine + i, offset, indenter, scanner); } // update caret position: move to new position when indenting just one line // keep selection when indenting multiple int newOffset= fCaretOffset; int newLength= 0; if (nLines > 1) { newOffset= offset; newLength= end.getOffset() - offset; } Assert.isTrue(newLength >= 0); Assert.isTrue(newOffset >= 0); // always reset the selection if anything was replaced if (hasChanged || newOffset != offset || newLength != length) getTextEditor().selectAndReveal(newOffset, newLength); document.removePosition(end); } catch (BadLocationException e) { // will only happen on concurrent modification JavaPlugin.log(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.OK, null, e)); } finally { if (target != null) { target.endCompoundChange(); target.setRedraw(true); } } } }; if (nLines > 50) { Display display= getTextEditor().getEditorSite().getWorkbenchWindow().getShell().getDisplay(); BusyIndicator.showWhile(display, runnable); } else runnable.run(); } } /** * Indents a single line using the java heuristic scanner. Javadoc and multiline comments are * indented as specified by the <code>JavaDocAutoIndentStrategy</code>. * * @param document the document * @param line the line to be indented * @param caret the caret position * @param indenter the java indenter * @param scanner the heuristic scanner * @return <code>true</code> if <code>document</code> was modified, <code>false</code> otherwise * @throws BadLocationException if the document got changed concurrently */ private boolean indentLine(IDocument document, int line, int caret, JavaIndenter indenter, JavaHeuristicScanner scanner) throws BadLocationException { IRegion currentLine= document.getLineInformation(line); int offset= currentLine.getOffset(); String indent= null; if (offset < document.getLength()) { ITypedRegion partition= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, offset); String type= partition.getType(); if (partition.getOffset() < offset && type.equals(IJavaPartitions.JAVA_DOC) || type.equals(IJavaPartitions.JAVA_MULTI_LINE_COMMENT)) { // TODO this is a hack // what I want to do // new JavaDocAutoIndentStrategy().indentLineAtOffset(document, offset); // return; IRegion previousLine= document.getLineInformation(line - 1); DocumentCommand command= new DocumentCommand() { }; command.text= "\n"; //$NON-NLS-1$ command.offset= previousLine.getOffset() + previousLine.getLength(); new JavaDocAutoIndentStrategy(IJavaPartitions.JAVA_PARTITIONING).customizeDocumentCommand(document, command); int i= command.text.indexOf('*'); if (i != -1) indent= command.text.substring(1, i); else indent= command.text.substring(1); } } // standard java indentation if (indent == null) indent= indenter.computeIndentation(offset); // default is no indentation if (indent == null) indent= new String(); // change document: // get current white space int lineLength= currentLine.getLength(); int end= scanner.findNonWhitespaceForwardInAnyPartition(offset, offset + lineLength); if (end == JavaHeuristicScanner.NOT_FOUND) end= offset + lineLength; int length= end - offset; String currentIndent= document.get(offset, length); // if we are right before the text start / line end, and already after the insertion point // then just insert a tab. if (fIsTabAction && caret == end && whiteSpaceLength(currentIndent) >= whiteSpaceLength(indent)) { String tab= getTabEquivalent(); document.replace(caret, 0, tab); fCaretOffset= caret + tab.length(); return true; } // set the caret offset so it can be used when setting the selection fCaretOffset= offset + indent.length(); // only change the document if it is a real change if (!indent.equals(currentIndent)) { document.replace(offset, length, indent); return true; } else return false; } /** * Returns the size in characters of a string. All characters count one, tabs count the editor's * preference for the tab display * * @param indent the string to be measured. * @return */ private int whiteSpaceLength(String indent) { if (indent == null) return 0; else { int size= 0; int l= indent.length(); int tabSize= JavaPlugin.getDefault().getPreferenceStore().getInt(PreferenceConstants.EDITOR_TAB_WIDTH); for (int i= 0; i < l; i++) size += indent.charAt(i) == '\t' ? tabSize : 1; return size; } } /** * Returns a tab equivalent, either as a tab character or as spaces, depending on the editor and * formatter preferences. * * @return a string representing one tab in the editor, never <code>null</code> */ private String getTabEquivalent() { String tab; if (JavaPlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SPACES_FOR_TABS)) { int size= JavaCore.getPlugin().getPluginPreferences().getInt(JavaCore.FORMATTER_TAB_SIZE); StringBuffer buf= new StringBuffer(); for (int i= 0; i< size; i++) buf.append(' '); tab= buf.toString(); } else tab= "\t"; //$NON-NLS-1$ return tab; } /** * Returns the editor's selection provider. * * @return the editor's selection provider or <code>null</code> */ private ISelectionProvider getSelectionProvider() { ITextEditor editor= getTextEditor(); if (editor != null) { return editor.getSelectionProvider(); } return null; } /* * @see org.eclipse.ui.texteditor.IUpdate#update() */ public void update() { super.update(); if (isEnabled()) if (fIsTabAction) setEnabled(canModifyEditor() && isSmartMode() && isValidSelection()); else setEnabled(canModifyEditor() && !getSelection().isEmpty()); } /** * Returns if the current selection is valid, i.e. whether it is empty and the caret in the * whitespace at the start of a line, or covers multiple lines. * * @return <code>true</code> if the selection is valid for an indent operation */ private boolean isValidSelection() { ITextSelection selection= getSelection(); if (selection.isEmpty()) return false; int offset= selection.getOffset(); int length= selection.getLength(); IDocument document= getDocument(); if (document == null) return false; try { IRegion firstLine= document.getLineInformationOfOffset(offset); int lineOffset= firstLine.getOffset(); // either the selection has to be empty and the caret in the WS at the line start // or the selection has to extend over multiple lines if (length == 0) return document.get(lineOffset, offset - lineOffset).trim().length() == 0; else // return lineOffset + firstLine.getLength() < offset + length; return false; // only enable for empty selections for now } catch (BadLocationException e) { } return false; } /** * Returns the smart preference state. * * @return <code>true</code> if smart mode is on, <code>false</code> otherwise */ private boolean isSmartMode() { ITextEditor editor= getTextEditor(); if (editor instanceof ITextEditorExtension3) return ((ITextEditorExtension3) editor).getInsertMode() == ITextEditorExtension3.SMART_INSERT; return false; } /** * Returns the document currently displayed in the editor, or <code>null</code> if none can be * obtained. * * @return the current document or <code>null</code> */ private IDocument getDocument() { ITextEditor editor= getTextEditor(); if (editor != null) { IDocumentProvider provider= editor.getDocumentProvider(); IEditorInput input= editor.getEditorInput(); if (provider != null && input != null) return provider.getDocument(input); } return null; } /** * Returns the selection on the editor or an invalid selection if none can be obtained. Returns * never <code>null</code>. * * @return the current selection, never <code>null</code> */ private ITextSelection getSelection() { ISelectionProvider provider= getSelectionProvider(); if (provider != null) { ISelection selection= provider.getSelection(); if (selection instanceof ITextSelection) return (ITextSelection) selection; } // null object return TextSelection.emptySelection(); } }
43,146
Bug 43146 [misc] Assertion failed in LinkedPositionManager.getPositions when using surrounding with try-catch
OSX 10.2.6 Eclipse I20030916 Doing a surround with try catch: !ENTRY org.eclipse.jdt.ui 4 10004 Sep 16, 2003 15:13:55.722 !MESSAGE Unrecoverable error occurred while performing the refactoring. !STACK 0 ChangeAbortException: org.eclipse.jdt.internal.corext.refactoring.base.ChangeAbortException at org.eclipse.jdt.internal.ui.refactoring.changes.AbortChangeExceptionHandler.handle(AbortChangeExcept ionHandler.java:28) at org.eclipse.jdt.internal.corext.refactoring.base.Change.handleException(Change.java:108) at org.eclipse.jdt.internal.corext.refactoring.changes.AbstractTextChange.perform(AbstractTextChange.jav a:201) at org.eclipse.jdt.internal.corext.refactoring.changes.TextFileChange.perform(TextFileChange.java:208) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation$1.run(PerformChangeOperation.java:173 ) at org.eclipse.jdt.internal.core.BatchOperation.executeOperation(BatchOperation.java:34) at org.eclipse.jdt.internal.core.JavaModelOperation.execute(JavaModelOperation.java:366) at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:705) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1571) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1588) at org.eclipse.jdt.core.JavaCore.run(JavaCore.java:2963) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.executeChange(PerformChangeOperation .java:183) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run(PerformChangeOperation.java:151) at org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext$BusyRunnable.internalRun(BusyIndicatorRu nnableContext.java:113) at org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext$BusyRunnable.run(BusyIndicatorRunnableC ontext.java:80) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:84) at org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext.run(BusyIndicatorRunnableContext.java:126 ) at org.eclipse.jdt.ui.actions.SurroundWithTryCatchAction.run(SurroundWithTryCatchAction.java:127) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun(SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run(SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:529) at org.eclipse.jface.action.ActionContributionItem.access$4(ActionContributionItem.java:482) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent(ActionContributionItem.java:454) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:1027) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2180) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1878) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2037) at org.eclipse.ui.internal.Workbench.run(Workbench.java:2020) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:295) at org.eclipse.core.launcher.Main.run(Main.java:751) at org.eclipse.core.launcher.Main.main(Main.java:587) Exception wrapped by ChangeAbortException: org.eclipse.jface.text.Assert$AssertionFailedException: Assertion failed: at org.eclipse.jface.text.Assert.isTrue(Assert.java:175) at org.eclipse.jface.text.Assert.isTrue(Assert.java:160) at org.eclipse.jdt.internal.ui.text.link.LinkedPositionManager.getPositions(LinkedPositionManager.java:427) at org.eclipse.jdt.internal.ui.text.link.LinkedPositionManager.documentAboutToBeChanged(LinkedPosition Manager.java:477) at org.eclipse.jface.text.AbstractDocument.fireDocumentAboutToBeChanged(AbstractDocument.java:549) at org.eclipse.jface.text.AbstractDocument.replace(AbstractDocument.java:956) at org.eclipse.jdt.internal.ui.javaeditor.PartiallySynchronizedDocument.replace(PartiallySynchronizedDocum ent.java:61) at org.eclipse.jdt.internal.corext.textmanipulation.TextEdit.performReplace(TextEdit.java:401) at org.eclipse.jdt.internal.corext.textmanipulation.SimpleTextEdit.perform(SimpleTextEdit.java:80) at org.eclipse.jdt.internal.corext.textmanipulation.EditProcessor.execute(EditProcessor.java:183) at org.eclipse.jdt.internal.corext.textmanipulation.EditProcessor.execute(EditProcessor.java:178) at org.eclipse.jdt.internal.corext.textmanipulation.EditProcessor.execute(EditProcessor.java:178) at org.eclipse.jdt.internal.corext.textmanipulation.EditProcessor.execute(EditProcessor.java:178) at org.eclipse.jdt.internal.corext.textmanipulation.EditProcessor.executeDo(EditProcessor.java:163) at org.eclipse.jdt.internal.corext.textmanipulation.EditProcessor.performEdits(EditProcessor.java:121) at org.eclipse.jdt.internal.corext.textmanipulation.TextBufferEditor.performEdits(TextBufferEditor.java:55) at org.eclipse.jdt.internal.corext.refactoring.changes.AbstractTextChange.perform(AbstractTextChange.jav a:199) at org.eclipse.jdt.internal.corext.refactoring.changes.TextFileChange.perform(TextFileChange.java:208) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation$1.run(PerformChangeOperation.java:173 ) at org.eclipse.jdt.internal.core.BatchOperation.executeOperation(BatchOperation.java:34) at org.eclipse.jdt.internal.core.JavaModelOperation.execute(JavaModelOperation.java:366) at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:705) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1571) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1588) at org.eclipse.jdt.core.JavaCore.run(JavaCore.java:2963) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.executeChange(PerformChangeOperation .java:183) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run(PerformChangeOperation.java:151) at org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext$BusyRunnable.internalRun(BusyIndicatorRu nnableContext.java:113) at org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext$BusyRunnable.run(BusyIndicatorRunnableC ontext.java:80) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:84) at org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext.run(BusyIndicatorRunnableContext.java:126 ) at org.eclipse.jdt.ui.actions.SurroundWithTryCatchAction.run(SurroundWithTryCatchAction.java:127) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun(SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run(SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:529) at org.eclipse.jface.action.ActionContributionItem.access$4(ActionContributionItem.java:482) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent(ActionContributionItem.java:454) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:1027) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2180) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1878) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2037) at org.eclipse.ui.internal.Workbench.run(Workbench.java:2020) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:295) at org.eclipse.core.launcher.Main.run(Main.java:751) at org.eclipse.core.launcher.Main.main(Main.java:587)
verified fixed
9f21086
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-24T10:53:39Z
2003-09-16T13:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/link/ILinkedPositionListener.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 org.eclipse.jface.text.Position; /** * A listener for highlight change notification and exititing linked mode. */ public interface ILinkedPositionListener { /** * Notifies that the linked mode has been left. On success, all changes * are kept, otherwise all changes made to the linked positions are restored * to the state before entering linked mode. */ void exit(boolean success); /** * Notifies the changed linked position. The listener is asked * to reposition the caret at the given offset. * * @param position the linked position which initiated the change. * @param caretOffset the caret offset relative to the position. */ void setCurrentPosition(Position position, int caretOffset); }
43,146
Bug 43146 [misc] Assertion failed in LinkedPositionManager.getPositions when using surrounding with try-catch
OSX 10.2.6 Eclipse I20030916 Doing a surround with try catch: !ENTRY org.eclipse.jdt.ui 4 10004 Sep 16, 2003 15:13:55.722 !MESSAGE Unrecoverable error occurred while performing the refactoring. !STACK 0 ChangeAbortException: org.eclipse.jdt.internal.corext.refactoring.base.ChangeAbortException at org.eclipse.jdt.internal.ui.refactoring.changes.AbortChangeExceptionHandler.handle(AbortChangeExcept ionHandler.java:28) at org.eclipse.jdt.internal.corext.refactoring.base.Change.handleException(Change.java:108) at org.eclipse.jdt.internal.corext.refactoring.changes.AbstractTextChange.perform(AbstractTextChange.jav a:201) at org.eclipse.jdt.internal.corext.refactoring.changes.TextFileChange.perform(TextFileChange.java:208) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation$1.run(PerformChangeOperation.java:173 ) at org.eclipse.jdt.internal.core.BatchOperation.executeOperation(BatchOperation.java:34) at org.eclipse.jdt.internal.core.JavaModelOperation.execute(JavaModelOperation.java:366) at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:705) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1571) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1588) at org.eclipse.jdt.core.JavaCore.run(JavaCore.java:2963) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.executeChange(PerformChangeOperation .java:183) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run(PerformChangeOperation.java:151) at org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext$BusyRunnable.internalRun(BusyIndicatorRu nnableContext.java:113) at org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext$BusyRunnable.run(BusyIndicatorRunnableC ontext.java:80) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:84) at org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext.run(BusyIndicatorRunnableContext.java:126 ) at org.eclipse.jdt.ui.actions.SurroundWithTryCatchAction.run(SurroundWithTryCatchAction.java:127) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun(SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run(SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:529) at org.eclipse.jface.action.ActionContributionItem.access$4(ActionContributionItem.java:482) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent(ActionContributionItem.java:454) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:1027) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2180) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1878) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2037) at org.eclipse.ui.internal.Workbench.run(Workbench.java:2020) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:295) at org.eclipse.core.launcher.Main.run(Main.java:751) at org.eclipse.core.launcher.Main.main(Main.java:587) Exception wrapped by ChangeAbortException: org.eclipse.jface.text.Assert$AssertionFailedException: Assertion failed: at org.eclipse.jface.text.Assert.isTrue(Assert.java:175) at org.eclipse.jface.text.Assert.isTrue(Assert.java:160) at org.eclipse.jdt.internal.ui.text.link.LinkedPositionManager.getPositions(LinkedPositionManager.java:427) at org.eclipse.jdt.internal.ui.text.link.LinkedPositionManager.documentAboutToBeChanged(LinkedPosition Manager.java:477) at org.eclipse.jface.text.AbstractDocument.fireDocumentAboutToBeChanged(AbstractDocument.java:549) at org.eclipse.jface.text.AbstractDocument.replace(AbstractDocument.java:956) at org.eclipse.jdt.internal.ui.javaeditor.PartiallySynchronizedDocument.replace(PartiallySynchronizedDocum ent.java:61) at org.eclipse.jdt.internal.corext.textmanipulation.TextEdit.performReplace(TextEdit.java:401) at org.eclipse.jdt.internal.corext.textmanipulation.SimpleTextEdit.perform(SimpleTextEdit.java:80) at org.eclipse.jdt.internal.corext.textmanipulation.EditProcessor.execute(EditProcessor.java:183) at org.eclipse.jdt.internal.corext.textmanipulation.EditProcessor.execute(EditProcessor.java:178) at org.eclipse.jdt.internal.corext.textmanipulation.EditProcessor.execute(EditProcessor.java:178) at org.eclipse.jdt.internal.corext.textmanipulation.EditProcessor.execute(EditProcessor.java:178) at org.eclipse.jdt.internal.corext.textmanipulation.EditProcessor.executeDo(EditProcessor.java:163) at org.eclipse.jdt.internal.corext.textmanipulation.EditProcessor.performEdits(EditProcessor.java:121) at org.eclipse.jdt.internal.corext.textmanipulation.TextBufferEditor.performEdits(TextBufferEditor.java:55) at org.eclipse.jdt.internal.corext.refactoring.changes.AbstractTextChange.perform(AbstractTextChange.jav a:199) at org.eclipse.jdt.internal.corext.refactoring.changes.TextFileChange.perform(TextFileChange.java:208) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation$1.run(PerformChangeOperation.java:173 ) at org.eclipse.jdt.internal.core.BatchOperation.executeOperation(BatchOperation.java:34) at org.eclipse.jdt.internal.core.JavaModelOperation.execute(JavaModelOperation.java:366) at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:705) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1571) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1588) at org.eclipse.jdt.core.JavaCore.run(JavaCore.java:2963) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.executeChange(PerformChangeOperation .java:183) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run(PerformChangeOperation.java:151) at org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext$BusyRunnable.internalRun(BusyIndicatorRu nnableContext.java:113) at org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext$BusyRunnable.run(BusyIndicatorRunnableC ontext.java:80) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:84) at org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext.run(BusyIndicatorRunnableContext.java:126 ) at org.eclipse.jdt.ui.actions.SurroundWithTryCatchAction.run(SurroundWithTryCatchAction.java:127) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun(SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run(SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:529) at org.eclipse.jface.action.ActionContributionItem.access$4(ActionContributionItem.java:482) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent(ActionContributionItem.java:454) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:1027) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2180) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1878) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2037) at org.eclipse.ui.internal.Workbench.run(Workbench.java:2020) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:295) at org.eclipse.core.launcher.Main.run(Main.java:751) at org.eclipse.core.launcher.Main.main(Main.java:587)
verified fixed
9f21086
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-24T10:53:39Z
2003-09-16T13:46:40Z
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; private boolean fMustLeave; /** * 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) { try { uninstall(success); if (fListener != null) fListener.exit(success); } finally { fMustLeave= false; } } /* * @see IDocumentListener#documentAboutToBeChanged(DocumentEvent) */ public void documentAboutToBeChanged(DocumentEvent event) { if (fMustLeave) { leave(true); return; } 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)) { // see bug 41849 if (length + deltaLength < 0) { fMustLeave= true; return; } 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) { if (fMustLeave) { leave(true); return; } // 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); } } } }
43,146
Bug 43146 [misc] Assertion failed in LinkedPositionManager.getPositions when using surrounding with try-catch
OSX 10.2.6 Eclipse I20030916 Doing a surround with try catch: !ENTRY org.eclipse.jdt.ui 4 10004 Sep 16, 2003 15:13:55.722 !MESSAGE Unrecoverable error occurred while performing the refactoring. !STACK 0 ChangeAbortException: org.eclipse.jdt.internal.corext.refactoring.base.ChangeAbortException at org.eclipse.jdt.internal.ui.refactoring.changes.AbortChangeExceptionHandler.handle(AbortChangeExcept ionHandler.java:28) at org.eclipse.jdt.internal.corext.refactoring.base.Change.handleException(Change.java:108) at org.eclipse.jdt.internal.corext.refactoring.changes.AbstractTextChange.perform(AbstractTextChange.jav a:201) at org.eclipse.jdt.internal.corext.refactoring.changes.TextFileChange.perform(TextFileChange.java:208) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation$1.run(PerformChangeOperation.java:173 ) at org.eclipse.jdt.internal.core.BatchOperation.executeOperation(BatchOperation.java:34) at org.eclipse.jdt.internal.core.JavaModelOperation.execute(JavaModelOperation.java:366) at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:705) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1571) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1588) at org.eclipse.jdt.core.JavaCore.run(JavaCore.java:2963) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.executeChange(PerformChangeOperation .java:183) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run(PerformChangeOperation.java:151) at org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext$BusyRunnable.internalRun(BusyIndicatorRu nnableContext.java:113) at org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext$BusyRunnable.run(BusyIndicatorRunnableC ontext.java:80) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:84) at org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext.run(BusyIndicatorRunnableContext.java:126 ) at org.eclipse.jdt.ui.actions.SurroundWithTryCatchAction.run(SurroundWithTryCatchAction.java:127) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun(SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run(SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:529) at org.eclipse.jface.action.ActionContributionItem.access$4(ActionContributionItem.java:482) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent(ActionContributionItem.java:454) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:1027) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2180) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1878) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2037) at org.eclipse.ui.internal.Workbench.run(Workbench.java:2020) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:295) at org.eclipse.core.launcher.Main.run(Main.java:751) at org.eclipse.core.launcher.Main.main(Main.java:587) Exception wrapped by ChangeAbortException: org.eclipse.jface.text.Assert$AssertionFailedException: Assertion failed: at org.eclipse.jface.text.Assert.isTrue(Assert.java:175) at org.eclipse.jface.text.Assert.isTrue(Assert.java:160) at org.eclipse.jdt.internal.ui.text.link.LinkedPositionManager.getPositions(LinkedPositionManager.java:427) at org.eclipse.jdt.internal.ui.text.link.LinkedPositionManager.documentAboutToBeChanged(LinkedPosition Manager.java:477) at org.eclipse.jface.text.AbstractDocument.fireDocumentAboutToBeChanged(AbstractDocument.java:549) at org.eclipse.jface.text.AbstractDocument.replace(AbstractDocument.java:956) at org.eclipse.jdt.internal.ui.javaeditor.PartiallySynchronizedDocument.replace(PartiallySynchronizedDocum ent.java:61) at org.eclipse.jdt.internal.corext.textmanipulation.TextEdit.performReplace(TextEdit.java:401) at org.eclipse.jdt.internal.corext.textmanipulation.SimpleTextEdit.perform(SimpleTextEdit.java:80) at org.eclipse.jdt.internal.corext.textmanipulation.EditProcessor.execute(EditProcessor.java:183) at org.eclipse.jdt.internal.corext.textmanipulation.EditProcessor.execute(EditProcessor.java:178) at org.eclipse.jdt.internal.corext.textmanipulation.EditProcessor.execute(EditProcessor.java:178) at org.eclipse.jdt.internal.corext.textmanipulation.EditProcessor.execute(EditProcessor.java:178) at org.eclipse.jdt.internal.corext.textmanipulation.EditProcessor.executeDo(EditProcessor.java:163) at org.eclipse.jdt.internal.corext.textmanipulation.EditProcessor.performEdits(EditProcessor.java:121) at org.eclipse.jdt.internal.corext.textmanipulation.TextBufferEditor.performEdits(TextBufferEditor.java:55) at org.eclipse.jdt.internal.corext.refactoring.changes.AbstractTextChange.perform(AbstractTextChange.jav a:199) at org.eclipse.jdt.internal.corext.refactoring.changes.TextFileChange.perform(TextFileChange.java:208) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation$1.run(PerformChangeOperation.java:173 ) at org.eclipse.jdt.internal.core.BatchOperation.executeOperation(BatchOperation.java:34) at org.eclipse.jdt.internal.core.JavaModelOperation.execute(JavaModelOperation.java:366) at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:705) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1571) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1588) at org.eclipse.jdt.core.JavaCore.run(JavaCore.java:2963) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.executeChange(PerformChangeOperation .java:183) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run(PerformChangeOperation.java:151) at org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext$BusyRunnable.internalRun(BusyIndicatorRu nnableContext.java:113) at org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext$BusyRunnable.run(BusyIndicatorRunnableC ontext.java:80) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:84) at org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext.run(BusyIndicatorRunnableContext.java:126 ) at org.eclipse.jdt.ui.actions.SurroundWithTryCatchAction.run(SurroundWithTryCatchAction.java:127) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun(SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run(SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:529) at org.eclipse.jface.action.ActionContributionItem.access$4(ActionContributionItem.java:482) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent(ActionContributionItem.java:454) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:1027) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2180) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1878) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2037) at org.eclipse.ui.internal.Workbench.run(Workbench.java:2020) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:295) at org.eclipse.core.launcher.Main.run(Main.java:751) at org.eclipse.core.launcher.Main.main(Main.java:587)
verified fixed
9f21086
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-24T10:53:39Z
2003-09-16T13:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/link/LinkedPositionUI.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.lang.reflect.InvocationTargetException; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.custom.VerifyKeyListener; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.events.ShellListener; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.events.VerifyListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferenceConverter; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.text.Assert; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.BadPositionCategoryException; import org.eclipse.jface.text.DefaultPositionUpdater; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IPositionUpdater; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.IRewriteTarget; import org.eclipse.jface.text.ITextInputListener; import org.eclipse.jface.text.ITextListener; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.ITextViewerExtension; import org.eclipse.jface.text.ITextViewerExtension2; import org.eclipse.jface.text.ITextViewerExtension3; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.Region; import org.eclipse.jface.text.TextEvent; import org.eclipse.jface.text.TextUtilities; import org.eclipse.jface.text.contentassist.ICompletionProposal; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.text.IJavaPartitions; import org.eclipse.jdt.internal.ui.text.link.contentassist.ContentAssistant2; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; /** * A user interface for <code>LinkedPositionManager</code>, using <code>ITextViewer</code>. */ public class LinkedPositionUI implements ILinkedPositionListener, ITextInputListener, ITextListener, ModifyListener, VerifyListener, VerifyKeyListener, PaintListener, IPropertyChangeListener, ShellListener { /** * A listener for notification when the user cancelled the edit operation. */ public interface ExitListener { void exit(boolean accept); } public static class ExitFlags { public int flags; public boolean doit; public ExitFlags(int flags, boolean doit) { this.flags= flags; this.doit= doit; } } public interface ExitPolicy { ExitFlags doExit(LinkedPositionManager manager, VerifyEvent event, int offset, int length); } // leave flags private static final int UNINSTALL= 1; // uninstall linked position manager public static final int COMMIT= 2; // commit changes private static final int DOCUMENT_CHANGED= 4; // document has changed public static final int UPDATE_CARET= 8; // update caret private static final IPreferenceStore fgStore= JavaPlugin.getDefault().getPreferenceStore(); private static final String CARET_POSITION_PREFIX= "LinkedPositionUI.caret.position"; //$NON-NLS-1$ private static int fgCounter= 0; private final ITextViewer fViewer; private final LinkedPositionManager fManager; private final IPositionUpdater fUpdater; private final String fPositionCategoryName; private Color fFrameColor; private int fFinalCaretOffset= -1; // no final caret offset private Position fFinalCaretPosition; private Position fFramePosition; private int fInitialOffset= -1; private int fCaretOffset; private ExitPolicy fExitPolicy; private ExitListener fExitListener; private boolean fNeedRedraw; private String fContentType; private Position fPreviousPosition; private ContentAssistant2 fAssistant; /** * Creates a user interface for <code>LinkedPositionManager</code>. * * @param viewer the text viewer. * @param manager the <code>LinkedPositionManager</code> managing a <code>IDocument</code> of the <code>ITextViewer</code>. */ public LinkedPositionUI(ITextViewer viewer, LinkedPositionManager manager) { Assert.isNotNull(viewer); Assert.isNotNull(manager); fViewer= viewer; fManager= manager; fPositionCategoryName= CARET_POSITION_PREFIX + (fgCounter++); fUpdater= new DefaultPositionUpdater(fPositionCategoryName); fManager.setLinkedPositionListener(this); initializeHighlightColor(viewer); } /* * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent) */ public void propertyChange(PropertyChangeEvent event) { if (event.getProperty().equals(PreferenceConstants.EDITOR_LINKED_POSITION_COLOR)) { initializeHighlightColor(fViewer); redrawRegion(); } } private void initializeHighlightColor(ITextViewer viewer) { if (fFrameColor != null) fFrameColor.dispose(); StyledText text= viewer.getTextWidget(); if (text != null) { Display display= text.getDisplay(); fFrameColor= createColor(fgStore, PreferenceConstants.EDITOR_LINKED_POSITION_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; } /** * Sets the initial offset. * @param offset */ public void setInitialOffset(int offset) { fInitialOffset= offset; } /** * Sets the final position of the caret when the linked mode is exited * successfully by leaving the last linked position using TAB. * The set position will be a TAB stop as well as the positions configured in the * <code>LinkedPositionManager</code>. */ public void setFinalCaretOffset(int offset) { fFinalCaretOffset= offset; } /** * Sets a <code>CancelListener</code> which is notified if the linked mode * is exited unsuccessfully by hitting ESC. */ public void setCancelListener(ExitListener listener) { fExitListener= listener; } /** * Sets an <code>ExitPolicy</code> which decides when and how * the linked mode is exited. */ public void setExitPolicy(ExitPolicy policy) { fExitPolicy= policy; } /* * @see LinkedPositionManager.LinkedPositionListener#setCurrentPositions(Position, int) */ public void setCurrentPosition(Position position, int caretOffset) { if (!fFramePosition.equals(position)) { fNeedRedraw= true; fFramePosition= position; } fCaretOffset= caretOffset; } /** * Enters the linked mode. The linked mode can be left by calling * <code>exit</code>. * * @see #exit(boolean) */ public void enter() { // track final caret IDocument document= fViewer.getDocument(); document.addPositionCategory(fPositionCategoryName); document.addPositionUpdater(fUpdater); try { if (fFinalCaretOffset != -1) { fFinalCaretPosition= new Position(fFinalCaretOffset); document.addPosition(fPositionCategoryName, fFinalCaretPosition); } } catch (BadLocationException e) { handleException(fViewer.getTextWidget().getShell(), e); } catch (BadPositionCategoryException e) { JavaPlugin.log(e); Assert.isTrue(false); } fViewer.addTextInputListener(this); fViewer.addTextListener(this); ITextViewerExtension extension= (ITextViewerExtension) fViewer; extension.prependVerifyKeyListener(this); StyledText text= fViewer.getTextWidget(); text.addVerifyListener(this); text.addModifyListener(this); text.addPaintListener(this); text.showSelection(); Shell shell= text.getShell(); shell.addShellListener(this); fFramePosition= (fInitialOffset == -1) ? fManager.getFirstPosition() : fManager.getPosition(fInitialOffset); if (fFramePosition == null) { leave(UNINSTALL | COMMIT | UPDATE_CARET); return; } fgStore.addPropertyChangeListener(this); try { fContentType= TextUtilities.getContentType(document, IJavaPartitions.JAVA_PARTITIONING, fFramePosition.offset); if (fViewer instanceof ITextViewerExtension2) { ((ITextViewerExtension2) fViewer).prependAutoEditStrategy(fManager, fContentType); } else { Assert.isTrue(false); } } catch (BadLocationException e) { handleException(fViewer.getTextWidget().getShell(), e); } selectRegion(); triggerContentAssist(); } /* * @see LinkedPositionManager.LinkedPositionListener#exit(boolean) */ public void exit(boolean success) { // no UNINSTALL since manager has already uninstalled itself leave((success ? COMMIT : 0) | UPDATE_CARET); } /** * Returns the cursor selection, after having entered the linked mode. * <code>enter()</code> must be called prior to a call to this method. */ public IRegion getSelectedRegion() { if (fFramePosition == null) return new Region(fFinalCaretOffset, 0); else return new Region(fFramePosition.getOffset(), fFramePosition.getLength()); } private void leave(int flags) { fInitialOffset= -1; if ((flags & UNINSTALL) != 0) fManager.uninstall((flags & COMMIT) != 0); fgStore.removePropertyChangeListener(this); if (fFrameColor != null) { fFrameColor.dispose(); fFrameColor= null; } StyledText text= fViewer.getTextWidget(); text.removePaintListener(this); text.removeModifyListener(this); text.removeVerifyListener(this); Shell shell= text.getShell(); shell.removeShellListener(this); if (fAssistant != null) { Display display= text.getDisplay(); if (display != null && !display.isDisposed()) { display.asyncExec(new Runnable() { public void run() { if (fAssistant != null) { fAssistant.uninstall(); fAssistant= null; } } }); } } ITextViewerExtension extension= (ITextViewerExtension) fViewer; extension.removeVerifyKeyListener(this); IRewriteTarget target= extension.getRewriteTarget(); target.endCompoundChange(); if (fViewer instanceof ITextViewerExtension2 && fContentType != null) ((ITextViewerExtension2) fViewer).removeAutoEditStrategy(fManager, fContentType); fContentType= null; fViewer.removeTextListener(this); fViewer.removeTextInputListener(this); try { IDocument document= fViewer.getDocument(); if (((flags & COMMIT) != 0) && ((flags & DOCUMENT_CHANGED) == 0) && ((flags & UPDATE_CARET) != 0)) { Position[] positions= document.getPositions(fPositionCategoryName); if ((positions != null) && (positions.length != 0)) { if (fViewer instanceof ITextViewerExtension3) { ITextViewerExtension3 extension3= (ITextViewerExtension3) fViewer; int widgetOffset= extension3.modelOffset2WidgetOffset(positions[0].getOffset()); if (widgetOffset >= 0) text.setSelection(widgetOffset, widgetOffset); } else { IRegion region= fViewer.getVisibleRegion(); int offset= positions[0].getOffset() - region.getOffset(); if ((offset >= 0) && (offset <= region.getLength())) text.setSelection(offset, offset); } } } document.removePositionUpdater(fUpdater); document.removePositionCategory(fPositionCategoryName); if (fExitListener != null) fExitListener.exit( ((flags & COMMIT) != 0) || ((flags & DOCUMENT_CHANGED) != 0)); } catch (BadPositionCategoryException e) { JavaPlugin.log(e); Assert.isTrue(false); } if ((flags & DOCUMENT_CHANGED) == 0) text.redraw(); } private void next() { redrawRegion(); if (fFramePosition == fFinalCaretPosition) fFramePosition= fManager.getFirstPosition(); else fFramePosition= fManager.getNextPosition(fFramePosition.getOffset()); if (fFramePosition == null) { if (fFinalCaretPosition != null) fFramePosition= fFinalCaretPosition; else fFramePosition= fManager.getFirstPosition(); } if (fFramePosition == null) { leave(UNINSTALL | COMMIT | UPDATE_CARET); } else { selectRegion(); triggerContentAssist(); redrawRegion(); } } private void previous() { redrawRegion(); fFramePosition= fManager.getPreviousPosition(fFramePosition.getOffset()); if (fFramePosition == null) { if (fFinalCaretPosition != null) fFramePosition= fFinalCaretPosition; else fFramePosition= fManager.getLastPosition(); } if (fFramePosition == null) { leave(UNINSTALL | COMMIT | UPDATE_CARET); } else { selectRegion(); triggerContentAssist(); redrawRegion(); } } /** Trigger content assist on choice positions */ private void triggerContentAssist() { if (fFramePosition instanceof ProposalPosition) { ProposalPosition pp= (ProposalPosition) fFramePosition; initializeContentAssistant(); if (fAssistant == null) return; fAssistant.setCompletions(pp.getChoices()); fAssistant.showPossibleCompletions(); } else { if (fAssistant != null) fAssistant.setCompletions(new ICompletionProposal[0]); } } /** Lazy initialize content assistant for this linked ui */ private void initializeContentAssistant() { if (fAssistant != null) return; fAssistant= new ContentAssistant2(); fAssistant.setDocumentPartitioning(IJavaPartitions.JAVA_PARTITIONING); fAssistant.install(fViewer); } /* * @see VerifyKeyListener#verifyKey(VerifyEvent) */ public void verifyKey(VerifyEvent event) { if (!event.doit) return; Point selection= fViewer.getSelectedRange(); int offset= selection.x; int length= selection.y; ExitFlags exitFlags= fExitPolicy == null ? null : fExitPolicy.doExit(fManager, event, offset, length); if (exitFlags != null) { leave(UNINSTALL | exitFlags.flags); event.doit= exitFlags.doit; return; } switch (event.character) { // [SHIFT-]TAB = hop between edit boxes case 0x09: { // if tab was treated as a document change, would it exceed variable range? if (!LinkedPositionManager.includes(fFramePosition, offset, length)) { leave(UNINSTALL | COMMIT); return; } } if (event.stateMask == SWT.SHIFT) previous(); else next(); event.doit= false; break; // ENTER case 0x0A: // Ctrl+Enter case 0x0D: { if (fAssistant != null && fAssistant.wasProposalChosen()) { next(); event.doit= false; break; } // if enter was treated as a document change, would it exceed variable range? if (!LinkedPositionManager.includes(fFramePosition, offset, length) || (fFramePosition == fFinalCaretPosition)) { leave(UNINSTALL | COMMIT); return; } } leave(UNINSTALL | COMMIT | UPDATE_CARET); event.doit= false; break; // ESC case 0x1B: leave(UNINSTALL | COMMIT); event.doit= false; break; case ';': leave(UNINSTALL | COMMIT); event.doit= true; break; default: if (event.character != 0) { if (!controlUndoBehavior(offset, length) || fFramePosition == fFinalCaretPosition) { leave(UNINSTALL | COMMIT); break; } } } } private boolean controlUndoBehavior(int offset, int length) { Position position= fManager.getEmbracingPosition(offset, length); if (position != null) { ITextViewerExtension extension= (ITextViewerExtension) fViewer; IRewriteTarget target= extension.getRewriteTarget(); if (fPreviousPosition != null && !fPreviousPosition.equals(position)) target.endCompoundChange(); target.beginCompoundChange(); } fPreviousPosition= position; return fPreviousPosition != null; } /* * @see VerifyListener#verifyText(VerifyEvent) */ public void verifyText(VerifyEvent event) { if (!event.doit) return; int offset= 0; int length= 0; if (fViewer instanceof ITextViewerExtension3) { ITextViewerExtension3 extension= (ITextViewerExtension3) fViewer; IRegion modelRange= extension.widgetRange2ModelRange(new Region(event.start, event.end - event.start)); if (modelRange == null) return; offset= modelRange.getOffset(); length= modelRange.getLength(); } else { IRegion visibleRegion= fViewer.getVisibleRegion(); offset= event.start + visibleRegion.getOffset(); length= event.end - event.start; } // allow changes only within linked positions when coming through UI if (!fManager.anyPositionIncludes(offset, length)) leave(UNINSTALL | COMMIT); } /* * @see PaintListener#paintControl(PaintEvent) */ public void paintControl(PaintEvent event) { if (fFramePosition == null) return; IRegion widgetRange= asWidgetRange(fFramePosition); if (widgetRange == null) { leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED); return; } int offset= widgetRange.getOffset(); int length= widgetRange.getLength(); StyledText text= fViewer.getTextWidget(); // 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; gc.setForeground(fFrameColor); gc.drawLine(x1, y, x2, y); } protected IRegion asWidgetRange(Position position) { if (fViewer instanceof ITextViewerExtension3) { ITextViewerExtension3 extension= (ITextViewerExtension3) fViewer; return extension.modelRange2WidgetRange(new Region(position.getOffset(), position.getLength())); } else { IRegion region= fViewer.getVisibleRegion(); if (includes(region, position)) return new Region(position.getOffset() - region.getOffset(), position.getLength()); } return null; } private static 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 static Point getMaximumLocation(StyledText text, int offset, int length) { Point maxLocation= new Point(Integer.MIN_VALUE, Integer.MIN_VALUE); for (int i= 0; i <= length; i++) { Point location= text.getLocationAtOffset(offset + i); if (location.x > maxLocation.x) maxLocation.x= location.x; if (location.y > maxLocation.y) maxLocation.y= location.y; } return maxLocation; } private void redrawRegion() { IRegion widgetRange= asWidgetRange(fFramePosition); if (widgetRange == null) { leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED); return; } StyledText text= fViewer.getTextWidget(); if (text != null && !text.isDisposed()) text.redrawRange(widgetRange.getOffset(), widgetRange.getLength(), true); } private void selectRegion() { IRegion widgetRange= asWidgetRange(fFramePosition); if (widgetRange == null) { leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED); return; } StyledText text= fViewer.getTextWidget(); if (text != null && !text.isDisposed()) { int start= widgetRange.getOffset(); int end= widgetRange.getLength() + start; text.setSelection(start, end); } } private void updateCaret() { IRegion widgetRange= asWidgetRange(fFramePosition); if (widgetRange == null) { leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED); return; } int offset= widgetRange.getOffset() + fCaretOffset; StyledText text= fViewer.getTextWidget(); if (text != null && !text.isDisposed()) text.setCaretOffset(offset); } /* * @see ModifyListener#modifyText(ModifyEvent) */ public void modifyText(ModifyEvent e) { // reposition caret after StyledText redrawRegion(); updateCaret(); } private static void handleException(Shell shell, Exception e) { String title= LinkedPositionMessages.getString("LinkedPositionUI.error.title"); //$NON-NLS-1$ if (e instanceof CoreException) ExceptionHandler.handle((CoreException)e, shell, title, null); else if (e instanceof InvocationTargetException) ExceptionHandler.handle((InvocationTargetException)e, shell, title, null); else { MessageDialog.openError(shell, title, e.getMessage()); JavaPlugin.log(e); } } /* * @see ITextInputListener#inputDocumentAboutToBeChanged(IDocument, IDocument) */ public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) { // 5326: leave linked mode on document change int flags= UNINSTALL | COMMIT | (oldInput.equals(newInput) ? 0 : DOCUMENT_CHANGED); leave(flags); } /* * @see ITextInputListener#inputDocumentChanged(IDocument, IDocument) */ public void inputDocumentChanged(IDocument oldInput, IDocument newInput) { } private static boolean includes(IRegion region, Position position) { return position.getOffset() >= region.getOffset() && position.getOffset() + position.getLength() <= region.getOffset() + region.getLength(); } /* * @see org.eclipse.jface.text.ITextListener#textChanged(TextEvent) */ public void textChanged(TextEvent event) { if (!fNeedRedraw) return; redrawRegion(); fNeedRedraw= false; } /* * @see org.eclipse.swt.events.ShellListener#shellActivated(org.eclipse.swt.events.ShellEvent) */ public void shellActivated(ShellEvent event) { } /* * @see org.eclipse.swt.events.ShellListener#shellClosed(org.eclipse.swt.events.ShellEvent) */ public void shellClosed(ShellEvent event) { leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED); } /* * @see org.eclipse.swt.events.ShellListener#shellDeactivated(org.eclipse.swt.events.ShellEvent) */ public void shellDeactivated(ShellEvent event) { // don't deactivate on focus lost, since the proposal popups may take focus // plus: it doesn't hurt if you can check with another window without losing linked mode // since there is no intrusive popup sticking out. // need to check first what happens on reentering based on an open action // Seems to be no problem // TODO check whether we can leave it or uncomment it after debugging // PS: why DOCUMENT_CHANGED? We want to trigger a redraw! (Shell deactivated does not mean // it is not visible any longer. // leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED); // Better: // Check with content assistant and only leave if its not the proposal shell that took the // focus away. StyledText text; Display display; if (fAssistant == null || fViewer == null || (text= fViewer.getTextWidget()) == null || (display= text.getDisplay()) == null || display.isDisposed()) { leave(UNINSTALL | COMMIT); } else { // Post in UI thread since the assistant popup will only get the focus after we lose it. display.asyncExec(new Runnable() { public void run() { // TODO add isDisposed / isUninstalled / hasLeft check? for now: check for content type, // since it gets nullified in leave() if (fAssistant == null || !fAssistant.hasFocus() || fContentType == null) { leave(UNINSTALL | COMMIT); } } }); } } /* * @see org.eclipse.swt.events.ShellListener#shellDeiconified(org.eclipse.swt.events.ShellEvent) */ public void shellDeiconified(ShellEvent event) { } /* * @see org.eclipse.swt.events.ShellListener#shellIconified(org.eclipse.swt.events.ShellEvent) */ public void shellIconified(ShellEvent event) { leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED); } }
43,488
Bug 43488 [typing] BadPositionCategoryException in LinkedPositionManager
null
resolved fixed
f33a208
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-24T10:54:42Z
2003-09-23T09: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.IStatus; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Preferences; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.BidiSegmentEvent; import org.eclipse.swt.custom.BidiSegmentListener; import org.eclipse.swt.custom.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.Shell; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.GroupMarker; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IStatusLineManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferenceConverter; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.IPostSelectionProvider; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.DefaultInformationControl; import org.eclipse.jface.text.DocumentEvent; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocumentListener; import org.eclipse.jface.text.IInformationControl; import org.eclipse.jface.text.IInformationControlCreator; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextHover; import org.eclipse.jface.text.ITextInputListener; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.ITextViewerExtension2; import org.eclipse.jface.text.ITextViewerExtension3; import org.eclipse.jface.text.ITextViewerExtension4; import org.eclipse.jface.text.ITypedRegion; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.Region; import org.eclipse.jface.text.TextSelection; import org.eclipse.jface.text.TextUtilities; import org.eclipse.jface.text.information.IInformationProvider; import org.eclipse.jface.text.information.IInformationProviderExtension2; import org.eclipse.jface.text.information.InformationPresenter; import org.eclipse.jface.text.source.Annotation; import org.eclipse.jface.text.source.IAnnotationAccess; import org.eclipse.jface.text.source.IAnnotationModel; import org.eclipse.jface.text.source.IOverviewRuler; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.jface.text.source.IVerticalRuler; import org.eclipse.jface.text.source.LineChangeHover; import org.eclipse.jface.text.source.SourceViewerConfiguration; import org.eclipse.ui.IEditorActionBarContributor; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IPageLayout; import org.eclipse.ui.IPartService; import org.eclipse.ui.IViewPart; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.actions.ActionContext; import org.eclipse.ui.actions.ActionGroup; import org.eclipse.ui.editors.text.DefaultEncodingSupport; import org.eclipse.ui.editors.text.IEncodingSupport; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.part.EditorActionBarContributor; import org.eclipse.ui.part.IShowInTargetList; import org.eclipse.ui.texteditor.AddTaskAction; import org.eclipse.ui.texteditor.AnnotationPreference; import org.eclipse.ui.texteditor.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; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICodeAssist; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IImportContainer; import org.eclipse.jdt.core.IImportDeclaration; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IPackageDeclaration; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.ISourceReference; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.IContextMenuConstants; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.actions.IJavaEditorActionDefinitionIds; import org.eclipse.jdt.ui.actions.JavaSearchActionGroup; import org.eclipse.jdt.ui.actions.OpenEditorActionGroup; import org.eclipse.jdt.ui.actions.OpenViewActionGroup; import org.eclipse.jdt.ui.actions.ShowActionGroup; import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration; import org.eclipse.jdt.ui.text.JavaTextTools; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup; import org.eclipse.jdt.internal.ui.actions.SelectionConverter; import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.GoToNextPreviousMemberAction; import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.SelectionHistory; import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectEnclosingAction; import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectHistoryAction; import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectNextAction; import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectPreviousAction; import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectionAction; import org.eclipse.jdt.internal.ui.text.HTMLTextPresenter; import org.eclipse.jdt.internal.ui.text.IJavaPartitions; import org.eclipse.jdt.internal.ui.text.JavaChangeHover; import org.eclipse.jdt.internal.ui.text.JavaPairMatcher; import org.eclipse.jdt.internal.ui.util.JavaUIHelp; import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider; /** * Java specific text editor. */ public abstract class JavaEditor extends ExtendedTextEditor implements IViewPartInputProvider { /** * Internal implementation class for a change listener. * @since 3.0 */ protected abstract class AbstractSelectionChangedListener implements ISelectionChangedListener { /** * Installs this selection changed listener with the given selection provider. If * the selection provider is a post selection provider, post selection changed * events are the preferred choice, otherwise normal selection changed events * are requested. * * @param selectionProvider */ public void install(ISelectionProvider selectionProvider) { if (selectionProvider == null) return; if (selectionProvider instanceof IPostSelectionProvider) { IPostSelectionProvider provider= (IPostSelectionProvider) selectionProvider; provider.addPostSelectionChangedListener(this); } else { selectionProvider.addSelectionChangedListener(this); } } /** * Removes this selection changed listener from the given selection provider. * * @param selectionProvider */ public void uninstall(ISelectionProvider selectionProvider) { if (selectionProvider == null) return; if (selectionProvider instanceof IPostSelectionProvider) { IPostSelectionProvider provider= (IPostSelectionProvider) selectionProvider; provider.removePostSelectionChangedListener(this); } else { selectionProvider.removeSelectionChangedListener(this); } } } /** * Updates the Java outline page selection and this editor's range indicator. * * @since 3.0 */ private class EditorSelectionChangedListener extends AbstractSelectionChangedListener { /* * @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent) */ public void selectionChanged(SelectionChangedEvent event) { selectionChanged(); } public void selectionChanged() { ISourceReference element= computeHighlightRangeSourceReference(); synchronizeOutlinePage(element); setSelection(element, false); } } /** * Updates the selection in the editor's widget with the selection of the outline page. */ class OutlineSelectionChangedListener extends AbstractSelectionChangedListener { public void selectionChanged(SelectionChangedEvent event) { doSelectionChanged(event); } } /* * Link mode. */ class MouseClickListener implements KeyListener, MouseListener, MouseMoveListener, FocusListener, PaintListener, IPropertyChangeListener, IDocumentListener, ITextInputListener { /** The session is active. */ private boolean fActive; /** The currently active style range. */ private IRegion fActiveRegion; /** The currently active style range as position. */ private Position fRememberedPosition; /** The hand cursor. */ private Cursor fCursor; /** The link color. */ private Color fColor; /** The key modifier mask. */ private int fKeyModifierMask; public void deactivate() { deactivate(false); } public void deactivate(boolean redrawAll) { if (!fActive) return; repairRepresentation(redrawAll); fActive= false; } public void install() { ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer == null) return; StyledText text= sourceViewer.getTextWidget(); if (text == null || text.isDisposed()) return; updateColor(sourceViewer); sourceViewer.addTextInputListener(this); IDocument document= sourceViewer.getDocument(); if (document != null) document.addDocumentListener(this); text.addKeyListener(this); text.addMouseListener(this); text.addMouseMoveListener(this); text.addFocusListener(this); text.addPaintListener(this); updateKeyModifierMask(); IPreferenceStore preferenceStore= getPreferenceStore(); preferenceStore.addPropertyChangeListener(this); } private void updateKeyModifierMask() { String modifiers= getPreferenceStore().getString(BROWSER_LIKE_LINKS_KEY_MODIFIER); fKeyModifierMask= computeStateMask(modifiers); if (fKeyModifierMask == -1) { // Fallback to stored state mask fKeyModifierMask= getPreferenceStore().getInt(BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK); } } private int computeStateMask(String modifiers) { if (modifiers == null) return -1; if (modifiers.length() == 0) return SWT.NONE; int stateMask= 0; StringTokenizer modifierTokenizer= new StringTokenizer(modifiers, ",;.:+-* "); //$NON-NLS-1$ while (modifierTokenizer.hasMoreTokens()) { int modifier= EditorUtility.findLocalizedModifier(modifierTokenizer.nextToken()); if (modifier == 0 || (stateMask & modifier) == modifier) return -1; stateMask= stateMask | modifier; } return stateMask; } public void uninstall() { if (fColor != null) { fColor.dispose(); fColor= null; } if (fCursor != null) { fCursor.dispose(); fCursor= null; } ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer == null) return; sourceViewer.removeTextInputListener(this); IDocument document= sourceViewer.getDocument(); if (document != null) document.removeDocumentListener(this); IPreferenceStore preferenceStore= getPreferenceStore(); if (preferenceStore != null) preferenceStore.removePropertyChangeListener(this); StyledText text= sourceViewer.getTextWidget(); if (text == null || text.isDisposed()) return; text.removeKeyListener(this); text.removeMouseListener(this); text.removeMouseMoveListener(this); text.removeFocusListener(this); text.removePaintListener(this); } /* * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent) */ public void propertyChange(PropertyChangeEvent event) { if (event.getProperty().equals(JavaEditor.LINK_COLOR)) { ISourceViewer viewer= getSourceViewer(); if (viewer != null) updateColor(viewer); } else if (event.getProperty().equals(BROWSER_LIKE_LINKS_KEY_MODIFIER)) { updateKeyModifierMask(); } } private void updateColor(ISourceViewer viewer) { if (fColor != null) fColor.dispose(); StyledText text= viewer.getTextWidget(); if (text == null || text.isDisposed()) return; Display display= text.getDisplay(); fColor= createColor(getPreferenceStore(), JavaEditor.LINK_COLOR, display); } /** * Creates a color from the information stored in the given preference store. * Returns <code>null</code> if there is no such information available. */ private Color createColor(IPreferenceStore store, String key, Display display) { RGB rgb= null; if (store.contains(key)) { if (store.isDefault(key)) rgb= PreferenceConverter.getDefaultColor(store, key); else rgb= PreferenceConverter.getColor(store, key); if (rgb != null) return new Color(display, rgb); } return null; } private void repairRepresentation() { repairRepresentation(false); } private void repairRepresentation(boolean redrawAll) { if (fActiveRegion == null) return; int offset= fActiveRegion.getOffset(); int length= fActiveRegion.getLength(); fActiveRegion= null; ISourceViewer viewer= getSourceViewer(); if (viewer != null) { resetCursor(viewer); // 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); } } } // 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) { if (!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(); } }); } } } else { fActiveRegion= null; fRememberedPosition= null; 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); fireSelectionChanged(); 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) { getTextWidget().setCaretOffset(modelOffset2WidgetOffset(getSourceViewer(), 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); } } } /** * 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); while (position >= 0 && Character.isUpperCase(character)) character= document.getChar(--position); setCaretPosition(position + 1); fireSelectionChanged(); 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) { getTextWidget().setCaretOffset(modelOffset2WidgetOffset(getSourceViewer(), 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); } } } /** * Quick format action to format the enclosing java element. * <p> * The quick format action works as follows: * <ul> * <li>If there is no selection and the caret is positioned on a Java element, * only this element is formatted. If the element has some accompanying comment, * then the comment is formatted as well.</li> * <li>If the selection spans one or more partitions of the document, then all * partitions covered by the selection are entirely formatted.</li> * <p> * Partitions at the end of the selection are not completed, except for comments. * * @since 3.0 */ protected class QuickFormatAction extends Action { /* * @see org.eclipse.jface.action.IAction#run() */ public void run() { final JavaSourceViewer viewer= (JavaSourceViewer) getSourceViewer(); if (viewer.isEditable()) { final Point selection= viewer.rememberSelection(); try { final String type= TextUtilities.getContentType(viewer.getDocument(), IJavaPartitions.JAVA_PARTITIONING, selection.x); if (type.equals(IDocument.DEFAULT_CONTENT_TYPE) && selection.y == 0) { try { final IJavaElement element= getElementAt(selection.x, true); if (element != null && element.exists()) { final int kind= element.getElementType(); if (kind == IJavaElement.TYPE || kind == IJavaElement.METHOD || kind == IJavaElement.INITIALIZER) { final ISourceReference reference= (ISourceReference)element; final ISourceRange range= reference.getSourceRange(); if (range != null) { viewer.setSelectedRange(range.getOffset(), range.getLength()); viewer.doOperation(ISourceViewer.FORMAT); } } } } catch (JavaModelException exception) { // Should not happen } } else { viewer.setSelectedRange(selection.x, 1); viewer.doOperation(ISourceViewer.FORMAT); } } catch (BadLocationException exception) { // Can not happen } finally { viewer.restoreSelection(); } } } } /** 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); /** This editor's encoding support */ private DefaultEncodingSupport fEncodingSupport; /** 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 (IEncodingSupport.class.equals(required)) return fEncodingSupport; if (required == IShowInTargetList.class) { return new IShowInTargetList() { public String[] getShowInTargetIds() { return new String[] { JavaUI.ID_PACKAGES, IPageLayout.ID_OUTLINE, IPageLayout.ID_RES_NAV }; } }; } return super.getAdapter(required); } protected void setSelection(ISourceReference reference, boolean moveCursor) { ISelection selection= getSelectionProvider().getSelection(); if (selection instanceof TextSelection) { TextSelection textSelection= (TextSelection) selection; // 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 StatusTextEditor#getStatusHeader(IStatus) */ protected String getStatusHeader(IStatus status) { if (fEncodingSupport != null) { String message= fEncodingSupport.getStatusHeader(status); if (message != null) return message; } return super.getStatusHeader(status); } /* * @see StatusTextEditor#getStatusBanner(IStatus) */ protected String getStatusBanner(IStatus status) { if (fEncodingSupport != null) { String message= fEncodingSupport.getStatusBanner(status); if (message != null) return message; } return super.getStatusBanner(status); } /* * @see StatusTextEditor#getStatusMessage(IStatus) */ protected String getStatusMessage(IStatus status) { if (fEncodingSupport != null) { String message= fEncodingSupport.getStatusMessage(status); if (message != null) return message; } return super.getStatusMessage(status); } /* * @see AbstractTextEditor#doSetInput */ protected void doSetInput(IEditorInput input) throws CoreException { super.doSetInput(input); if (fEncodingSupport != null) fEncodingSupport.reset(); setOutlinePageInput(fOutlinePage, input); } /* * @see IWorkbenchPart#dispose() */ public void dispose() { if (isBrowserLikeLinks()) disableBrowserLikeLinks(); if (fEncodingSupport != null) { fEncodingSupport.dispose(); fEncodingSupport= null; } if (fPropertyChangeListener != null) { Preferences preferences= JavaCore.getPlugin().getPluginPreferences(); preferences.removePropertyChangeListener(fPropertyChangeListener); fPropertyChangeListener= null; } if (fBracketMatcher != null) { fBracketMatcher.dispose(); fBracketMatcher= null; } if (fSelectionHistory != null) { fSelectionHistory.dispose(); fSelectionHistory= null; } if (fEditorSelectionChangedListener != null) { fEditorSelectionChangedListener.uninstall(getSelectionProvider()); fEditorSelectionChangedListener= null; } super.dispose(); } protected void createActions() { super.createActions(); ResourceAction resAction= new AddTaskAction(JavaEditorMessages.getResourceBundle(), "AddTask.", this); //$NON-NLS-1$ resAction.setHelpContextId(IAbstractTextEditorHelpContextIds.ADD_TASK_ACTION); resAction.setActionDefinitionId(ITextEditorActionDefinitionIds.ADD_TASK); setAction(ITextEditorActionConstants.ADD_TASK, resAction); ActionGroup oeg, ovg, jsg, sg; fActionGroups= new CompositeActionGroup(new ActionGroup[] { oeg= new OpenEditorActionGroup(this), sg= new ShowActionGroup(this), ovg= new OpenViewActionGroup(this), jsg= new JavaSearchActionGroup(this) }); fContextMenuGroup= new CompositeActionGroup(new ActionGroup[] {oeg, ovg, sg, jsg}); resAction= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc.", this, ISourceViewer.INFORMATION, true); //$NON-NLS-1$ resAction= new InformationDispatchAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc.", (TextOperationAction) resAction); //$NON-NLS-1$ resAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_JAVADOC); setAction("ShowJavaDoc", resAction); //$NON-NLS-1$ WorkbenchHelp.setHelp(resAction, IJavaHelpContextIds.SHOW_JAVADOC_ACTION); Action action= new GotoMatchingBracketAction(this); action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_MATCHING_BRACKET); setAction(GotoMatchingBracketAction.GOTO_MATCHING_BRACKET, action); action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"ShowOutline.", this, JavaSourceViewer.SHOW_OUTLINE, true); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_OUTLINE); setAction(IJavaEditorActionDefinitionIds.SHOW_OUTLINE, action); WorkbenchHelp.setHelp(action, IJavaHelpContextIds.SHOW_OUTLINE_ACTION); action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"OpenStructure.", this, JavaSourceViewer.OPEN_STRUCTURE, true); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_STRUCTURE); setAction(IJavaEditorActionDefinitionIds.OPEN_STRUCTURE, action); WorkbenchHelp.setHelp(action, IJavaHelpContextIds.OPEN_STRUCTURE_ACTION); action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"OpenHierarchy.", this, JavaSourceViewer.SHOW_HIERARCHY, true); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_HIERARCHY); setAction(IJavaEditorActionDefinitionIds.OPEN_HIERARCHY, action); WorkbenchHelp.setHelp(action, IJavaHelpContextIds.OPEN_HIERARCHY_ACTION); fEncodingSupport= new DefaultEncodingSupport(); fEncodingSupport.initialize(this); fSelectionHistory= new SelectionHistory(this); action= new StructureSelectEnclosingAction(this, fSelectionHistory); action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_ENCLOSING); setAction(StructureSelectionAction.ENCLOSING, action); action= new StructureSelectNextAction(this, fSelectionHistory); action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_NEXT); setAction(StructureSelectionAction.NEXT, action); action= new StructureSelectPreviousAction(this, fSelectionHistory); action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_PREVIOUS); setAction(StructureSelectionAction.PREVIOUS, action); StructureSelectHistoryAction historyAction= new StructureSelectHistoryAction(this, fSelectionHistory); historyAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_LAST); setAction(StructureSelectionAction.HISTORY, historyAction); fSelectionHistory.setHistoryAction(historyAction); action= GoToNextPreviousMemberAction.newGoToNextMemberAction(this); action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_NEXT_MEMBER); setAction(GoToNextPreviousMemberAction.NEXT_MEMBER, action); action= GoToNextPreviousMemberAction.newGoToPreviousMemberAction(this); action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_PREVIOUS_MEMBER); setAction(GoToNextPreviousMemberAction.PREVIOUS_MEMBER, action); action= new QuickFormatAction(); action.setActionDefinitionId(IJavaEditorActionDefinitionIds.QUICK_FORMAT); setAction(IJavaEditorActionDefinitionIds.QUICK_FORMAT, 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; } /* * @see org.eclipse.ui.texteditor.AbstractTextEditor#updatePropertyDependentActions() */ protected void updatePropertyDependentActions() { super.updatePropertyDependentActions(); if (fEncodingSupport != null) fEncodingSupport.reset(); } /* * Update the hovering behavior depending on the preferences. */ private void updateHoverBehavior() { SourceViewerConfiguration configuration= getSourceViewerConfiguration(); String[] types= configuration.getConfiguredContentTypes(getSourceViewer()); for (int i= 0; i < types.length; i++) { String t= types[i]; ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer instanceof ITextViewerExtension2) { // Remove existing hovers ((ITextViewerExtension2)sourceViewer).removeTextHovers(t); int[] stateMasks= configuration.getConfiguredTextHoverStateMasks(getSourceViewer(), t); if (stateMasks != null) { for (int j= 0; j < stateMasks.length; j++) { int stateMask= stateMasks[j]; ITextHover textHover= configuration.getTextHover(sourceViewer, t, stateMask); ((ITextViewerExtension2)sourceViewer).setTextHover(textHover, t, stateMask); } } else { ITextHover textHover= configuration.getTextHover(sourceViewer, t); ((ITextViewerExtension2)sourceViewer).setTextHover(textHover, t, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK); } } else sourceViewer.setTextHover(configuration.getTextHover(sourceViewer, t), t); } } /* * @see org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput() */ public Object getViewPartInput() { return getEditorInput().getAdapter(IJavaElement.class); } /* * @see org.eclipse.ui.texteditor.AbstractTextEditor#doSetSelection(ISelection) */ protected void doSetSelection(ISelection selection) { super.doSetSelection(selection); synchronizeOutlinePageSelection(); } /* * @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite) */ public void createPartControl(Composite parent) { super.createPartControl(parent); 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); } }
43,488
Bug 43488 [typing] BadPositionCategoryException in LinkedPositionManager
null
resolved fixed
f33a208
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-24T10:54:42Z
2003-09-23T09:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/link/contentassist/ContentAssistant2.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.contentassist; import java.util.HashMap; import java.util.Map; import org.eclipse.swt.SWT; import org.eclipse.swt.SWTError; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.custom.VerifyKeyListener; import org.eclipse.swt.events.ControlEvent; import org.eclipse.swt.events.ControlListener; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseListener; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Widget; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferenceConverter; import org.eclipse.jface.text.Assert; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.DefaultInformationControl; import org.eclipse.jface.text.IEventConsumer; import org.eclipse.jface.text.IInformationControl; import org.eclipse.jface.text.IInformationControlCreator; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.ITextViewerExtension; import org.eclipse.jface.text.IViewportListener; import org.eclipse.jface.text.IWidgetTokenKeeper; import org.eclipse.jface.text.IWidgetTokenKeeperExtension; import org.eclipse.jface.text.IWidgetTokenOwner; import org.eclipse.jface.text.IWidgetTokenOwnerExtension; import org.eclipse.jface.text.TextUtilities; import org.eclipse.jface.text.contentassist.CompletionProposal; import org.eclipse.jface.text.contentassist.ICompletionProposal; import org.eclipse.jface.text.contentassist.IContentAssistProcessor; import org.eclipse.jface.text.contentassist.IContentAssistant; import org.eclipse.jface.text.contentassist.IContentAssistantExtension; import org.eclipse.jface.text.contentassist.IContextInformation; import org.eclipse.jface.text.contentassist.IContextInformationPresenter; import org.eclipse.jface.text.contentassist.IContextInformationValidator; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.text.IColorManager; import org.eclipse.jdt.ui.text.JavaTextTools; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.text.HTMLTextPresenter; /** * The standard implementation of the <code>IContentAssistant</code> interface. * Usually, clients instantiate this class and configure it before using it. */ public class ContentAssistant2 implements IContentAssistant, IContentAssistantExtension, IWidgetTokenKeeper, IWidgetTokenKeeperExtension { /** * A generic closer class used to monitor various * interface events in order to determine whether * content-assist should be terminated and all * associated windows closed. */ class Closer implements ControlListener, MouseListener, FocusListener, DisposeListener, IViewportListener { /** * Installs this closer on it's viewer's text widget. */ protected void install() { Control w= fViewer.getTextWidget(); if (Helper2.okToUse(w)) { Control shell= w.getShell(); shell.addControlListener(this); w.addMouseListener(this); w.addFocusListener(this); /* * 1GGYYWK: ITPJUI:ALL - Dismissing editor with code assist up causes lots of Internal Errors */ w.addDisposeListener(this); } fViewer.addViewportListener(this); } /** * Uninstalls this closer from the viewer's text widget. */ protected void uninstall() { Control w= fViewer.getTextWidget(); if (Helper2.okToUse(w)) { Control shell= w.getShell(); if (Helper2.okToUse(shell)) shell.removeControlListener(this); w.removeMouseListener(this); w.removeFocusListener(this); /* * 1GGYYWK: ITPJUI:ALL - Dismissing editor with code assist up causes lots of Internal Errors */ w.removeDisposeListener(this); } fViewer.removeViewportListener(this); } /* * @see ControlListener#controlResized(ControlEvent) */ public void controlResized(ControlEvent e) { hide(); } /* * @see ControlListener#controlMoved(ControlEvent) */ public void controlMoved(ControlEvent e) { hide(); } /* * @see MouseListener#mouseDown(MouseEvent) */ public void mouseDown(MouseEvent e) { hide(); } /* * @see MouseListener#mouseUp(MouseEvent) */ public void mouseUp(MouseEvent e) { } /* * @see MouseListener#mouseDoubleClick(MouseEvent) */ public void mouseDoubleClick(MouseEvent e) { hide(); } /* * @see FocusListener#focusGained(FocusEvent) */ public void focusGained(FocusEvent e) { } /* * @see FocusListener#focusLost(FocusEvent) */ public void focusLost(FocusEvent e) { if (fViewer != null) { Control control= fViewer.getTextWidget(); if (control != null) { Display d= control.getDisplay(); if (d != null) { d.asyncExec(new Runnable() { public void run() { if (!hasFocus()) hide(); } }); } } } } /* * @seeDisposeListener#widgetDisposed(DisposeEvent) */ public void widgetDisposed(DisposeEvent e) { /* * 1GGYYWK: ITPJUI:ALL - Dismissing editor with code assist up causes lots of Internal Errors */ hide(); } /* * @see IViewportListener#viewportChanged(int) */ public void viewportChanged(int topIndex) { hide(); } /** * Hides any open popups. */ protected void hide() { fProposalPopup.hide(); fContextInfoPopup.hide(); } } /** * An implementation of <code>IContentAssistListener</code>, this class is * used to monitor key events in support of automatic activation * of the content assistant. If enabled, the implementation utilizes a * thread to watch for input characters matching the activation * characters specified by the content assist processor, and if * detected, will wait the indicated delay interval before * activating the content assistant. */ class AutoAssistListener implements VerifyKeyListener, Runnable { private Thread fThread; private boolean fIsReset= false; private Object fMutex= new Object(); private int fShowStyle; private final static int SHOW_PROPOSALS= 1; private final static int SHOW_CONTEXT_INFO= 2; protected AutoAssistListener() { } protected void start(int showStyle) { fShowStyle= showStyle; fThread= new Thread(this, JFaceTextMessages2.getString("ContentAssistant.assist_delay_timer_name")); //$NON-NLS-1$ fThread.start(); } public void run() { try { while (true) { synchronized (fMutex) { if (fAutoActivationDelay != 0) fMutex.wait(fAutoActivationDelay); if (fIsReset) { fIsReset= false; continue; } } showAssist(fShowStyle); break; } } catch (InterruptedException e) { } fThread= null; } protected void reset(int showStyle) { synchronized (fMutex) { fShowStyle= showStyle; fIsReset= true; fMutex.notifyAll(); } } protected void stop() { if (fThread != null) { fThread.interrupt(); } } private boolean contains(char[] characters, char character) { if (characters != null) { for (int i= 0; i < characters.length; i++) { if (character == characters[i]) return true; } } return false; } public void verifyKey(VerifyEvent e) { int showStyle; int pos= fViewer.getSelectedRange().x; char[] activation= getCompletionProposalAutoActivationCharacters(fViewer, pos); if (contains(activation, e.character) && !fProposalPopup.isActive()) showStyle= SHOW_PROPOSALS; else { activation= getContextInformationAutoActivationCharacters(fViewer, pos); if (contains(activation, e.character) && !fContextInfoPopup.isActive()) showStyle= SHOW_CONTEXT_INFO; else { if (fThread != null && fThread.isAlive()) stop(); return; } } if (fThread != null && fThread.isAlive()) reset(showStyle); else start(showStyle); } protected void showAssist(final int showStyle) { Control control= fViewer.getTextWidget(); Display d= control.getDisplay(); if (d != null) { try { d.syncExec(new Runnable() { public void run() { if (showStyle == SHOW_PROPOSALS) fProposalPopup.showProposals(true); else if (showStyle == SHOW_CONTEXT_INFO) fContextInfoPopup.showContextProposals(true); } }); } catch (SWTError e) { } } } } /** * The laypout manager layouts the various * windows associated with the content assistant based on the * settings of the content assistant. */ class LayoutManager implements Listener { // Presentation types. public final static int LAYOUT_PROPOSAL_SELECTOR= 0; public final static int LAYOUT_CONTEXT_SELECTOR= 1; public final static int LAYOUT_CONTEXT_INFO_POPUP= 2; int fContextType= LAYOUT_CONTEXT_SELECTOR; Shell[] fShells= new Shell[3]; Object[] fPopups= new Object[3]; protected void add(Object popup, Shell shell, int type, int offset) { Assert.isNotNull(popup); Assert.isTrue(shell != null && !shell.isDisposed()); checkType(type); if (fShells[type] != shell) { if (fShells[type] != null) fShells[type].removeListener(SWT.Dispose, this); shell.addListener(SWT.Dispose, this); fShells[type]= shell; } fPopups[type]= popup; if (type == LAYOUT_CONTEXT_SELECTOR || type == LAYOUT_CONTEXT_INFO_POPUP) fContextType= type; layout(type, offset); adjustListeners(type); } protected void checkType(int type) { Assert.isTrue(type == LAYOUT_PROPOSAL_SELECTOR || type == LAYOUT_CONTEXT_SELECTOR || type == LAYOUT_CONTEXT_INFO_POPUP); } public void handleEvent(Event event) { Widget source= event.widget; source.removeListener(SWT.Dispose, this); int type= getShellType(source); checkType(type); fShells[type]= null; switch (type) { case LAYOUT_PROPOSAL_SELECTOR: if (fContextType == LAYOUT_CONTEXT_SELECTOR && Helper2.okToUse(fShells[LAYOUT_CONTEXT_SELECTOR])) { // Restore event notification to the tip popup. addContentAssistListener((IContentAssistListener2) fPopups[LAYOUT_CONTEXT_SELECTOR], CONTEXT_SELECTOR); } break; case LAYOUT_CONTEXT_SELECTOR: if (Helper2.okToUse(fShells[LAYOUT_PROPOSAL_SELECTOR])) { if (fProposalPopupOrientation == PROPOSAL_STACKED) layout(LAYOUT_PROPOSAL_SELECTOR, getSelectionOffset()); // Restore event notification to the proposal popup. addContentAssistListener((IContentAssistListener2) fPopups[LAYOUT_PROPOSAL_SELECTOR], PROPOSAL_SELECTOR); } fContextType= LAYOUT_CONTEXT_INFO_POPUP; break; case LAYOUT_CONTEXT_INFO_POPUP: if (Helper2.okToUse(fShells[LAYOUT_PROPOSAL_SELECTOR])) { if (fContextInfoPopupOrientation == CONTEXT_INFO_BELOW) layout(LAYOUT_PROPOSAL_SELECTOR, getSelectionOffset()); } fContextType= LAYOUT_CONTEXT_SELECTOR; break; } } protected int getShellType(Widget shell) { for (int i=0; i<fShells.length; i++) { if (fShells[i] == shell) return i; } return -1; } protected void layout(int type, int offset) { switch (type) { case LAYOUT_PROPOSAL_SELECTOR: layoutProposalSelector(offset); break; case LAYOUT_CONTEXT_SELECTOR: layoutContextSelector(offset); break; case LAYOUT_CONTEXT_INFO_POPUP: layoutContextInfoPopup(offset); break; } } protected void layoutProposalSelector(int offset) { if (fContextType == LAYOUT_CONTEXT_INFO_POPUP && fContextInfoPopupOrientation == CONTEXT_INFO_BELOW && Helper2.okToUse(fShells[LAYOUT_CONTEXT_INFO_POPUP])) { // Stack proposal selector beneath the tip box. Shell shell= fShells[LAYOUT_PROPOSAL_SELECTOR]; Shell parent= fShells[LAYOUT_CONTEXT_INFO_POPUP]; shell.setLocation(getStackedLocation(shell, parent)); } else if (fContextType != LAYOUT_CONTEXT_SELECTOR || !Helper2.okToUse(fShells[LAYOUT_CONTEXT_SELECTOR])) { // There are no other presentations to be concerned with, // so place the proposal selector beneath the cursor line. Shell shell= fShells[LAYOUT_PROPOSAL_SELECTOR]; shell.setLocation(getBelowLocation(shell, offset)); } else { switch (fProposalPopupOrientation) { case PROPOSAL_REMOVE: { // Remove the tip selector and place the // proposal selector beneath the cursor line. fShells[LAYOUT_CONTEXT_SELECTOR].dispose(); Shell shell= fShells[LAYOUT_PROPOSAL_SELECTOR]; shell.setLocation(getBelowLocation(shell, offset)); break; } case PROPOSAL_OVERLAY: { // Overlay the tip selector with the proposal selector. Shell shell= fShells[LAYOUT_PROPOSAL_SELECTOR]; shell.setLocation(getBelowLocation(shell, offset)); break; } case PROPOSAL_STACKED: { // Stack the proposal selector beneath the tip selector. Shell shell= fShells[LAYOUT_PROPOSAL_SELECTOR]; Shell parent= fShells[LAYOUT_CONTEXT_SELECTOR]; shell.setLocation(getStackedLocation(shell, parent)); break; } } } } protected void layoutContextSelector(int offset) { // Always place the context selector beneath the cursor line. Shell shell= fShells[LAYOUT_CONTEXT_SELECTOR]; shell.setLocation(getBelowLocation(shell, offset)); if (Helper2.okToUse(fShells[LAYOUT_PROPOSAL_SELECTOR])) { switch (fProposalPopupOrientation) { case PROPOSAL_REMOVE: // Remove the proposal selector. fShells[LAYOUT_PROPOSAL_SELECTOR].dispose(); break; case PROPOSAL_OVERLAY: // The proposal selector has been overlayed by the tip selector. break; case PROPOSAL_STACKED: { // Stack the proposal selector beneath the tip selector. shell= fShells[LAYOUT_PROPOSAL_SELECTOR]; Shell parent= fShells[LAYOUT_CONTEXT_SELECTOR]; shell.setLocation(getStackedLocation(shell, parent)); break; } } } } protected void layoutContextInfoPopup(int offset) { switch (fContextInfoPopupOrientation) { case CONTEXT_INFO_ABOVE: { // Place the popup above the cursor line. Shell shell= fShells[LAYOUT_CONTEXT_INFO_POPUP]; shell.setLocation(getAboveLocation(shell, offset)); break; } case CONTEXT_INFO_BELOW: { // Place the popup beneath the cursor line. Shell parent= fShells[LAYOUT_CONTEXT_INFO_POPUP]; parent.setLocation(getBelowLocation(parent, offset)); if (Helper2.okToUse(fShells[LAYOUT_PROPOSAL_SELECTOR])) { // Stack the proposal selector beneath the context info popup. Shell shell= fShells[LAYOUT_PROPOSAL_SELECTOR]; shell.setLocation(getStackedLocation(shell, parent)); } break; } } } protected void shiftHorizontalLocation(Point location, Rectangle shellBounds, Rectangle displayBounds) { if (location.x + shellBounds.width > displayBounds.width) location.x= displayBounds.width - shellBounds.width; if (location.x < displayBounds.x) location.x= displayBounds.x; } protected void shiftVerticalLocation(Point location, Rectangle shellBounds, Rectangle displayBounds) { if (location.y + shellBounds.height > displayBounds.height) location.y= displayBounds.height - shellBounds.height; if (location.y < displayBounds.y) location.y= displayBounds.y; } protected Point getAboveLocation(Shell shell, int offset) { StyledText text= fViewer.getTextWidget(); Point location= text.getLocationAtOffset(offset); location= text.toDisplay(location); Rectangle shellBounds= shell.getBounds(); Rectangle displayBounds= shell.getDisplay().getClientArea(); location.y=location.y - shellBounds.height; shiftHorizontalLocation(location, shellBounds, displayBounds); shiftVerticalLocation(location, shellBounds, displayBounds); return location; } protected Point getBelowLocation(Shell shell, int offset) { StyledText text= fViewer.getTextWidget(); Point location= text.getLocationAtOffset(offset); if (location.x < 0) location.x= 0; if (location.y < 0) location.y= 0; location= text.toDisplay(location); Rectangle shellBounds= shell.getBounds(); Rectangle displayBounds= shell.getDisplay().getClientArea(); location.y= location.y + text.getLineHeight(); shiftHorizontalLocation(location, shellBounds, displayBounds); shiftVerticalLocation(location, shellBounds, displayBounds); return location; } protected Point getStackedLocation(Shell shell, Shell parent) { Point p= parent.getLocation(); Point size= parent.getSize(); p.x += size.x / 4; p.y += size.y; p= parent.toDisplay(p); Rectangle shellBounds= shell.getBounds(); Rectangle displayBounds= shell.getDisplay().getClientArea(); shiftHorizontalLocation(p, shellBounds, displayBounds); shiftVerticalLocation(p, shellBounds, displayBounds); return p; } protected void adjustListeners(int type) { switch (type) { case LAYOUT_PROPOSAL_SELECTOR: if (fContextType == LAYOUT_CONTEXT_SELECTOR && Helper2.okToUse(fShells[LAYOUT_CONTEXT_SELECTOR])) // Disable event notification to the tip selector. removeContentAssistListener((IContentAssistListener2) fPopups[LAYOUT_CONTEXT_SELECTOR], CONTEXT_SELECTOR); break; case LAYOUT_CONTEXT_SELECTOR: if (Helper2.okToUse(fShells[LAYOUT_PROPOSAL_SELECTOR])) // Disable event notification to the proposal selector. removeContentAssistListener((IContentAssistListener2) fPopups[LAYOUT_PROPOSAL_SELECTOR], PROPOSAL_SELECTOR); break; case LAYOUT_CONTEXT_INFO_POPUP: break; } } } /** * Internal key listener and event consumer. */ class InternalListener implements VerifyKeyListener, IEventConsumer { /** * Verifies key events by notifying the registered listeners. * Each listener is allowed to indicate that the event has been * handled and should not be further processed. * * @param event the verify event * @see VerifyKeyListener#verifyKey */ public void verifyKey(VerifyEvent e) { IContentAssistListener2[] listeners= (IContentAssistListener2[]) fListeners.clone(); for (int i= 0; i < listeners.length; i++) { if (listeners[i] != null) { if (!listeners[i].verifyKey(e) || !e.doit) return; } } } /* * @see IEventConsumer#processEvent */ public void processEvent(VerifyEvent event) { installKeyListener(); IContentAssistListener2[] listeners= (IContentAssistListener2[])fListeners.clone(); for (int i= 0; i < listeners.length; i++) { if (listeners[i] != null) { listeners[i].processEvent(event); if (!event.doit) return; } } } } // Content-Assist Listener types final static int CONTEXT_SELECTOR= 0; final static int PROPOSAL_SELECTOR= 1; final static int CONTEXT_INFO_POPUP= 2; /** * The popup priority: &gt; infopops, &lt; standard content assist. * Default value: <code>10</code>. * * @since 3.0 */ public static final int WIDGET_PRIORITY= 10; private static final int DEFAULT_AUTO_ACTIVATION_DELAY= 500; private IInformationControlCreator fInformationControlCreator; private int fAutoActivationDelay= DEFAULT_AUTO_ACTIVATION_DELAY; private boolean fIsAutoActivated= false; private boolean fIsAutoInserting= false; private int fProposalPopupOrientation= PROPOSAL_OVERLAY; private int fContextInfoPopupOrientation= CONTEXT_INFO_ABOVE; private Map fProcessors; private String fPartitioning; private Color fContextInfoPopupBackground; private Color fContextInfoPopupForeground; private Color fContextSelectorBackground; private Color fContextSelectorForeground; private Color fProposalSelectorBackground; private Color fProposalSelectorForeground; private ITextViewer fViewer; private String fLastErrorMessage; private Closer fCloser; private LayoutManager fLayoutManager; private AutoAssistListener fAutoAssistListener; private InternalListener fInternalListener; private CompletionProposalPopup2 fProposalPopup; private ContextInformationPopup2 fContextInfoPopup; private boolean fKeyListenerHooked= false; private IContentAssistListener2[] fListeners= new IContentAssistListener2[4]; private int fCompletionPosition; private String[] fProposalStrings; private ICompletionProposal[] fProposals; /** Whether a proposal was chosen the last time a proposal popup was shown. */ private boolean fWasChosen; /** * Creates a new content assistant. The content assistant is not automatically activated, * overlays the completion proposals with context information list if necessary, and * shows the context information above the location at which it was activated. If auto * activation will be enabled, without further configuration steps, this content assistant * is activated after a 500 ms delay. It uses the default partitioning. */ public ContentAssistant2() { setContextInformationPopupOrientation(CONTEXT_INFO_ABOVE); setInformationControlCreator(getInformationControlCreator()); JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools(); IColorManager manager= textTools.getColorManager(); IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); Color c= getColor(store, PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND, manager); setProposalSelectorForeground(c); c= getColor(store, PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND, manager); setProposalSelectorBackground(c); } /** * Creates an <code>IInformationControlCreator</code> to be used to display context information. * * @return an <code>IInformationControlCreator</code> to be used to display context information */ private IInformationControlCreator getInformationControlCreator() { return new IInformationControlCreator() { public IInformationControl createInformationControl(Shell parent) { return new DefaultInformationControl(parent, new HTMLTextPresenter()); } }; } /** * Fetches the color specified by <code>key</code> from the given <code>IPreferenceStore</code>. * The color is managed by <code>manager</code> so we don't have to deal with its disposal. * * @param store the preference store * @param key the key into <code>store</code> * @param manager the color manager for the returned color * @return a color as specified by the value for <code>key</code> in <code>store</code>, managed by <code>manager</code> */ private static Color getColor(IPreferenceStore store, String key, IColorManager manager) { RGB rgb= PreferenceConverter.getColor(store, key); return manager.getColor(rgb); } /** * Sets the document partitioning this content assistant is using. * * @param partitioning the document partitioning for this content assistant */ public void setDocumentPartitioning(String partitioning) { Assert.isNotNull(partitioning); fPartitioning= partitioning; } /* * @see org.eclipse.jface.text.contentassist.IContentAssistantExtension#getDocumentPartitioning() * @since 3.0 */ public String getDocumentPartitioning() { return fPartitioning; } /** * Registers a given content assist processor for a particular content type. * If there is already a processor registered for this type, the new processor * is registered instead of the old one. * * @param processor the content assist processor to register, or <code>null</code> to remove an existing one * @param contentType the content type under which to register */ public void setContentAssistProcessor(IContentAssistProcessor processor, String contentType) { Assert.isNotNull(contentType); if (fProcessors == null) fProcessors= new HashMap(); if (processor == null) fProcessors.remove(contentType); else fProcessors.put(contentType, processor); } /* * @see IContentAssistant#getContentAssistProcessor */ public IContentAssistProcessor getContentAssistProcessor(String contentType) { if (fProcessors == null) return null; return (IContentAssistProcessor) fProcessors.get(contentType); } /** * Enables the content assistant's auto activation mode. * * @param enabled indicates whether auto activation is enabled or not */ public void enableAutoActivation(boolean enabled) { fIsAutoActivated= enabled; manageAutoActivation(fIsAutoActivated); } /** * Enables the content assistant's auto insertion mode. If enabled, * the content assistant inserts a proposal automatically if it is * the only proposal. In the case of ambiguities, the user must * make the choice. * * @param enabled indicates whether auto insertion is enabled or not * @since 2.0 */ public void enableAutoInsert(boolean enabled) { fIsAutoInserting= enabled; } /** * Returns whether this content assistant is in the auto insertion * mode or not. * * @return <code>true</code> if in auto insertion mode * @since 2.0 */ boolean isAutoInserting() { return fIsAutoInserting; } /** * Installs and uninstall the listeners needed for autoactivation. * @param start <code>true</code> if listeners must be installed, * <code>false</code> if they must be removed * @since 2.0 */ private void manageAutoActivation(boolean start) { if (start) { if (fViewer != null && fAutoAssistListener == null) { fAutoAssistListener= new AutoAssistListener(); if (fViewer instanceof ITextViewerExtension) { ITextViewerExtension extension= (ITextViewerExtension) fViewer; extension.appendVerifyKeyListener(fAutoAssistListener); } else { StyledText textWidget= fViewer.getTextWidget(); if (Helper2.okToUse(textWidget)) textWidget.addVerifyKeyListener(fAutoAssistListener); } } } else if (fAutoAssistListener != null) { if (fViewer instanceof ITextViewerExtension) { ITextViewerExtension extension= (ITextViewerExtension) fViewer; extension.removeVerifyKeyListener(fAutoAssistListener); } else { StyledText textWidget= fViewer.getTextWidget(); if (Helper2.okToUse(textWidget)) textWidget.removeVerifyKeyListener(fAutoAssistListener); } fAutoAssistListener= null; } } /** * Sets the delay after which the content assistant is automatically invoked * if the cursor is behind an auto activation character. * * @param delay the auto activation delay */ public void setAutoActivationDelay(int delay) { fAutoActivationDelay= delay; } /** * Sets the proposal popups' orientation. * The following values may be used: * <ul> * <li>PROPOSAL_OVERLAY<p> * proposal popup windows should overlay each other * </li> * <li>PROPOSAL_REMOVE<p> * any currently shown proposal popup should be closed * </li> * <li>PROPOSAL_STACKED<p> * proposal popup windows should be vertical stacked, with no overlap, * beneath the line containing the current cursor location * </li> * </ul> * * @param orientation the popup's orientation */ public void setProposalPopupOrientation(int orientation) { fProposalPopupOrientation= orientation; } /** * Sets the context information popup's orientation. * The following values may be used: * <ul> * <li>CONTEXT_ABOVE<p> * context information popup should always appear above the line containing * the current cursor location * </li> * <li>CONTEXT_BELOW<p> * context information popup should always appear below the line containing * the current cursor location * </li> * </ul> * * @param orientation the popup's orientation */ public void setContextInformationPopupOrientation(int orientation) { fContextInfoPopupOrientation= orientation; } /** * Sets the context information popup's background color. * * @param background the background color */ public void setContextInformationPopupBackground(Color background) { fContextInfoPopupBackground= background; } /** * Returns the background of the context information popup. * * @return the background of the context information popup * @since 2.0 */ Color getContextInformationPopupBackground() { return fContextInfoPopupBackground; } /** * Sets the context information popup's foreground color. * * @param foreground the foreground color * @since 2.0 */ public void setContextInformationPopupForeground(Color foreground) { fContextInfoPopupForeground= foreground; } /** * Returns the foreground of the context information popup. * * @return the foreground of the context information popup * @since 2.0 */ Color getContextInformationPopupForeground() { return fContextInfoPopupForeground; } /** * Sets the proposal selector's background color. * * @param background the background color * @since 2.0 */ public void setProposalSelectorBackground(Color background) { fProposalSelectorBackground= background; } /** * Returns the background of the proposal selector. * * @return the background of the proposal selector * @since 2.0 */ Color getProposalSelectorBackground() { return fProposalSelectorBackground; } /** * Sets the proposal's foreground color. * * @param foreground the foreground color * @since 2.0 */ public void setProposalSelectorForeground(Color foreground) { fProposalSelectorForeground= foreground; } /** * Returns the foreground of the proposal selector. * * @return the foreground of the proposal selector * @since 2.0 */ Color getProposalSelectorForeground() { return fProposalSelectorForeground; } /** * Sets the context selector's background color. * * @param background the background color * @since 2.0 */ public void setContextSelectorBackground(Color background) { fContextSelectorBackground= background; } /** * Returns the background of the context selector. * * @return the background of the context selector * @since 2.0 */ Color getContextSelectorBackground() { return fContextSelectorBackground; } /** * Sets the context selector's foreground color. * * @param foreground the foreground color * @since 2.0 */ public void setContextSelectorForeground(Color foreground) { fContextSelectorForeground= foreground; } /** * Returns the foreground of the context selector. * * @return the foreground of the context selector * @since 2.0 */ Color getContextSelectorForeground() { return fContextSelectorForeground; } /** * Sets the information control creator for the additional information control. * * @param creator the information control creator for the additional information control * @since 2.0 */ public void setInformationControlCreator(IInformationControlCreator creator) { fInformationControlCreator= creator; } /* * @see IContentAssist#install */ public void install(ITextViewer textViewer) { Assert.isNotNull(textViewer); fViewer= textViewer; fLayoutManager= new LayoutManager(); fInternalListener= new InternalListener(); AdditionalInfoController2 controller= null; if (fInformationControlCreator != null) { int delay= fAutoActivationDelay; if (delay == 0) delay= DEFAULT_AUTO_ACTIVATION_DELAY; delay= Math.round(delay * 1.5f); controller= new AdditionalInfoController2(fInformationControlCreator, delay); } fContextInfoPopup= new ContextInformationPopup2(this, fViewer); fProposalPopup= new CompletionProposalPopup2(this, fViewer, controller); manageAutoActivation(fIsAutoActivated); } /* * @see IContentAssist#uninstall */ public void uninstall() { if (fProposalPopup != null) fProposalPopup.hide(); if (fContextInfoPopup != null) fContextInfoPopup.hide(); manageAutoActivation(false); if (fCloser != null) { fCloser.uninstall(); fCloser= null; } fViewer= null; } /** * Adds the given shell of the specified type to the layout. * Valid types are defined by <code>LayoutManager</code>. * * @param popup a content assist popup * @param shell the shell of the content-assist popup * @param type the type of popup * @param visibleOffset the offset at which to layout the popup relative to the offset of the viewer's visible region * @since 2.0 */ void addToLayout(Object popup, Shell shell, int type, int visibleOffset) { fLayoutManager.add(popup, shell, type, visibleOffset); } /** * Layouts the registered popup of the given type relative to the * given offset. The offset is relative to the offset of the viewer's visible region. * Valid types are defined by <code>LayoutManager</code>. * * @param type the type of popup to layout * @param visibleOffset the offset at which to layout relative to the offset of the viewer's visible region * @since 2.0 */ void layout(int type, int visibleOffset) { fLayoutManager.layout(type, visibleOffset); } /** * Notifies the controller that a popup has lost focus. * * @param e the focus event */ void popupFocusLost(FocusEvent e) { fCloser.focusLost(e); } /** * Returns the offset of the selection relative to the offset of the visible region. * * @return the offset of the selection relative to the offset of the visible region * @since 2.0 */ int getSelectionOffset() { StyledText text= fViewer.getTextWidget(); return text.getSelectionRange().x; } /** * Returns whether the widget token could be acquired. * The following are valid listener types: * <ul> * <li>AUTO_ASSIST * <li>CONTEXT_SELECTOR * <li>PROPOSAL_SELECTOR * <li>CONTEXT_INFO_POPUP * <ul> * @param type the listener type for which to acquire * @return <code>true</code> if the widget token could be acquired * @since 2.0 */ private boolean acquireWidgetToken(int type) { switch (type) { case CONTEXT_SELECTOR: case PROPOSAL_SELECTOR: if (fViewer instanceof IWidgetTokenOwner) { IWidgetTokenOwner owner= (IWidgetTokenOwner) fViewer; return owner.requestWidgetToken(this); } else if (fViewer instanceof IWidgetTokenOwnerExtension) { IWidgetTokenOwnerExtension extension= (IWidgetTokenOwnerExtension) fViewer; return extension.requestWidgetToken(this, WIDGET_PRIORITY); } return false; } return true; } /** * Registers a content assist listener. * The following are valid listener types: * <ul> * <li>AUTO_ASSIST * <li>CONTEXT_SELECTOR * <li>PROPOSAL_SELECTOR * <li>CONTEXT_INFO_POPUP * <ul> * Returns whether the listener could be added successfully. A listener * can not be added if the widget token could not be acquired. * * @param listener the listener to register * @param type the type of listener * @return <code>true</code> if the listener could be added */ boolean addContentAssistListener(IContentAssistListener2 listener, int type) { if (acquireWidgetToken(type)) { fListeners[type]= listener; if (getNumberOfListeners() == 1) { fCloser= new Closer(); fCloser.install(); fViewer.setEventConsumer(fInternalListener); installKeyListener(); } return true; } return false; } /** * Installs a key listener on the text viewer's widget. */ private void installKeyListener() { if (!fKeyListenerHooked) { StyledText text= fViewer.getTextWidget(); if (Helper2.okToUse(text)) { if (fViewer instanceof ITextViewerExtension) { ITextViewerExtension e= (ITextViewerExtension) fViewer; e.prependVerifyKeyListener(fInternalListener); } else { text.addVerifyKeyListener(fInternalListener); } fKeyListenerHooked= true; } } } /** * Releases the previously acquired widget token if the token * is no longer necessary. * The following are valid listener types: * <ul> * <li>AUTO_ASSIST * <li>CONTEXT_SELECTOR * <li>PROPOSAL_SELECTOR * <li>CONTEXT_INFO_POPUP * <ul> * * @param type the listener type * @since 2.0 */ private void releaseWidgetToken(int type) { if (fListeners[CONTEXT_SELECTOR] == null && fListeners[PROPOSAL_SELECTOR] == null) { if (fViewer instanceof IWidgetTokenOwner) { IWidgetTokenOwner owner= (IWidgetTokenOwner) fViewer; owner.releaseWidgetToken(this); } } } /** * Unregisters a content assist listener. * * @param listener the listener to unregister * @param type the type of listener * * @see #addContentAssistListener */ void removeContentAssistListener(IContentAssistListener2 listener, int type) { fListeners[type]= null; if (getNumberOfListeners() == 0) { if (fCloser != null) { fCloser.uninstall(); fCloser= null; } uninstallKeyListener(); fViewer.setEventConsumer(null); } releaseWidgetToken(type); } /** * Uninstall the key listener from the text viewer's widget. */ private void uninstallKeyListener() { if (fKeyListenerHooked) { StyledText text= fViewer.getTextWidget(); if (Helper2.okToUse(text)) { if (fViewer instanceof ITextViewerExtension) { ITextViewerExtension e= (ITextViewerExtension) fViewer; e.removeVerifyKeyListener(fInternalListener); } else { text.removeVerifyKeyListener(fInternalListener); } fKeyListenerHooked= false; } } } /** * Returns the number of listeners. * * @return the number of listeners * @since 2.0 */ private int getNumberOfListeners() { int count= 0; for (int i= 0; i <= CONTEXT_INFO_POPUP; i++) { if (fListeners[i] != null) ++ count; } return count; } /* * @see IContentAssist#showPossibleCompletions */ public String showPossibleCompletions() { setProposalChosen(false); return fProposalPopup.showProposals(false); } public void hidePossibleCompletions() { if (fProposalPopup != null) fProposalPopup.hide(); } /** * Callback to signal this content assistant that the presentation of the possible completions has been stopped. * @since 2.1 */ protected void possibleCompletionsClosed() { } /* * @see IContentAssist#showContextInformation */ public String showContextInformation() { return fContextInfoPopup.showContextProposals(false); } /** * Callback to signal this content assistant that the presentation of the context information has been stopped. * @since 2.1 */ protected void contextInformationClosed() { } /** * Requests that the specified context information to be shown. * * @param contextInformation the context information to be shown * @param position the position to which the context information refers to * @since 2.0 */ void showContextInformation(IContextInformation contextInformation, int position) { fContextInfoPopup.showContextInformation(contextInformation, position); } /** * Returns the current content assist error message. * * @return an error message or <code>null</code> if no error has occurred */ String getErrorMessage() { return fLastErrorMessage; } /** * Returns the content assist processor for the content * type of the specified document position. * * @param textViewer the text viewer * @param offset a offset within the document * @return a content-assist processor or <code>null</code> if none exists */ private IContentAssistProcessor getProcessor(ITextViewer viewer, int offset) { try { String type= TextUtilities.getContentType(viewer.getDocument(), getDocumentPartitioning(), offset); return getContentAssistProcessor(type); } catch (BadLocationException x) { } return null; } /** * Returns an array of completion proposals computed based on * the specified document position. The position is used to * determine the appropriate content assist processor to invoke. * * @param viewer the viewer for which to compute the prosposals * @param position a document position * @return an array of completion proposals * * @see IContentAssistProcessor#computeCompletionProposals */ ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int position) { if (fProposals != null) { return fProposals; } else if (fProposalStrings != null) { ICompletionProposal[] result= new ICompletionProposal[fProposalStrings.length]; for (int i= 0; i < fProposalStrings.length; i++) { result[i]= new CompletionProposal(fProposalStrings[i], position, fProposalStrings[i].length(), fProposalStrings[i].length()); } return result; } else return null; } /** * Returns an array of context information objects computed based * on the specified document position. The position is used to determine * the appropriate content assist processor to invoke. * * @param viewer the viewer for which to compute the context information * @param position a document position * @return an array of context information objects * * @see IContentAssistProcessor#computeContextInformation */ IContextInformation[] computeContextInformation(ITextViewer viewer, int position) { fLastErrorMessage= null; IContextInformation[] result= null; IContentAssistProcessor p= getProcessor(viewer, position); if (p != null) { result= p.computeContextInformation(viewer, position); fLastErrorMessage= p.getErrorMessage(); } return result; } /** * Returns the context information validator that should be used to * determine when the currently displayed context information should * be dismissed. The position is used to determine the appropriate * content assist processor to invoke. * * @param textViewer the text viewer * @param offset a document offset * @return an validator * * @see IContentAssistProcessor#getContextInformationValidator */ IContextInformationValidator getContextInformationValidator(ITextViewer textViewer, int offset) { IContentAssistProcessor p= getProcessor(textViewer, offset); return p != null ? p.getContextInformationValidator() : null; } /** * Returns the context information presenter that should be used to * display context information. The position is used to determine the appropriate * content assist processor to invoke. * * @param textViewer the text viewer * @param offset a document offset * @return a presenter * @since 2.0 */ IContextInformationPresenter getContextInformationPresenter(ITextViewer textViewer, int offset) { IContextInformationValidator validator= getContextInformationValidator(textViewer, offset); if (validator instanceof IContextInformationPresenter) return (IContextInformationPresenter) validator; return null; } /** * Returns the characters which when typed by the user should automatically * initiate proposing completions. The position is used to determine the * appropriate content assist processor to invoke. * * @param textViewer the text viewer * @param offset a document offset * @return the auto activation characters * * @see IContentAssistProcessor#getCompletionProposalAutoActivationCharacters */ private char[] getCompletionProposalAutoActivationCharacters(ITextViewer textViewer, int offset) { IContentAssistProcessor p= getProcessor(textViewer, offset); return p != null ? p.getCompletionProposalAutoActivationCharacters() : null; } /** * Returns the characters which when typed by the user should automatically * initiate the presentation of context information. The position is used * to determine the appropriate content assist processor to invoke. * * @param textViewer the text viewer * @param offset a document offset * @return the auto activation characters * * @see IContentAssistProcessor#getContextInformationAutoActivationCharacters */ private char[] getContextInformationAutoActivationCharacters(ITextViewer textViewer, int offset) { IContentAssistProcessor p= getProcessor(textViewer, offset); return p != null ? p.getContextInformationAutoActivationCharacters() : null; } /* * @see org.eclipse.jface.text.IWidgetTokenKeeper#requestWidgetToken(IWidgetTokenOwner) * @since 2.0 */ public boolean requestWidgetToken(IWidgetTokenOwner owner) { hidePossibleCompletions(); return true; } /** * @param i */ public void setCompletionPosition(int completionPosition) { fCompletionPosition= completionPosition; } public int getCompletionPosition() { return fCompletionPosition; } /** * @param strings */ public void setCompletions(String[] proposals) { fProposalStrings= proposals; } /** * @param proposals */ public void setCompletions(ICompletionProposal[] proposals) { fProposals= proposals; setProposalChosen(false); } /* * @see org.eclipse.jface.text.IWidgetTokenKeeperExtension#requestWidgetToken(org.eclipse.jface.text.IWidgetTokenOwner, int) * @since 3.0 */ public boolean requestWidgetToken(IWidgetTokenOwner owner, int priority) { if (priority > WIDGET_PRIORITY) { hidePossibleCompletions(); return true; } else return false; } /* * @see org.eclipse.jface.text.IWidgetTokenKeeperExtension#setFocus(org.eclipse.jface.text.IWidgetTokenOwner) * @since 3.0 */ public void setFocus(IWidgetTokenOwner owner) { if (fProposalPopup != null) fProposalPopup.setFocus(); } /** * Returns a hint whether a proposal was chosen the last time a popup selector was shown. * * @return <code>true</code> if a proposal was chosen and inserted the last time * {@link #showPossibleCompletions()} was called, <code>false</code> otherwise or if no proposal * has been shown so far */ public boolean wasProposalChosen() { return fWasChosen; } /** * Sets the <code>wasChosen</code> flag which indicates whether a proposal was selected the last * time a proposal popup was shown. * * @param wasChosen the new value of the <code>wasChosen</code> flag. */ protected void setProposalChosen(boolean wasChosen) { fWasChosen= wasChosen; } /** * Returns whether any popups controlled by the receiver have the input focus. * * @return <code>true</code> if any of the managed popups have the focus, <code>false</code> otherwise */ public boolean hasFocus() { return (fProposalPopup != null && fProposalPopup.hasFocus()) || (fContextInfoPopup != null && fContextInfoPopup.hasFocus()); } }
40,009
Bug 40009 [templates][typing] quote cancels template parameters
define a template as follows ----------------------------- method(${parameter},${paramter2}); ----------------------------- when using the above template if you put string as the first parameter and the auto-closing of quotes is enabled eg. ---------------------------- method("hello",parameter2); ---------------------------- when you press tab the second parameter is not highlighted!
resolved fixed
913fb8d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-24T11:12:02Z
2003-07-14T10:53:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/CompilationUnitEditor.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.lang.reflect.InvocationTargetException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Stack; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Preferences; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.VerifyKeyListener; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.dialogs.IMessageProvider; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.window.Window; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.DocumentCommand; import org.eclipse.jface.text.IAutoEditStrategy; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.ILineTracker; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextOperationTarget; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.text.ITextViewerExtension; import org.eclipse.jface.text.ITypedRegion; import org.eclipse.jface.text.IWidgetTokenKeeper; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.TextUtilities; import org.eclipse.jface.text.contentassist.ContentAssistant; import org.eclipse.jface.text.contentassist.IContentAssistant; 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.SourceViewerConfiguration; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.actions.ActionContext; import org.eclipse.ui.actions.ActionGroup; import org.eclipse.ui.actions.WorkspaceModifyOperation; import org.eclipse.ui.dialogs.SaveAsDialog; import org.eclipse.ui.editors.text.IStorageDocumentProvider; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.part.FileEditorInput; import org.eclipse.ui.texteditor.ContentAssistAction; import org.eclipse.ui.texteditor.ExtendedTextEditorPreferenceConstants; import org.eclipse.ui.texteditor.IDocumentProvider; import org.eclipse.ui.texteditor.ITextEditorActionConstants; import org.eclipse.ui.texteditor.TextOperationAction; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.ISourceReference; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.IWorkingCopyManager; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.actions.GenerateActionGroup; import org.eclipse.jdt.ui.actions.IJavaEditorActionDefinitionIds; import org.eclipse.jdt.ui.actions.RefactorActionGroup; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.actions.AddBlockCommentAction; import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup; import org.eclipse.jdt.internal.ui.actions.IndentAction; import org.eclipse.jdt.internal.ui.actions.RemoveBlockCommentAction; import org.eclipse.jdt.internal.ui.compare.LocalHistoryActionGroup; import org.eclipse.jdt.internal.ui.text.ContentAssistPreference; import org.eclipse.jdt.internal.ui.text.IJavaPartitions; import org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionAssistant; import org.eclipse.jdt.internal.ui.text.java.IReconcilingParticipant; import org.eclipse.jdt.internal.ui.text.java.SmartSemicolonAutoEditStrategy; import org.eclipse.jdt.internal.ui.text.link.LinkedPositionManager; import org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI; import org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI.ExitFlags; /** * Java specific text editor. */ public class CompilationUnitEditor extends JavaEditor implements IReconcilingParticipant { /** * Text operation code for requesting correction assist to show correction * proposals for the current position. */ public static final int CORRECTIONASSIST_PROPOSALS= 50; interface ITextConverter { void customizeDocumentCommand(IDocument document, DocumentCommand command); } class AdaptedSourceViewer extends JavaSourceViewer { private List fTextConverters; private boolean fIgnoreTextConverters= false; private JavaCorrectionAssistant fCorrectionAssistant; public AdaptedSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean showAnnotationsOverview, int styles) { super(parent, verticalRuler, overviewRuler, showAnnotationsOverview, styles); } public IContentAssistant getContentAssistant() { return fContentAssistant; } /* * @see ITextOperationTarget#doOperation(int) */ public void doOperation(int operation) { if (getTextWidget() == null) return; switch (operation) { case CONTENTASSIST_PROPOSALS: String msg= fContentAssistant.showPossibleCompletions(); setStatusLineErrorMessage(msg); return; case CORRECTIONASSIST_PROPOSALS: msg= fCorrectionAssistant.showPossibleCompletions(); setStatusLineErrorMessage(msg); return; case UNDO: fIgnoreTextConverters= true; break; case REDO: fIgnoreTextConverters= true; break; } super.doOperation(operation); } /* * @see ITextOperationTarget#canDoOperation(int) */ public boolean canDoOperation(int operation) { if (operation == CORRECTIONASSIST_PROPOSALS) return isEditable(); return super.canDoOperation(operation); } /* * @see TextViewer#handleDispose() */ protected void handleDispose() { if (fCorrectionAssistant != null) { fCorrectionAssistant.uninstall(); fCorrectionAssistant= null; } super.handleDispose(); } public void insertTextConverter(ITextConverter textConverter, int index) { throw new UnsupportedOperationException(); } public void addTextConverter(ITextConverter textConverter) { if (fTextConverters == null) { fTextConverters= new ArrayList(1); fTextConverters.add(textConverter); } else if (!fTextConverters.contains(textConverter)) fTextConverters.add(textConverter); } public void removeTextConverter(ITextConverter textConverter) { if (fTextConverters != null) { fTextConverters.remove(textConverter); if (fTextConverters.size() == 0) fTextConverters= null; } } /* * @see TextViewer#customizeDocumentCommand(DocumentCommand) */ protected void customizeDocumentCommand(DocumentCommand command) { super.customizeDocumentCommand(command); if (!fIgnoreTextConverters && fTextConverters != null) { for (Iterator e = fTextConverters.iterator(); e.hasNext();) ((ITextConverter) e.next()).customizeDocumentCommand(getDocument(), command); } fIgnoreTextConverters= false; } // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270 public void updateIndentationPrefixes() { SourceViewerConfiguration configuration= getSourceViewerConfiguration(); String[] types= configuration.getConfiguredContentTypes(this); for (int i= 0; i < types.length; i++) { String[] prefixes= configuration.getIndentPrefixes(this, types[i]); if (prefixes != null && prefixes.length > 0) setIndentPrefixes(prefixes, types[i]); } } /* * @see IWidgetTokenOwner#requestWidgetToken(IWidgetTokenKeeper) */ public boolean requestWidgetToken(IWidgetTokenKeeper requester) { if (WorkbenchHelp.isContextHelpDisplayed()) return false; return super.requestWidgetToken(requester); } /* * @see IWidgetTokenOwnerExtension#requestWidgetToken(IWidgetTokenKeeper, int) * @since 3.0 */ public boolean requestWidgetToken(IWidgetTokenKeeper requester, int priority) { if (WorkbenchHelp.isContextHelpDisplayed()) return false; return super.requestWidgetToken(requester, priority); } /* * @see org.eclipse.jface.text.source.ISourceViewer#configure(org.eclipse.jface.text.source.SourceViewerConfiguration) */ public void configure(SourceViewerConfiguration configuration) { super.configure(configuration); fCorrectionAssistant= new JavaCorrectionAssistant(CompilationUnitEditor.this); fCorrectionAssistant.install(this); IAutoEditStrategy smartSemi= new SmartSemicolonAutoEditStrategy(IJavaPartitions.JAVA_PARTITIONING); prependAutoEditStrategy(smartSemi, IDocument.DEFAULT_CONTENT_TYPE); } } static class TabConverter implements ITextConverter { private int fTabRatio; private ILineTracker fLineTracker; public TabConverter() { } public void setNumberOfSpacesPerTab(int ratio) { fTabRatio= ratio; } public void setLineTracker(ILineTracker lineTracker) { fLineTracker= lineTracker; } private int insertTabString(StringBuffer buffer, int offsetInLine) { if (fTabRatio == 0) return 0; int remainder= offsetInLine % fTabRatio; remainder= fTabRatio - remainder; for (int i= 0; i < remainder; i++) buffer.append(' '); return remainder; } public void customizeDocumentCommand(IDocument document, DocumentCommand command) { String text= command.text; if (text == null) return; int index= text.indexOf('\t'); if (index > -1) { StringBuffer buffer= new StringBuffer(); fLineTracker.set(command.text); int lines= fLineTracker.getNumberOfLines(); try { for (int i= 0; i < lines; i++) { int offset= fLineTracker.getLineOffset(i); int endOffset= offset + fLineTracker.getLineLength(i); String line= text.substring(offset, endOffset); int position= 0; if (i == 0) { IRegion firstLine= document.getLineInformationOfOffset(command.offset); position= command.offset - firstLine.getOffset(); } int length= line.length(); for (int j= 0; j < length; j++) { char c= line.charAt(j); if (c == '\t') { position += insertTabString(buffer, position); } else { buffer.append(c); ++ position; } } } command.text= buffer.toString(); } catch (BadLocationException x) { } } } } private class ExitPolicy implements LinkedPositionUI.ExitPolicy { final char fExitCharacter; final char fEscapeCharacter; final Stack fStack; final int fSize; public ExitPolicy(char exitCharacter, char escapeCharacter, Stack stack) { fExitCharacter= exitCharacter; fEscapeCharacter= escapeCharacter; fStack= stack; fSize= fStack.size(); } /* * @see org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI.ExitPolicy#doExit(org.eclipse.jdt.internal.ui.text.link.LinkedPositionManager, org.eclipse.swt.events.VerifyEvent, int, int) */ public ExitFlags doExit(LinkedPositionManager manager, VerifyEvent event, int offset, int length) { if (event.character == fExitCharacter) { if (fSize == fStack.size() && !isMasked(offset)) { if (manager.anyPositionIncludes(offset, length)) return new ExitFlags(LinkedPositionUI.COMMIT| LinkedPositionUI.UPDATE_CARET, false); else return new ExitFlags(LinkedPositionUI.COMMIT, true); } } Position p= manager.getFirstPosition(); int pEndOffset= p.offset + p.length; // if the bracket position gets deleted or replaced, take the linked UI down. // 1: the event has to happen so that it occurs on or before the position end if (pEndOffset >= offset) { int endOffset= offset + length; // 2: either it is a replace event (selection length > 0, selection extends over closing peer, character != 0) // or it is a delete event right at the end of the position, with no selection if (pEndOffset < endOffset && event.character != 0 || length == 0 && pEndOffset == endOffset && event.keyCode == 127) return new ExitFlags(LinkedPositionUI.COMMIT, true); } switch (event.character) { case '\b': { if (p.offset == offset && p.length == length) return new ExitFlags(0, false); else return null; } case '\n': case '\r': return new ExitFlags(LinkedPositionUI.COMMIT, true); case ';': if (getInsertMode() == SMART_INSERT) return new ExitFlags(LinkedPositionUI.COMMIT, true); // else fall through default: return null; } } private boolean isMasked(int offset) { IDocument document= getSourceViewer().getDocument(); try { return fEscapeCharacter == document.getChar(offset - 1); } catch (BadLocationException e) { } return false; } } private static class BracketLevel { int fOffset; int fLength; LinkedPositionManager fManager; LinkedPositionUI fEditor; } private class BracketInserter implements VerifyKeyListener, LinkedPositionUI.ExitListener { private boolean fCloseBrackets= true; private boolean fCloseStrings= true; private Stack fBracketLevelStack= new Stack(); public void setCloseBracketsEnabled(boolean enabled) { fCloseBrackets= enabled; } public void setCloseStringsEnabled(boolean enabled) { fCloseStrings= enabled; } private boolean hasIdentifierToTheRight(IDocument document, int offset) { try { int end= offset; IRegion endLine= document.getLineInformationOfOffset(end); int maxEnd= endLine.getOffset() + endLine.getLength(); while (end != maxEnd && Character.isWhitespace(document.getChar(end))) ++end; return end != maxEnd && Character.isJavaIdentifierPart(document.getChar(end)); } catch (BadLocationException e) { // be conservative return true; } } private boolean hasIdentifierToTheLeft(IDocument document, int offset) { try { int start= offset; IRegion startLine= document.getLineInformationOfOffset(start); int minStart= startLine.getOffset(); while (start != minStart && Character.isWhitespace(document.getChar(start - 1))) --start; return start != minStart && Character.isJavaIdentifierPart(document.getChar(start - 1)); } catch (BadLocationException e) { return true; } } private boolean hasCharacterToTheRight(IDocument document, int offset, char character) { try { int end= offset; IRegion endLine= document.getLineInformationOfOffset(end); int maxEnd= endLine.getOffset() + endLine.getLength(); while (end != maxEnd && Character.isWhitespace(document.getChar(end))) ++end; return end != maxEnd && document.getChar(end) == character; } catch (BadLocationException e) { // be conservative return true; } } /* * @see org.eclipse.swt.custom.VerifyKeyListener#verifyKey(org.eclipse.swt.events.VerifyEvent) */ public void verifyKey(VerifyEvent event) { if (!event.doit || getInsertMode() != SMART_INSERT) return; final ISourceViewer sourceViewer= getSourceViewer(); IDocument document= sourceViewer.getDocument(); final Point selection= sourceViewer.getSelectedRange(); final int offset= selection.x; final int length= selection.y; switch (event.character) { case '(': if (hasCharacterToTheRight(document, offset + length, '(')) return; // fall through case '[': if (!fCloseBrackets) return; if (hasIdentifierToTheRight(document, offset + length)) return; // fall through case '\'': if (event.character == '\'') { if (!fCloseStrings) return; if (hasIdentifierToTheLeft(document, offset) || hasIdentifierToTheRight(document, offset + length)) return; } // fall through case '"': if (event.character == '"') { if (!fCloseStrings) return; if (hasIdentifierToTheLeft(document, offset) || hasIdentifierToTheRight(document, offset + length)) return; } try { ITypedRegion partition= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, offset); if (! IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType()) && partition.getOffset() != offset) return; if (!validateEditorInputState()) return; final char character= event.character; final char closingCharacter= getPeerCharacter(character); final StringBuffer buffer= new StringBuffer(); buffer.append(character); buffer.append(closingCharacter); document.replace(offset, length, buffer.toString()); BracketLevel level= new BracketLevel(); fBracketLevelStack.push(level); level.fManager= new LinkedPositionManager(document, fBracketLevelStack.size() > 1); level.fManager.addPosition(offset + 1, 0); level.fOffset= offset; level.fLength= 2; level.fEditor= new LinkedPositionUI(sourceViewer, level.fManager); level.fEditor.setCancelListener(this); level.fEditor.setExitPolicy(new ExitPolicy(closingCharacter, getEscapeCharacter(closingCharacter), fBracketLevelStack)); level.fEditor.setFinalCaretOffset(offset + 2); level.fEditor.enter(); IRegion newSelection= level.fEditor.getSelectedRegion(); sourceViewer.setSelectedRange(newSelection.getOffset(), newSelection.getLength()); event.doit= false; } catch (BadLocationException e) { } break; } } /* * @see org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI.ExitListener#exit(boolean) */ public void exit(boolean accept) { BracketLevel level= (BracketLevel) fBracketLevelStack.pop(); if (accept) return; // remove brackets try { final ISourceViewer sourceViewer= getSourceViewer(); IDocument document= sourceViewer.getDocument(); document.replace(level.fOffset, level.fLength, null); } catch (BadLocationException e) { } } } /** Preference key for code formatter tab size */ private final static String CODE_FORMATTER_TAB_SIZE= JavaCore.FORMATTER_TAB_SIZE; /** Preference key for inserting spaces rather than tabs */ private final static String SPACES_FOR_TABS= PreferenceConstants.EDITOR_SPACES_FOR_TABS; /** Preference key for automatically closing strings */ private final static String CLOSE_STRINGS= PreferenceConstants.EDITOR_CLOSE_STRINGS; /** Preference key for automatically closing brackets and parenthesis */ private final static String CLOSE_BRACKETS= PreferenceConstants.EDITOR_CLOSE_BRACKETS; /** The editor's save policy */ protected ISavePolicy fSavePolicy; /** Listener to annotation model changes that updates the error tick in the tab image */ private JavaEditorErrorTickUpdater fJavaEditorErrorTickUpdater; /** The editor's tab converter */ private TabConverter fTabConverter; /** The remembered java element */ private IJavaElement fRememberedElement; /** The remembered selection */ private ITextSelection fRememberedSelection; /** The remembered java element offset */ private int fRememberedElementOffset; /** The bracket inserter. */ private BracketInserter fBracketInserter= new BracketInserter(); /** The standard action groups added to the menu */ private GenerateActionGroup fGenerateActionGroup; private CompositeActionGroup fContextMenuGroup; /** * Creates a new compilation unit editor. */ public CompilationUnitEditor() { super(); setDocumentProvider(JavaPlugin.getDefault().getCompilationUnitDocumentProvider()); setEditorContextMenuId("#CompilationUnitEditorContext"); //$NON-NLS-1$ setRulerContextMenuId("#CompilationUnitRulerContext"); //$NON-NLS-1$ setOutlinerContextMenuId("#CompilationUnitOutlinerContext"); //$NON-NLS-1$ // don't set help contextId, we install our own help context fSavePolicy= null; fJavaEditorErrorTickUpdater= new JavaEditorErrorTickUpdater(this); } /* * @see AbstractTextEditor#createActions() */ protected void createActions() { super.createActions(); Action action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "CorrectionAssistProposal.", this, CORRECTIONASSIST_PROPOSALS); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.CORRECTION_ASSIST_PROPOSALS); setAction("CorrectionAssistProposal", action); //$NON-NLS-1$ markAsStateDependentAction("CorrectionAssistProposal", true); //$NON-NLS-1$ WorkbenchHelp.setHelp(action, IJavaHelpContextIds.QUICK_FIX_ACTION); action= new ContentAssistAction(JavaEditorMessages.getResourceBundle(), "ContentAssistProposal.", this); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS); setAction("ContentAssistProposal", action); //$NON-NLS-1$ markAsStateDependentAction("ContentAssistProposal", true); //$NON-NLS-1$ WorkbenchHelp.setHelp(action, IJavaHelpContextIds.CONTENT_ASSIST_ACTION); action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "ContentAssistContextInformation.", this, ISourceViewer.CONTENTASSIST_CONTEXT_INFORMATION); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.CONTENT_ASSIST_CONTEXT_INFORMATION); setAction("ContentAssistContextInformation", action); //$NON-NLS-1$ markAsStateDependentAction("ContentAssistContextInformation", true); //$NON-NLS-1$ WorkbenchHelp.setHelp(action, IJavaHelpContextIds.PARAMETER_HINTS_ACTION); action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "Comment.", this, ITextOperationTarget.PREFIX); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.COMMENT); setAction("Comment", action); //$NON-NLS-1$ markAsStateDependentAction("Comment", true); //$NON-NLS-1$ WorkbenchHelp.setHelp(action, IJavaHelpContextIds.COMMENT_ACTION); action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "Uncomment.", this, ITextOperationTarget.STRIP_PREFIX); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.UNCOMMENT); setAction("Uncomment", action); //$NON-NLS-1$ markAsStateDependentAction("Uncomment", true); //$NON-NLS-1$ WorkbenchHelp.setHelp(action, IJavaHelpContextIds.UNCOMMENT_ACTION); action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "Format.", this, ISourceViewer.FORMAT); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.FORMAT); setAction("Format", action); //$NON-NLS-1$ markAsStateDependentAction("Format", true); //$NON-NLS-1$ markAsSelectionDependentAction("Format", true); //$NON-NLS-1$ WorkbenchHelp.setHelp(action, IJavaHelpContextIds.FORMAT_ACTION); action= new AddBlockCommentAction(JavaEditorMessages.getResourceBundle(), "AddBlockComment.", this); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.ADD_BLOCK_COMMENT); setAction("AddBlockComment", action); //$NON-NLS-1$ markAsStateDependentAction("AddBlockComment", true); //$NON-NLS-1$ markAsSelectionDependentAction("AddBlockComment", true); //$NON-NLS-1$ WorkbenchHelp.setHelp(action, IJavaHelpContextIds.ADD_BLOCK_COMMENT_ACTION); action= new RemoveBlockCommentAction(JavaEditorMessages.getResourceBundle(), "RemoveBlockComment.", this); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.REMOVE_BLOCK_COMMENT); setAction("RemoveBlockComment", action); //$NON-NLS-1$ markAsStateDependentAction("RemoveBlockComment", true); //$NON-NLS-1$ markAsSelectionDependentAction("RemoveBlockComment", true); //$NON-NLS-1$ WorkbenchHelp.setHelp(action, IJavaHelpContextIds.REMOVE_BLOCK_COMMENT_ACTION); action= new IndentAction(JavaEditorMessages.getResourceBundle(), "Indent.", this, false); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.INDENT); setAction("Indent", action); //$NON-NLS-1$ markAsStateDependentAction("Indent", true); //$NON-NLS-1$ markAsSelectionDependentAction("Indent", true); //$NON-NLS-1$ WorkbenchHelp.setHelp(action, IJavaHelpContextIds.INDENT_ACTION); action= new IndentAction(JavaEditorMessages.getResourceBundle(), "Indent.", this, true); //$NON-NLS-1$ setAction("IndentOnTab", action); //$NON-NLS-1$ markAsStateDependentAction("IndentOnTab", true); //$NON-NLS-1$ markAsSelectionDependentAction("IndentOnTab", true); //$NON-NLS-1$ if (getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SMART_TAB)) { // don't replace Shift Right - have to make sure their enablement is mutually exclusive // removeActionActivationCode(ITextEditorActionConstants.SHIFT_RIGHT); setActionActivationCode("IndentOnTab", '\t', -1, SWT.NONE); //$NON-NLS-1$ } fGenerateActionGroup= new GenerateActionGroup(this, ITextEditorActionConstants.GROUP_EDIT); ActionGroup rg= new RefactorActionGroup(this, ITextEditorActionConstants.GROUP_EDIT); fActionGroups.addGroup(rg); fActionGroups.addGroup(fGenerateActionGroup); // We have to keep the context menu group separate to have better control over positioning fContextMenuGroup= new CompositeActionGroup(new ActionGroup[] { fGenerateActionGroup, rg, new LocalHistoryActionGroup(this, ITextEditorActionConstants.GROUP_EDIT)}); } /* * @see JavaEditor#getElementAt(int) */ protected IJavaElement getElementAt(int offset) { return getElementAt(offset, true); } /** * Returns the most narrow element including the given offset. If <code>reconcile</code> * is <code>true</code> the editor's input element is reconciled in advance. If it is * <code>false</code> this method only returns a result if the editor's input element * does not need to be reconciled. * * @param offset the offset included by the retrieved element * @param reconcile <code>true</code> if working copy should be reconciled */ protected IJavaElement getElementAt(int offset, boolean reconcile) { IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager(); ICompilationUnit unit= manager.getWorkingCopy(getEditorInput()); if (unit != null) { try { if (reconcile) { synchronized (unit) { unit.reconcile(); } return unit.getElementAt(offset); } else if (unit.isConsistent()) return unit.getElementAt(offset); } catch (JavaModelException x) { if (!x.isDoesNotExist()) JavaPlugin.log(x.getStatus()); // nothing found, be tolerant and go on } } return null; } /* * @see JavaEditor#getCorrespondingElement(IJavaElement) */ protected IJavaElement getCorrespondingElement(IJavaElement element) { try { return EditorUtility.getWorkingCopy(element, true); } catch (JavaModelException x) { JavaPlugin.log(x.getStatus()); // nothing found, be tolerant and go on } return null; } /* * @see AbstractTextEditor#editorContextMenuAboutToShow(IMenuManager) */ public void editorContextMenuAboutToShow(IMenuManager menu) { super.editorContextMenuAboutToShow(menu); ActionContext context= new ActionContext(getSelectionProvider().getSelection()); fContextMenuGroup.setContext(context); fContextMenuGroup.fillContextMenu(menu); fContextMenuGroup.setContext(null); } /* * @see JavaEditor#setOutlinePageInput(JavaOutlinePage, IEditorInput) */ protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input) { if (page != null) { IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager(); page.setInput(manager.getWorkingCopy(input)); } } /* * @see AbstractTextEditor#performSaveOperation(WorkspaceModifyOperation, IProgressMonitor) */ protected void performSaveOperation(WorkspaceModifyOperation operation, IProgressMonitor progressMonitor) { IDocumentProvider p= getDocumentProvider(); if (p instanceof ICompilationUnitDocumentProvider) { ICompilationUnitDocumentProvider cp= (ICompilationUnitDocumentProvider) p; cp.setSavePolicy(fSavePolicy); } try { super.performSaveOperation(operation, progressMonitor); } finally { if (p instanceof ICompilationUnitDocumentProvider) { ICompilationUnitDocumentProvider cp= (ICompilationUnitDocumentProvider) p; cp.setSavePolicy(null); } } } /* * @see AbstractTextEditor#doSaveAs */ public void doSaveAs() { if (askIfNonWorkbenchEncodingIsOk()) { super.doSaveAs(); } } /* * @see AbstractTextEditor#doSave(IProgressMonitor) */ public void doSave(IProgressMonitor progressMonitor) { IDocumentProvider p= getDocumentProvider(); if (p == null) { // editor has been closed return; } if (!askIfNonWorkbenchEncodingIsOk()) { progressMonitor.setCanceled(true); return; } if (p.isDeleted(getEditorInput())) { if (isSaveAsAllowed()) { /* * 1GEUSSR: ITPUI:ALL - User should never loose changes made in the editors. * Changed Behavior to make sure that if called inside a regular save (because * of deletion of input element) there is a way to report back to the caller. */ performSaveAs(progressMonitor); } else { /* * 1GF5YOX: ITPJUI:ALL - Save of delete file claims it's still there * Missing resources. */ Shell shell= getSite().getShell(); MessageDialog.openError(shell, JavaEditorMessages.getString("CompilationUnitEditor.error.saving.title1"), JavaEditorMessages.getString("CompilationUnitEditor.error.saving.message1")); //$NON-NLS-1$ //$NON-NLS-2$ } } else { setStatusLineErrorMessage(null); IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager(); ICompilationUnit unit= manager.getWorkingCopy(getEditorInput()); if (unit != null) { synchronized (unit) { performSaveOperation(createSaveOperation(false), progressMonitor); } } else performSaveOperation(createSaveOperation(false), progressMonitor); } } /** * Asks the user if it is ok to store in non-workbench encoding. * @return <true> if the user wants to continue */ private boolean askIfNonWorkbenchEncodingIsOk() { IDocumentProvider provider= getDocumentProvider(); if (provider instanceof IStorageDocumentProvider) { IEditorInput input= getEditorInput(); IStorageDocumentProvider storageProvider= (IStorageDocumentProvider)provider; String encoding= storageProvider.getEncoding(input); String defaultEncoding= storageProvider.getDefaultEncoding(); if (encoding != null && !encoding.equals(defaultEncoding)) { Shell shell= getSite().getShell(); String title= JavaEditorMessages.getString("CompilationUnitEditor.warning.save.nonWorkbenchEncoding.title"); //$NON-NLS-1$ String msg; if (input != null) msg= MessageFormat.format(JavaEditorMessages.getString("CompilationUnitEditor.warning.save.nonWorkbenchEncoding.message1"), new String[] {input.getName(), encoding});//$NON-NLS-1$ else msg= MessageFormat.format(JavaEditorMessages.getString("CompilationUnitEditor.warning.save.nonWorkbenchEncoding.message2"), new String[] {encoding});//$NON-NLS-1$ return MessageDialog.openQuestion(shell, title, msg); } } return true; } public boolean isSaveAsAllowed() { return true; } /** * The compilation unit editor implementation of this <code>AbstractTextEditor</code> * method asks the user for the workspace path of a file resource and saves the document * there. See http://dev.eclipse.org/bugs/show_bug.cgi?id=6295 */ protected void performSaveAs(IProgressMonitor progressMonitor) { Shell shell= getSite().getShell(); IEditorInput input = getEditorInput(); SaveAsDialog dialog= new SaveAsDialog(shell); IFile original= (input instanceof IFileEditorInput) ? ((IFileEditorInput) input).getFile() : null; if (original != null) dialog.setOriginalFile(original); dialog.create(); IDocumentProvider provider= getDocumentProvider(); if (provider == null) { // editor has been programmatically closed while the dialog was open return; } if (provider.isDeleted(input) && original != null) { String message= JavaEditorMessages.getFormattedString("CompilationUnitEditor.warning.save.delete", new Object[] { original.getName() }); //$NON-NLS-1$ dialog.setErrorMessage(null); dialog.setMessage(message, IMessageProvider.WARNING); } if (dialog.open() == Window.CANCEL) { if (progressMonitor != null) progressMonitor.setCanceled(true); return; } IPath filePath= dialog.getResult(); if (filePath == null) { if (progressMonitor != null) progressMonitor.setCanceled(true); return; } IWorkspace workspace= ResourcesPlugin.getWorkspace(); IFile file= workspace.getRoot().getFile(filePath); final IEditorInput newInput= new FileEditorInput(file); WorkspaceModifyOperation op= new WorkspaceModifyOperation() { public void execute(final IProgressMonitor monitor) throws CoreException { getDocumentProvider().saveDocument(monitor, newInput, getDocumentProvider().getDocument(getEditorInput()), true); } }; boolean success= false; try { provider.aboutToChange(newInput); new ProgressMonitorDialog(shell).run(false, true, op); success= true; } catch (InterruptedException x) { } catch (InvocationTargetException x) { Throwable t= x.getTargetException(); if (t instanceof CoreException) { CoreException cx= (CoreException) t; ErrorDialog.openError(shell, JavaEditorMessages.getString("CompilationUnitEditor.error.saving.title2"), JavaEditorMessages.getString("CompilationUnitEditor.error.saving.message2"), cx.getStatus()); //$NON-NLS-1$ //$NON-NLS-2$ } else { MessageDialog.openError(shell, JavaEditorMessages.getString("CompilationUnitEditor.error.saving.title3"), JavaEditorMessages.getString("CompilationUnitEditor.error.saving.message3") + t.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$ } } finally { provider.changed(newInput); if (success) setInput(newInput); } if (progressMonitor != null) progressMonitor.setCanceled(!success); } /* * @see AbstractTextEditor#doSetInput(IEditorInput) */ protected void doSetInput(IEditorInput input) throws CoreException { super.doSetInput(input); configureTabConverter(); } private void configureTabConverter() { if (fTabConverter != null) { IDocumentProvider provider= getDocumentProvider(); if (provider instanceof ICompilationUnitDocumentProvider) { ICompilationUnitDocumentProvider cup= (ICompilationUnitDocumentProvider) provider; fTabConverter.setLineTracker(cup.createLineTracker(getEditorInput())); } } } private int getTabSize() { Preferences preferences= JavaCore.getPlugin().getPluginPreferences(); return preferences.getInt(CODE_FORMATTER_TAB_SIZE); } private void startTabConversion() { if (fTabConverter == null) { fTabConverter= new TabConverter(); configureTabConverter(); fTabConverter.setNumberOfSpacesPerTab(getTabSize()); AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer(); asv.addTextConverter(fTabConverter); // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270 asv.updateIndentationPrefixes(); } } private void stopTabConversion() { if (fTabConverter != null) { AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer(); asv.removeTextConverter(fTabConverter); // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270 asv.updateIndentationPrefixes(); fTabConverter= null; } } private boolean isTabConversionEnabled() { IPreferenceStore store= getPreferenceStore(); return store.getBoolean(SPACES_FOR_TABS); } public void dispose() { ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer instanceof ITextViewerExtension) ((ITextViewerExtension) sourceViewer).removeVerifyKeyListener(fBracketInserter); if (fJavaEditorErrorTickUpdater != null) { fJavaEditorErrorTickUpdater.dispose(); fJavaEditorErrorTickUpdater= null; } if (fActionGroups != null) { fActionGroups.dispose(); fActionGroups= null; } super.dispose(); } /* * @see AbstractTextEditor#createPartControl(Composite) */ public void createPartControl(Composite parent) { super.createPartControl(parent); if (isTabConversionEnabled()) startTabConversion(); IPreferenceStore preferenceStore= getPreferenceStore(); boolean closeBrackets= preferenceStore.getBoolean(CLOSE_BRACKETS); boolean closeStrings= preferenceStore.getBoolean(CLOSE_STRINGS); fBracketInserter.setCloseBracketsEnabled(closeBrackets); fBracketInserter.setCloseStringsEnabled(closeStrings); ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer instanceof ITextViewerExtension) ((ITextViewerExtension) sourceViewer).prependVerifyKeyListener(fBracketInserter); } private static char getEscapeCharacter(char character) { switch (character) { case '"': case '\'': return '\\'; default: return 0; } } private static char getPeerCharacter(char character) { switch (character) { case '(': return ')'; case ')': return '('; case '[': return ']'; case ']': return '['; case '"': return character; case '\'': return character; default: throw new IllegalArgumentException(); } } /* * @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent) */ protected void handlePreferenceStoreChanged(PropertyChangeEvent event) { try { AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer(); if (asv != null) { String p= event.getProperty(); if (CLOSE_BRACKETS.equals(p)) { fBracketInserter.setCloseBracketsEnabled(getPreferenceStore().getBoolean(p)); return; } if (CLOSE_STRINGS.equals(p)) { fBracketInserter.setCloseStringsEnabled(getPreferenceStore().getBoolean(p)); return; } if (SPACES_FOR_TABS.equals(p)) { if (isTabConversionEnabled()) startTabConversion(); else stopTabConversion(); return; } if (PreferenceConstants.EDITOR_SMART_TAB.equals(p)) { if (getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SMART_TAB)) { setActionActivationCode("IndentOnTab", '\t', -1, SWT.NONE); //$NON-NLS-1$ } else { removeActionActivationCode("IndentOnTab"); //$NON-NLS-1$ } } IContentAssistant c= asv.getContentAssistant(); if (c instanceof ContentAssistant) ContentAssistPreference.changeConfiguration((ContentAssistant) c, getPreferenceStore(), event); } } finally { super.handlePreferenceStoreChanged(event); } } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor#handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent) */ protected void handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) { AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer(); if (asv != null) { String p= event.getProperty(); if (CODE_FORMATTER_TAB_SIZE.equals(p)) { asv.updateIndentationPrefixes(); if (fTabConverter != null) fTabConverter.setNumberOfSpacesPerTab(getTabSize()); } } super.handlePreferencePropertyChanged(event); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor#createJavaSourceViewer(org.eclipse.swt.widgets.Composite, org.eclipse.jface.text.source.IVerticalRuler, org.eclipse.jface.text.source.IOverviewRuler, boolean, int) */ protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean isOverviewRulerVisible, int styles) { return new AdaptedSourceViewer(parent, verticalRuler, overviewRuler, isOverviewRulerVisible, styles); } /* * @see IReconcilingParticipant#reconciled() */ public void reconciled() { if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE)) { Shell shell= getSite().getShell(); if (shell != null && !shell.isDisposed()) { shell.getDisplay().asyncExec(new Runnable() { public void run() { synchronizeOutlinePageSelection(); } }); } } } protected void updateStateDependentActions() { super.updateStateDependentActions(); fGenerateActionGroup.editorStateChanged(); } /** * Returns the updated java element for the old java element. */ private IJavaElement findElement(IJavaElement element) { if (element == null) return null; IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager(); ICompilationUnit unit= manager.getWorkingCopy(getEditorInput()); if (unit != null) { try { synchronized (unit) { unit.reconcile(); } IJavaElement[] findings= unit.findElements(element); if (findings != null && findings.length > 0) return findings[0]; } catch (JavaModelException x) { JavaPlugin.log(x.getStatus()); // nothing found, be tolerant and go on } } return null; } /** * Returns the offset of the given Java element. */ private int getOffset(IJavaElement element) { if (element instanceof ISourceReference) { ISourceReference sr= (ISourceReference) element; try { ISourceRange srcRange= sr.getSourceRange(); if (srcRange != null) return srcRange.getOffset(); } catch (JavaModelException e) { } } return -1; } /* * @see AbstractTextEditor#rememberSelection() */ protected void rememberSelection() { ISelectionProvider sp= getSelectionProvider(); fRememberedSelection= (sp == null ? null : (ITextSelection) sp.getSelection()); if (fRememberedSelection != null) { fRememberedElement= getElementAt(fRememberedSelection.getOffset(), true); fRememberedElementOffset= getOffset(fRememberedElement); } } /* * @see AbstractTextEditor#restoreSelection() */ protected void restoreSelection() { try { if (getSourceViewer() == null || fRememberedSelection == null) return; IJavaElement newElement= findElement(fRememberedElement); int newOffset= getOffset(newElement); int delta= (newOffset > -1 && fRememberedElementOffset > -1) ? newOffset - fRememberedElementOffset : 0; if (isValidSelection(delta + fRememberedSelection.getOffset(), fRememberedSelection.getLength())) selectAndReveal(delta + fRememberedSelection.getOffset(), fRememberedSelection.getLength()); } finally { fRememberedSelection= null; fRememberedElement= null; fRememberedElementOffset= -1; } } private boolean isValidSelection(int offset, int length) { IDocumentProvider provider= getDocumentProvider(); if (provider != null) { IDocument document= provider.getDocument(getEditorInput()); if (document != null) { int end= offset + length; int documentLength= document.getLength(); return 0 <= offset && offset <= documentLength && 0 <= end && end <= documentLength; } } return false; } /* * @see AbstractTextEditor#canHandleMove(IEditorInput, IEditorInput) */ protected boolean canHandleMove(IEditorInput originalElement, IEditorInput movedElement) { String oldExtension= ""; //$NON-NLS-1$ if (originalElement instanceof IFileEditorInput) { IFile file= ((IFileEditorInput) originalElement).getFile(); if (file != null) { String ext= file.getFileExtension(); if (ext != null) oldExtension= ext; } } String newExtension= ""; //$NON-NLS-1$ if (movedElement instanceof IFileEditorInput) { IFile file= ((IFileEditorInput) movedElement).getFile(); if (file != null) newExtension= file.getFileExtension(); } return oldExtension.equals(newExtension); } /* * @see org.eclipse.ui.texteditor.ExtendedTextEditor#isPrefQuickDiffAlwaysOn() */ protected boolean isPrefQuickDiffAlwaysOn() { // reestablishes the behaviour from ExtendedTextEditor which was hacked by JavaEditor // to disable the change bar for the class file (attached source) java editor. IPreferenceStore store= getPreferenceStore(); return store.getBoolean(ExtendedTextEditorPreferenceConstants.QUICK_DIFF_ALWAYS_ON); } }
38,471
Bug 38471 inline method: compile error (array related) [refactoring]
20030604 int y(int[] p){ return p[0]; } void yg(){ int x= y(new int[0]); } inline y you get int x= new int[0][0]; which does not type check
resolved fixed
029e2c4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-24T13:58:01Z
2003-06-05T10:46:40Z
org.eclipse.jdt.ui.tests.refactoring/resources/InlineMethodWorkspace/TestCases/argument_in/TestArray.java
38,471
Bug 38471 inline method: compile error (array related) [refactoring]
20030604 int y(int[] p){ return p[0]; } void yg(){ int x= y(new int[0]); } inline y you get int x= new int[0][0]; which does not type check
resolved fixed
029e2c4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-24T13:58:01Z
2003-06-05T10:46:40Z
org.eclipse.jdt.ui.tests.refactoring/resources/InlineMethodWorkspace/TestCases/argument_out/TestArray.java
38,471
Bug 38471 inline method: compile error (array related) [refactoring]
20030604 int y(int[] p){ return p[0]; } void yg(){ int x= y(new int[0]); } inline y you get int x= new int[0][0]; which does not type check
resolved fixed
029e2c4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-24T13:58:01Z
2003-06-05T10:46:40Z
org.eclipse.jdt.ui.tests.refactoring/test
38,471
Bug 38471 inline method: compile error (array related) [refactoring]
20030604 int y(int[] p){ return p[0]; } void yg(){ int x= y(new int[0]); } inline y you get int x= new int[0][0]; which does not type check
resolved fixed
029e2c4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-24T13:58:01Z
2003-06-05T10:46:40Z
cases/org/eclipse/jdt/ui/tests/refactoring/InlineMethodTests.java
38,471
Bug 38471 inline method: compile error (array related) [refactoring]
20030604 int y(int[] p){ return p[0]; } void yg(){ int x= y(new int[0]); } inline y you get int x= new int[0][0]; which does not type check
resolved fixed
029e2c4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-24T13:58:01Z
2003-06-05T10:46:40Z
org.eclipse.jdt.ui/core
38,471
Bug 38471 inline method: compile error (array related) [refactoring]
20030604 int y(int[] p){ return p[0]; } void yg(){ int x= y(new int[0]); } inline y you get int x= new int[0][0]; which does not type check
resolved fixed
029e2c4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-24T13:58:01Z
2003-06-05T10:46:40Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/CallInliner.java
43,595
Bug 43595 Javadoc formatter adds an extra line every time you format
20030924 Everytime you format a comment with a blank line another blank line is added. STEPS 1)Add a comment like this: /** * Get the progress monitor for a job. If it is a UIJob get the main * monitor from the status line. Otherwise get a background monitor. * * @return IProgressMonitor */ 2) Make a change in another method and format. It will look this this afterwards /** * Get the progress monitor for a job. If it is a UIJob get the main * monitor from the status line. Otherwise get a background monitor. * * * @return IProgressMonitor */
resolved fixed
e3c2521
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-26T07:16:00Z
2003-09-24T19:00:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/comment/CommentRegion.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 java.util.Iterator; import java.util.LinkedList; import java.util.Map; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.graphics.GC; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.BadPositionCategoryException; import org.eclipse.jface.text.ConfigurableLineTracker; import org.eclipse.jface.text.DefaultPositionUpdater; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.ILineTracker; import org.eclipse.jface.text.IPositionUpdater; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.TypedPosition; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.jdt.ui.PreferenceConstants; /** * Comment region in a source code document. * * @since 3.0 */ public class CommentRegion extends TypedPosition implements IHtmlTagConstants, IBorderAttributes { /** Position category of comment regions */ protected static final String COMMENT_POSITION_CATEGORY= "__comment_position"; //$NON-NLS-1$ /** Default line prefix length */ public static final int COMMENT_PREFIX_LENGTH= 3; /** Default range delimiter */ protected static final String COMMENT_RANGE_DELIMITER= " "; //$NON-NLS-1$ /** The borders of this range */ private int fBorders= 0; /** Should all blank lines be cleared during formatting? */ private final boolean fClearBlankLines; /** The line delimiter used in this comment region */ private final String fDelimiter; /** The document to format */ private final IDocument fDocument; /** Graphics context for non-monospace fonts */ private final GC fGraphics; /** The sequence of lines in this comment region */ private final LinkedList fLines= new LinkedList(); /** The sequence of comment ranges in this comment region */ private final LinkedList fRanges= new LinkedList(); /** Is this comment region a single line region? */ private final boolean fSingleLine; /** The comment formatting strategy for this comment region */ private final CommentFormattingStrategy fStrategy; /** Number of characters representing tabulator */ private final int fTabs; /** * Creates a new comment region. * * @param strategy The comment formatting strategy used to format this comment region * @param position The typed position which forms this comment region * @param delimiter The line delimiter to use in this comment region */ protected CommentRegion(final CommentFormattingStrategy strategy, final TypedPosition position, final String delimiter) { super(position.getOffset(), position.getLength(), position.getType()); fStrategy= strategy; fDelimiter= delimiter; fClearBlankLines= fStrategy.getPreferences().get(PreferenceConstants.FORMATTER_COMMENT_CLEARBLANKLINES) == IPreferenceStore.TRUE; final ISourceViewer viewer= strategy.getViewer(); fDocument= viewer.getDocument(); final StyledText text= viewer.getTextWidget(); fGraphics= new GC(text); fGraphics.setFont(text.getFont()); fTabs= text.getTabs(); final ILineTracker tracker= new ConfigurableLineTracker(new String[] { delimiter }); IRegion range= null; CommentLine line= null; tracker.set(getText(0, getLength())); final int lines= tracker.getNumberOfLines(); fSingleLine= lines == 1; try { for (int index= 0; index < lines; index++) { range= tracker.getLineInformation(index); line= CommentObjectFactory.createLine(this); line.append(CommentObjectFactory.createRange(this, range.getOffset(), range.getLength())); fLines.add(line); } } catch (BadLocationException exception) { // Should not happen } } /** * Appends the comment range to this comment region. * * @param range Comment range to append to this comment region */ protected void append(final CommentRange range) { fRanges.add(range); } /** * Applies the formatted comment region to the underlying document. * * @param indentation Indentation of the formatted comment region * @param length The maximal length of text in this comment region measured in average character widths */ protected void applyRegion(final String indentation, final int length) { final int last= fLines.size() - 1; if (last >= 0) { CommentLine previous= null; CommentLine next= (CommentLine)fLines.get(last); CommentRange range= next.getLast(); next.applyEnd(range, indentation, length); for (int line= last; line >= 0; line--) { previous= next; next= (CommentLine)fLines.get(line); range= next.applyLine(previous, range, indentation, line); } next.applyStart(range, indentation, length); } } /** * Applies the changed content to the underlying document * * @param change Text content to apply to the underlying document * @param offset Offset measured in comment region coordinates where to apply the changed content * @param length Length of the content to be changed */ protected final void applyText(final String change, final int offset, final int length) { try { final int base= getOffset() + offset; final String content= fDocument.get(base, length); if (!change.equals(content)) fDocument.replace(getOffset() + offset, length, change); } catch (BadLocationException exception) { // Should not happen } } /** * Can the comment range be appended to the comment line? * * @param line Comment line where to append the comment range * @param previous Comment range which is the predecessor of the current comment range * @param next Comment range to test whether it can be appended to the comment line * @param space Amount of space in the comment line used by already inserted comment ranges * @param length The maximal length of text in this comment region measured in average character widths * @return <code>true</code> iff the comment range can be added to the line, <code>false</code> otherwise */ protected boolean canAppend(final CommentLine line, final CommentRange previous, final CommentRange next, final int space, final int length) { return space == 0 || space + next.getLength() < length; } /** * Can the two current comment ranges be applied to the underlying document? * * @param previous Previous comment range which was already applied * @param next Next comment range to be applied * @return <code>true</code> iff the next comment range can be applied, <code>false</code> otherwise */ protected boolean canApply(final CommentRange previous, final CommentRange next) { return true; } /** * Finalizes the comment region and adjusts its starting indentation. * * @param indentation Indentation of the formatted comment region */ protected void finalizeRegion(final String indentation) { // Do nothing } /** * Formats the comment region. * * @param indentation Indentation of the formatted comment region */ public void format(String indentation) { final IDocument document= getDocument(); final Map preferences= getStrategy().getPreferences(); int margin= 80; try { margin= Integer.parseInt(preferences.get(PreferenceConstants.FORMATTER_COMMENT_LINELENGTH).toString()); } catch (Exception exception) { // Do nothing } margin= Math.max(COMMENT_PREFIX_LENGTH + 1, margin - stringToLength(indentation) - COMMENT_PREFIX_LENGTH); document.addPositionCategory(COMMENT_POSITION_CATEGORY); final IPositionUpdater positioner= new DefaultPositionUpdater(COMMENT_POSITION_CATEGORY); document.addPositionUpdater(positioner); try { initializeRegion(); markRegion(); wrapRegion(margin); applyRegion(indentation, margin); finalizeRegion(indentation); } finally { if (fGraphics != null && !fGraphics.isDisposed()) fGraphics.dispose(); try { document.removePositionCategory(COMMENT_POSITION_CATEGORY); document.removePositionUpdater(positioner); } catch (BadPositionCategoryException exception) { // Should not happen } } } /** * Returns the general line delimiter used in this comment region. * * @return The line delimiter for this comment region */ protected final String getDelimiter() { return fDelimiter; } /** * Returns the line delimiter used in this comment line break. * * @param predecessor The predecessor comment line before the line break * @param successor The successor comment line after the line break * @param previous The comment range after the line break * @param next The comment range before the line break * @param indentation Indentation of the formatted line break * @return The line delimiter for this comment line break */ protected String getDelimiter(final CommentLine predecessor, final CommentLine successor, final CommentRange previous, final CommentRange next, final String indentation) { return fDelimiter + indentation + successor.getContentPrefix(); } /** * Returns the range delimiter for this comment range break in this comment region. * * @param previous The previous comment range to the right of the range delimiter * @param next The next comment range to the left of the range delimiter * @return The delimiter for this comment range break */ protected String getDelimiter(final CommentRange previous, final CommentRange next) { return COMMENT_RANGE_DELIMITER; } /** * Returns the document of this comment region. * * @return The document of this region */ protected final IDocument getDocument() { return fDocument; } /** * Returns the list of comment ranges in this comment region * * @return The list of comment ranges in this region */ protected final LinkedList getRanges() { return fRanges; } /** * Returns the number of comment lines in this comment region. * * @return The number of lines in this comment region */ protected final int getSize() { return fLines.size(); } /** * Returns the comment formatting strategy used to format this comment region. * * @return The formatting strategy for this comment region */ public final CommentFormattingStrategy getStrategy() { return fStrategy; } /** * Returns the text of this comment region in the indicated range. * * @param offset The offset of the comment range to retrieve in comment region coordinates * @param length The length of the comment range to retrieve * @return The content of this comment region in the indicated range */ protected final String getText(final int offset, final int length) { String content= ""; //$NON-NLS-1$ try { content= getDocument().get(getOffset() + offset, length); } catch (BadLocationException exception) { // Should not happen } return content; } /** * Does the border <code>border</code> exist? * * @param border The type of the border. Must be a border attribute of <code>CommentRegion</code>. * @return <code>true</code> iff this border exists, <code>false</code> otherwise. */ protected final boolean hasBorder(final int border) { return (fBorders & border) == border; } /** * Initializes the internal representation of the comment region. */ protected void initializeRegion() { try { getDocument().addPosition(COMMENT_POSITION_CATEGORY, this); } catch (BadLocationException exception) { // Should not happen } catch (BadPositionCategoryException exception) { // Should not happen } int index= 0; CommentLine line= null; for (final Iterator iterator= fLines.iterator(); iterator.hasNext(); index++) { line= (CommentLine)iterator.next(); line.scanLine(index); line.tokenizeLine(index); } } /** * Should blank lines be cleared during formatting? * * @return <code>true</code> iff blank lines should be cleared, <code>false</code> otherwise */ protected final boolean isClearBlankLines() { return fClearBlankLines; } /** * Is the current comment range a word? * * @param current Comment range to test whether it is a word * @return <code>true</code> iff the comment range is a word, <code>false</code> otherwise. */ protected final boolean isCommentWord(final CommentRange current) { final String token= getText(current.getOffset(), current.getLength()); for (int offset= 0; offset < token.length(); offset++) { if (!Character.isLetterOrDigit(token.charAt(offset))) return false; } return true; } /** * Is this comment region a single line region? * * @return <code>true</code> iff this region is single line, <code>false</code> otherwise. */ protected final boolean isSingleLine() { return fSingleLine; } /** * Marks the attributed ranges in this comment region. */ protected void markRegion() { // Do nothing } /** * Set the border <code>border</code> to true. * * @param border The type of the border. Must be a border attribute of <code>CommentRegion</code>. */ protected final void setBorder(final int border) { fBorders |= border; } /** * Returns the indentation string for a reference string * * @param reference The reference string to get the indentation string for * @param tabs <code>true</code> iff the indent should use tabs, <code>false</code> otherwise. * @return The indentation string */ protected String stringToIndent(final String reference, final boolean tabs) { final int pixels= stringToPixels(reference); final int space= fGraphics.stringExtent(" ").x; //$NON-NLS-1$ final StringBuffer buffer= new StringBuffer(); final int spaces= pixels / space; if (tabs) { final int count= spaces / fTabs; final int modulo= spaces % fTabs; for (int index= 0; index < count; index++) buffer.append('\t'); for (int index= 0; index < modulo; index++) buffer.append(' '); } else { for (int index= 0; index < spaces; index++) buffer.append(' '); } return buffer.toString(); } /** * Returns the length of the reference string in characters. * * @param reference The reference string to get the length * @return The length of the string in characters */ protected int stringToLength(final String reference) { int tabs= 0; int length= reference.length(); for (int offset= 0; offset < length; offset++) { if (reference.charAt(offset) == '\t') tabs++; } length += tabs * (fTabs - 1); return length; } /** * Returns the width of the reference string in pixels. * * @param reference The reference string to get the width * @return The width of the string in pixels */ protected int stringToPixels(final String reference) { final StringBuffer buffer= new StringBuffer(); char character= 0; for (int offset= 0; offset < reference.length(); offset++) { character= reference.charAt(offset); if (character == '\t') { for (int tab= 0; tab < fTabs; tab++) buffer.append(' '); } else buffer.append(character); } return fGraphics.stringExtent(buffer.toString()).x; } /** * Wraps the comment ranges in this comment region into comment lines. * * @param length The maximal length of text in this comment region measured in average character widths */ protected void wrapRegion(final int length) { fLines.clear(); int offset= 0; CommentLine successor= null; CommentLine predecessor= null; CommentRange previous= null; CommentRange next= null; while (!fRanges.isEmpty()) { offset= 0; predecessor= successor; successor= CommentObjectFactory.createLine(this); if (predecessor != null) successor.adapt(predecessor); fLines.add(successor); while (!fRanges.isEmpty()) { next= (CommentRange)fRanges.getFirst(); if (canAppend(successor, previous, next, offset, length)) { fRanges.removeFirst(); successor.append(next); offset += (next.getLength() + 1); previous= next; } else break; } } } }
43,595
Bug 43595 Javadoc formatter adds an extra line every time you format
20030924 Everytime you format a comment with a blank line another blank line is added. STEPS 1)Add a comment like this: /** * Get the progress monitor for a job. If it is a UIJob get the main * monitor from the status line. Otherwise get a background monitor. * * @return IProgressMonitor */ 2) Make a change in another method and format. It will look this this afterwards /** * Get the progress monitor for a job. If it is a UIJob get the main * monitor from the status line. Otherwise get a background monitor. * * * @return IProgressMonitor */
resolved fixed
e3c2521
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-26T07:16:00Z
2003-09-24T19:00:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/comment/JavaDocLine.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; /** * Javadoc comment line in a comment region. * * @since 3.0 */ public class JavaDocLine extends MultiCommentLine implements IJavaDocAttributes { /** Line prefix of javadoc start lines */ public static final String JAVADOC_START_PREFIX= "/**"; //$NON-NLS-1$ /** The reference indentation of this line */ private String fReference= ""; //$NON-NLS-1$ /** * Creates a new javadoc line. * * @param region Comment region to create the line for */ protected JavaDocLine(final CommentRegion region) { super(region); } /* * @see org.eclipse.jdt.internal.ui.text.comment.CommentLine#adaptLine(org.eclipse.jdt.internal.ui.text.comment.CommentLine) */ protected void adapt(final CommentLine previous) { if (!hasAttribute(JAVADOC_ROOT) && !hasAttribute(JAVADOC_PARAMETER)) fReference= previous.getReference(); } /* * @see org.eclipse.jdt.internal.ui.text.comment.CommentLine#append(org.eclipse.jdt.internal.ui.text.comment.CommentRange) */ protected void append(final CommentRange range) { final JavaDocRegion parent= (JavaDocRegion)getParent(); if (range.hasAttribute(JAVADOC_PARAMETER)) setAttribute(JAVADOC_PARAMETER); else if (range.hasAttribute(JAVADOC_ROOT)) setAttribute(JAVADOC_ROOT); final int ranges= getSize(); if (ranges == 1) { final CommentRange first= getFirst(); final String common= getParent().getText(first.getOffset(), first.getLength()) + CommentRegion.COMMENT_RANGE_DELIMITER; if (hasAttribute(JAVADOC_ROOT)) fReference= common; else if (hasAttribute(JAVADOC_PARAMETER)) { if (parent.isIndentRootDescriptions()) fReference= common + " "; //$NON-NLS-1$ else fReference= common; } } super.append(range); } /* * @see org.eclipse.jdt.internal.ui.text.comment.CommentLine#applyStart(org.eclipse.jdt.internal.ui.text.comment.CommentRange, java.lang.String, int) */ protected void applyStart(final CommentRange range, final String indentation, final int length) { final CommentRegion parent= getParent(); if (parent.isSingleLine() && parent.getSize() == 1) { parent.applyText(getStartingPrefix() + CommentRegion.COMMENT_RANGE_DELIMITER, 0, range.getOffset()); } else super.applyStart(range, indentation, length); } /* * @see org.eclipse.jdt.internal.ui.text.comment.CommentLine#getReference() */ protected String getReference() { return fReference; } /* * @see org.eclipse.jdt.internal.ui.text.comment.CommentLine#getStartingPrefix() */ protected String getStartingPrefix() { return JAVADOC_START_PREFIX; } }
43,595
Bug 43595 Javadoc formatter adds an extra line every time you format
20030924 Everytime you format a comment with a blank line another blank line is added. STEPS 1)Add a comment like this: /** * Get the progress monitor for a job. If it is a UIJob get the main * monitor from the status line. Otherwise get a background monitor. * * @return IProgressMonitor */ 2) Make a change in another method and format. It will look this this afterwards /** * Get the progress monitor for a job. If it is a UIJob get the main * monitor from the status line. Otherwise get a background monitor. * * * @return IProgressMonitor */
resolved fixed
e3c2521
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-26T07:16:00Z
2003-09-24T19:00:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/comment/JavaDocRegion.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 java.util.Iterator; import java.util.Map; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.BadPositionCategoryException; import org.eclipse.jface.text.ConfigurableLineTracker; import org.eclipse.jface.text.DefaultPositionUpdater; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.ILineTracker; import org.eclipse.jface.text.IPositionUpdater; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.TypedPosition; import org.eclipse.jface.text.formatter.ContentFormatter; import org.eclipse.jface.text.formatter.FormattingContextProperties; import org.eclipse.jface.text.formatter.IFormattingContext; import org.eclipse.jdt.ui.PreferenceConstants; /** * Javadoc region in a source code document. * * @since 3.0 */ public class JavaDocRegion extends MultiCommentRegion implements IJavaDocAttributes, IJavaDocTagConstants { /** Position category of javadoc code ranges */ protected static final String CODE_POSITION_CATEGORY= "__javadoc_code_position"; //$NON-NLS-1$ /** Should source code regions be formatted? */ private final boolean fFormatSource; /** Should root tag parameter descriptions be indented? */ private final boolean fIndentRootDescriptions; /** Should root tag paragraphs be indented? */ private final boolean fIndentRootTags; /** Should description of parameters go to the next line? */ private final boolean fParameterNewLine; /** Should root tags be separated from description? */ private boolean fSeparateRootTags; /** * Creates a new javadoc region. * * @param strategy The comment formatting strategy used to format this comment region * @param position The typed position which forms this javadoc region * @param delimiter The line delimiter to use in this javadoc region */ protected JavaDocRegion(final CommentFormattingStrategy strategy, final TypedPosition position, final String delimiter) { super(strategy, position, delimiter); final Map preferences= getStrategy().getPreferences(); fFormatSource= preferences.get(PreferenceConstants.FORMATTER_COMMENT_FORMATSOURCE) == IPreferenceStore.TRUE; fIndentRootTags= preferences.get(PreferenceConstants.FORMATTER_COMMENT_INDENTROOTTAGS) == IPreferenceStore.TRUE; fSeparateRootTags= preferences.get(PreferenceConstants.FORMATTER_COMMENT_SEPARATEROOTTAGS) == IPreferenceStore.TRUE; fParameterNewLine= preferences.get(PreferenceConstants.FORMATTER_COMMENT_NEWLINEFORPARAMETER) == IPreferenceStore.TRUE; fIndentRootDescriptions= preferences.get(PreferenceConstants.FORMATTER_COMMENT_INDENTPARAMETERDESCRIPTION) == IPreferenceStore.TRUE; } /* * @see org.eclipse.jdt.internal.ui.text.comment.CommentRegion#applyRegion(java.lang.String, int) */ protected void applyRegion(final String indentation, final int length) { super.applyRegion(indentation, length); if (fFormatSource) { final ContentFormatter formatter= getStrategy().getFormatter(); try { final IDocument document= getDocument(); final Position[] positions= document.getPositions(CODE_POSITION_CATEGORY); if (positions.length > 0) { int begin= 0; int end= 0; final IFormattingContext context= new CommentFormattingContext(); context.setProperty(FormattingContextProperties.CONTEXT_DOCUMENT, Boolean.valueOf(false)); context.setProperty(FormattingContextProperties.CONTEXT_PREFERENCES, getStrategy().getPreferences()); for (int position= 0; position < positions.length - 1; position++) { begin= positions[position++].getOffset(); end= positions[position].getOffset(); context.setProperty(FormattingContextProperties.CONTEXT_PARTITION, new TypedPosition(begin, end - begin, IDocument.DEFAULT_CONTENT_TYPE)); formatter.format(document, context); } } } catch (BadPositionCategoryException exception) { // Should not happen } } } /* * @see org.eclipse.jdt.internal.ui.text.comment.CommentRegion#canAppend(org.eclipse.jdt.internal.ui.text.comment.CommentLine, org.eclipse.jdt.internal.ui.text.comment.CommentRange, org.eclipse.jdt.internal.ui.text.comment.CommentRange, int, int) */ protected boolean canAppend(final CommentLine line, final CommentRange previous, final CommentRange next, final int offset, int length) { final boolean blank= next.hasAttribute(COMMENT_BLANKLINE); if (next.getLength() <= 2 && !blank && !isCommentWord(next)) return true; if (fParameterNewLine && line.hasAttribute(JAVADOC_PARAMETER) && line.getSize() > 1) return false; if (previous != null) { if (offset != 0 && (blank || previous.hasAttribute(COMMENT_BLANKLINE) || next.hasAttribute(JAVADOC_PARAMETER) || next.hasAttribute(JAVADOC_ROOT) || next.hasAttribute(JAVADOC_SEPARATOR) || next.hasAttribute(COMMENT_NEWLINE) || previous.hasAttribute(COMMENT_BREAK) || previous.hasAttribute(JAVADOC_SEPARATOR))) return false; if (next.hasAttribute(JAVADOC_IMMUTABLE) && previous.hasAttribute(JAVADOC_IMMUTABLE)) return true; } if (fIndentRootTags && !line.hasAttribute(JAVADOC_ROOT) && !line.hasAttribute(JAVADOC_PARAMETER)) length -= stringToLength(line.getReference()); return super.canAppend(line, previous, next, offset, length); } /* * @see org.eclipse.jdt.internal.ui.text.comment.CommentRegion#canApply(org.eclipse.jdt.internal.ui.text.comment.CommentRange, org.eclipse.jdt.internal.ui.text.comment.CommentRange) */ protected boolean canApply(final CommentRange previous, final CommentRange next) { if (previous != null) { final boolean isCurrentCode= next.hasAttribute(JAVADOC_CODE); final boolean isLastCode= previous.hasAttribute(JAVADOC_CODE); try { final int offset= getOffset(); final IDocument document= getDocument(); if (!isLastCode && isCurrentCode) document.addPosition(CODE_POSITION_CATEGORY, new Position(offset + next.getOffset() + next.getLength())); else if (isLastCode && !isCurrentCode) document.addPosition(CODE_POSITION_CATEGORY, new Position(offset + previous.getOffset())); } catch (BadLocationException exception) { // Should not happen } catch (BadPositionCategoryException exception) { // Should not happen } if (previous.hasAttribute(JAVADOC_IMMUTABLE) && next.hasAttribute(JAVADOC_IMMUTABLE) && !isLastCode) return false; } return true; } /* * @see org.eclipse.jdt.internal.ui.text.comment.CommentRegion#finishRegion(java.lang.String) */ protected void finalizeRegion(final String indentation) { final String test= indentation + MultiCommentLine.MULTI_COMMENT_CONTENT_PREFIX; final StringBuffer buffer= new StringBuffer(); buffer.append(test); buffer.append(' '); final String delimiter= buffer.toString(); try { final ILineTracker tracker= new ConfigurableLineTracker(new String[] { getDelimiter()}); tracker.set(getText(0, getLength())); int index= 0; String content= null; IRegion range= null; for (int line= tracker.getNumberOfLines() - 3; line >= 1; line--) { range= tracker.getLineInformation(line); index= range.getOffset(); content= getText(index, range.getLength()); if (!content.startsWith(test)) applyText(delimiter, index, 0); } } catch (BadLocationException exception) { // Should not happen } } /* * @see org.eclipse.jdt.internal.ui.text.comment.CommentRegion#formatRegion(java.lang.String) */ public void format(final String indentation) { IPositionUpdater updater= null; final IDocument document= getDocument(); if (fFormatSource) { document.addPositionCategory(CODE_POSITION_CATEGORY); updater= new DefaultPositionUpdater(CODE_POSITION_CATEGORY); document.addPositionUpdater(updater); } super.format(indentation); if (fFormatSource) { try { document.removePositionCategory(CODE_POSITION_CATEGORY); document.removePositionUpdater(updater); } catch (BadPositionCategoryException exception) { // Should not happen } } } /* * @see org.eclipse.jdt.internal.ui.text.comment.CommentRegion#getDelimiter(org.eclipse.jdt.internal.ui.text.comment.CommentLine, org.eclipse.jdt.internal.ui.text.comment.CommentLine, org.eclipse.jdt.internal.ui.text.comment.CommentRange, org.eclipse.jdt.internal.ui.text.comment.CommentRange, java.lang.String) */ protected String getDelimiter(final CommentLine predecessor, final CommentLine successor, final CommentRange previous, final CommentRange next, final String indentation) { final String delimiter= super.getDelimiter(predecessor, successor, previous, next, indentation); if (previous != null) { if (previous.hasAttribute(JAVADOC_IMMUTABLE | JAVADOC_SEPARATOR) && !next.hasAttribute(JAVADOC_CODE)) return delimiter + delimiter; else if (previous.hasAttribute(JAVADOC_CODE) && !next.hasAttribute(JAVADOC_CODE)) return getDelimiter(); else if (next.hasAttribute(JAVADOC_IMMUTABLE | JAVADOC_SEPARATOR) || previous.hasAttribute(JAVADOC_PARAGRAPH)) return delimiter + delimiter; else if (fIndentRootTags && !predecessor.hasAttribute(JAVADOC_ROOT) && !predecessor.hasAttribute(JAVADOC_PARAMETER)) return delimiter + stringToIndent(predecessor.getReference(), false); } return delimiter; } /* * @see org.eclipse.jdt.internal.ui.text.comment.CommentRegion#getDelimiter(org.eclipse.jdt.internal.ui.text.comment.CommentRange, org.eclipse.jdt.internal.ui.text.comment.CommentRange) */ protected String getDelimiter(final CommentRange previous, final CommentRange next) { if (previous != null) { if (previous.hasAttribute(COMMENT_HTML) && next.hasAttribute(COMMENT_HTML)) return ""; //$NON-NLS-1$ else if (next.hasAttribute(COMMENT_OPEN) || previous.hasAttribute(COMMENT_HTML | COMMENT_CLOSE)) return ""; //$NON-NLS-1$ else if (!next.hasAttribute(JAVADOC_CODE) && previous.hasAttribute(JAVADOC_CODE)) return ""; //$NON-NLS-1$ else if (next.hasAttribute(COMMENT_CLOSE) && previous.getLength() <= 2 && !isCommentWord(previous)) return ""; //$NON-NLS-1$ else if (previous.hasAttribute(COMMENT_OPEN) && next.getLength() <= 2 && !isCommentWord(next)) return ""; //$NON-NLS-1$ } return super.getDelimiter(previous, next); } /** * Should inline source code be formatted? * * @return <code>true</code> iff the code should be formatted, <code>false</code> otherwise. */ protected final boolean isFormatSource() { return fFormatSource; } /** * Should parameter descriptions be indented from their parameter? * * @return <code>true</code> iff the descriptions should be indented, <code>false</code> otherwise. */ protected final boolean isIndentRootDescriptions() { return fIndentRootDescriptions; } /** * Should javadoc root tags be indented? * * @return <code>true</code> iff the root tags should be indented, <code>false</code> otherwise. */ protected final boolean isIndentRootTags() { return fIndentRootTags; } /** * Should the formatter insert a new line after javadoc parameters? * * @return <code>true</code> iff a new line should be inserted, <code>false</code> otherwise. */ protected final boolean isParameterNewLine() { return fParameterNewLine; } /** * Should javadoc root tags be separated from the rest of the comment? * * @return <code>true</code> iff the root tags should be separated, <code>false</code> otherwise. */ protected final boolean isSeparateRootTags() { return fSeparateRootTags; } /** * Marks attributed ranges in this javadoc region. * * @param tags The html tags which confine the attributed ranges * @param key The key of the attribute to set when an attributed range has been recognized * @param html <code>true</code> iff html tags in this attributed range should be attributed too, <code>false</code> otherwise */ protected void markRanges(final String[] tags, final int key, final boolean html) { int level= 0; int length= 0; String token= null; JavaDocRange current= null; for (int index= 0; index < tags.length; index++) { level= 0; for (final Iterator iterator= getRanges().iterator(); iterator.hasNext();) { current= (JavaDocRange)iterator.next(); length= current.getLength(); if (length > 0) { token= getText(current.getOffset(), current.getLength()); level= current.markRange(token, tags[index], level, key, html); } } } } /* * @see org.eclipse.jdt.internal.ui.text.comment.CommentRegion#markRegion() */ protected void markRegion() { int length= 0; String token= null; JavaDocRange range= null; for (final Iterator iterator= getRanges().iterator(); iterator.hasNext();) { range= (JavaDocRange)iterator.next(); length= range.getLength(); if (length > 0) { token= getText(range.getOffset(), length).toLowerCase(); range.markJavadocTag(JAVADOC_PARAM_TAGS, token, JAVADOC_PARAMETER); range.markJavadocTag(JAVADOC_ROOT_TAGS, token, JAVADOC_ROOT); if (fSeparateRootTags && (range.hasAttribute(JAVADOC_ROOT) || range.hasAttribute(JAVADOC_PARAMETER))) { range.setAttribute(JAVADOC_PARAGRAPH); fSeparateRootTags= false; } if (range.hasAttribute(COMMENT_HTML)) { range.markHtmlTag(JAVADOC_SEPARATOR_TAGS, token, JAVADOC_SEPARATOR, true, true); range.markHtmlTag(JAVADOC_BREAK_TAGS, token, COMMENT_BREAK, false, true); range.markHtmlTag(JAVADOC_NEWLINE_TAGS, token, COMMENT_NEWLINE, true, false); range.markHtmlTag(JAVADOC_IMMUTABLE_TAGS, token, JAVADOC_IMMUTABLE, true, true); } } } markRanges(JAVADOC_IMMUTABLE_TAGS, JAVADOC_IMMUTABLE, true); if (fFormatSource) markRanges(JAVADOC_CODE_TAGS, JAVADOC_CODE, false); } }
43,761
Bug 43761 Implemented Interfaces Selection dialog behavior
a) Add two interfaces. -> Two interfaces have been added to the list box on the "New Java Class" dialog. Close the dialog via the x in the upper right hand corner. -> Two interfaces have been added. b) Add two interfaces. -> Two interfaces have been added to the list box on the "New Java Class" dialog. Close the dialog via "Cancel". -> Both interfaces will not be added. @@@@ Shouldn't closing the dialog equate to a "Cancel"?
closed fixed
90547f0
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-29T09:47:58Z
2003-09-26T18:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/SuperInterfaceSelectionDialog.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.wizards; import java.util.List; import org.eclipse.core.runtime.IStatus; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.operation.IRunnableContext; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.search.IJavaSearchConstants; import org.eclipse.jdt.core.search.IJavaSearchScope; import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.internal.corext.util.TypeInfo; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.TypeSelectionDialog; import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField; public class SuperInterfaceSelectionDialog extends TypeSelectionDialog { private static final int ADD_ID= IDialogConstants.CLIENT_ID + 1; private ListDialogField fList; private List fOldContent; public SuperInterfaceSelectionDialog(Shell parent, IRunnableContext context, ListDialogField list, IJavaProject p) { super(parent, context, IJavaSearchConstants.INTERFACE, createSearchScope(p)); fList= list; // to restore the content of the dialog field if the dialog is canceled fOldContent= fList.getElements(); setStatusLineAboveButtons(true); } /* * @see Dialog#createButtonsForButtonBar */ protected void createButtonsForButtonBar(Composite parent) { createButton(parent, ADD_ID, NewWizardMessages.getString("SuperInterfaceSelectionDialog.addButton.label"), true); //$NON-NLS-1$ super.createButtonsForButtonBar(parent); } /* * @see Dialog#cancelPressed */ protected void cancelPressed() { fList.setElements(fOldContent); super.cancelPressed(); } /* * @see Dialog#buttonPressed */ protected void buttonPressed(int buttonId) { if (buttonId == ADD_ID){ addSelectedInterface(); } super.buttonPressed(buttonId); } /* * @see Dialog#okPressed */ protected void okPressed() { addSelectedInterface(); super.okPressed(); } private void addSelectedInterface(){ Object ref= getLowerSelectedElement(); if (ref instanceof TypeInfo) { String qualifiedName= ((TypeInfo) ref).getFullyQualifiedName(); fList.addElement(qualifiedName); String message= NewWizardMessages.getFormattedString("SuperInterfaceSelectionDialog.interfaceadded.info", qualifiedName); //$NON-NLS-1$ updateStatus(new StatusInfo(IStatus.INFO, message)); } } private static IJavaSearchScope createSearchScope(IJavaProject p) { return SearchEngine.createJavaSearchScope(new IJavaProject[] { p }); } /* * @see AbstractElementListSelectionDialog#handleDefaultSelected() */ protected void handleDefaultSelected() { if (validateCurrentSelection()) buttonPressed(ADD_ID); } /* * @see org.eclipse.jface.window.Window#configureShell(Shell) */ protected void configureShell(Shell newShell) { super.configureShell(newShell); WorkbenchHelp.setHelp(newShell, IJavaHelpContextIds.SUPER_INTERFACE_SELECTION_DIALOG); } }
43,766
Bug 43766 [reconciling] ResourceMarkerAnnotationModel listener taking a long time
Build: I20030925 I was investigating a situation where adding breakpoints to a large file was very slow. It can take up to a second to add a breakpoint to a file such as Workspace.java (2000 lines). Almost all of this time is in the resource change listener added by ResourceMarkerAnnotationModel. First, a minor issue: Instead of adding a resource change listener that traverses the entire delta, you can locate a given resource delta within the resource change delta very quickly using IResourceDelta.findMember(): public void resourceChanged(IResourceChangeEvent e) { IResourceDelta delta= e.getDelta(); if (delta != null) { IResourceDelta child = delta.findMember(fResource.getFullPath()); if (child != null) update(child.getMarkerDeltas()); } } However, this was only a small speed improvement. The main problem is that the entire compilation unit is reparsed every time a breakpoint is added. I have added a profiler trace of where the time is going for adding a single breakpoint.
resolved fixed
17aa847
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-29T15:13:12Z
2003-09-26T18:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/filebuffers/CompilationUnitDocumentProvider2.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.javaeditor.filebuffers; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IMarkerDelta; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.Display; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.ListenerList; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.DefaultLineTracker; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.ILineTracker; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.source.Annotation; import org.eclipse.jface.text.source.AnnotationModelEvent; import org.eclipse.jface.text.source.IAnnotationModel; import org.eclipse.jface.text.source.IAnnotationModelListener; import org.eclipse.jface.text.source.IAnnotationModelListenerExtension; import org.eclipse.ui.editors.text.TextFileDocumentProvider; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.texteditor.AbstractMarkerAnnotationModel; import org.eclipse.ui.texteditor.IAnnotationExtension; import org.eclipse.ui.texteditor.MarkerAnnotation; import org.eclipse.ui.texteditor.ResourceMarkerAnnotationModel; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IProblemRequestor; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.compiler.IProblem; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitAnnotationModelEvent; import org.eclipse.jdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider; import org.eclipse.jdt.internal.ui.javaeditor.IJavaAnnotation; import org.eclipse.jdt.internal.ui.javaeditor.ISavePolicy; import org.eclipse.jdt.internal.ui.javaeditor.JavaMarkerAnnotation; import org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionProcessor; import org.eclipse.jdt.internal.ui.text.java.IProblemRequestorExtension; public class CompilationUnitDocumentProvider2 extends TextFileDocumentProvider implements ICompilationUnitDocumentProvider { /** * Bundle of all required informations to allow working copy management. */ static protected class CompilationUnitInfo extends FileInfo { public ICompilationUnit fCopy; } /** * Annotation representating an <code>IProblem</code>. */ static protected class ProblemAnnotation extends Annotation implements IJavaAnnotation, IAnnotationExtension { private static final String TASK_ANNOTATION_TYPE= "org.eclipse.ui.workbench.texteditor.task"; //$NON-NLS-1$ private static final String ERROR_ANNOTATION_TYPE= "org.eclipse.ui.workbench.texteditor.error"; //$NON-NLS-1$ private static final String WARNING_ANNOTATION_TYPE= "org.eclipse.ui.workbench.texteditor.warning"; //$NON-NLS-1$ private static final String INFO_ANNOTATION_TYPE= "org.eclipse.ui.workbench.texteditor.info"; //$NON-NLS-1$ private static Image fgQuickFixImage; private static Image fgQuickFixErrorImage; private static boolean fgQuickFixImagesInitialized= false; private ICompilationUnit fCompilationUnit; private List fOverlaids; private IProblem fProblem; private Image fImage; private boolean fQuickFixImagesInitialized= false; private String fType; public ProblemAnnotation(IProblem problem, ICompilationUnit cu) { fProblem= problem; fCompilationUnit= cu; setLayer(MarkerAnnotation.PROBLEM_LAYER + 1); if (IProblem.Task == fProblem.getID()) fType= TASK_ANNOTATION_TYPE; else if (fProblem.isWarning()) fType= WARNING_ANNOTATION_TYPE; else if (fProblem.isError()) fType= ERROR_ANNOTATION_TYPE; else fType= INFO_ANNOTATION_TYPE; } private void initializeImages() { // http://bugs.eclipse.org/bugs/show_bug.cgi?id=18936 if (!fQuickFixImagesInitialized) { if (isProblem() && indicateQuixFixableProblems() && JavaCorrectionProcessor.hasCorrections(this)) { // no light bulb for tasks if (!fgQuickFixImagesInitialized) { fgQuickFixImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_FIXABLE_PROBLEM); fgQuickFixErrorImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_FIXABLE_ERROR); fgQuickFixImagesInitialized= true; } if (ERROR_ANNOTATION_TYPE.equals(fType)) fImage= fgQuickFixErrorImage; else fImage= fgQuickFixImage; } fQuickFixImagesInitialized= true; } } private boolean indicateQuixFixableProblems() { return PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_CORRECTION_INDICATION); } /* * @see Annotation#paint */ public void paint(GC gc, Canvas canvas, Rectangle r) { initializeImages(); if (fImage != null) drawImage(fImage, gc, canvas, r, SWT.CENTER, SWT.TOP); } /* * @see IJavaAnnotation#getImage(Display) */ public Image getImage(Display display) { initializeImages(); return fImage; } /* * @see IJavaAnnotation#getMessage() */ public String getMessage() { return fProblem.getMessage(); } /* * @see IJavaAnnotation#isTemporary() */ public boolean isTemporary() { return true; } /* * @see IJavaAnnotation#getArguments() */ public String[] getArguments() { return isProblem() ? fProblem.getArguments() : null; } /* * @see IJavaAnnotation#getId() */ public int getId() { return fProblem.getID(); } /* * @see IJavaAnnotation#isProblem() */ public boolean isProblem() { return WARNING_ANNOTATION_TYPE.equals(fType) || ERROR_ANNOTATION_TYPE.equals(fType); } /* * @see IJavaAnnotation#isRelevant() */ public boolean isRelevant() { return true; } /* * @see IJavaAnnotation#hasOverlay() */ public boolean hasOverlay() { return false; } /* * @see IJavaAnnotation#addOverlaid(IJavaAnnotation) */ public void addOverlaid(IJavaAnnotation annotation) { if (fOverlaids == null) fOverlaids= new ArrayList(1); fOverlaids.add(annotation); } /* * @see IJavaAnnotation#removeOverlaid(IJavaAnnotation) */ public void removeOverlaid(IJavaAnnotation annotation) { if (fOverlaids != null) { fOverlaids.remove(annotation); if (fOverlaids.size() == 0) fOverlaids= null; } } /* * @see IJavaAnnotation#getOverlaidIterator() */ public Iterator getOverlaidIterator() { if (fOverlaids != null) return fOverlaids.iterator(); return null; } public String getAnnotationType() { return fType; } /* * @see IAnnotationExtension#getMarkerType() */ public String getMarkerType() { if (isProblem() || INFO_ANNOTATION_TYPE.equals(fType)) return IMarker.PROBLEM; else return IMarker.TASK; } /* * @see IAnnotationExtension#getSeverity() */ public int getSeverity() { if (ERROR_ANNOTATION_TYPE.equals(fType)) return IMarker.SEVERITY_ERROR; if (WARNING_ANNOTATION_TYPE.equals(fType)) return IMarker.SEVERITY_WARNING; return IMarker.SEVERITY_INFO; } /* * @see org.eclipse.jdt.internal.ui.javaeditor.IJavaAnnotation#getCompilationUnit() */ public ICompilationUnit getCompilationUnit() { return fCompilationUnit; } } /** * Internal structure for mapping positions to some value. * The reason for this specific structure is that positions can * change over time. Thus a lookup is based on value and not * on hash value. */ protected static class ReverseMap { static class Entry { Position fPosition; Object fValue; } private List fList= new ArrayList(2); private int fAnchor= 0; public ReverseMap() { } public Object get(Position position) { Entry entry; // behind anchor int length= fList.size(); for (int i= fAnchor; i < length; i++) { entry= (Entry) fList.get(i); if (entry.fPosition.equals(position)) { fAnchor= i; return entry.fValue; } } // before anchor for (int i= 0; i < fAnchor; i++) { entry= (Entry) fList.get(i); if (entry.fPosition.equals(position)) { fAnchor= i; return entry.fValue; } } return null; } private int getIndex(Position position) { Entry entry; int length= fList.size(); for (int i= 0; i < length; i++) { entry= (Entry) fList.get(i); if (entry.fPosition.equals(position)) return i; } return -1; } public void put(Position position, Object value) { int index= getIndex(position); if (index == -1) { Entry entry= new Entry(); entry.fPosition= position; entry.fValue= value; fList.add(entry); } else { Entry entry= (Entry) fList.get(index); entry.fValue= value; } } public void remove(Position position) { int index= getIndex(position); if (index > -1) fList.remove(index); } public void clear() { fList.clear(); } } /** * Annotation model dealing with java marker annotations and temporary problems. * Also acts as problem requestor for its compilation unit. Initialiy inactive. Must explicitly be * activated. */ protected static class CompilationUnitAnnotationModel extends ResourceMarkerAnnotationModel implements IProblemRequestor, IProblemRequestorExtension { private ICompilationUnit fCompilationUnit; private List fCollectedProblems; private List fGeneratedAnnotations; private IProgressMonitor fProgressMonitor; private boolean fIsActive= false; private ReverseMap fReverseMap= new ReverseMap(); private List fPreviouslyOverlaid= null; private List fCurrentlyOverlaid= new ArrayList(); private CompilationUnitAnnotationModelEvent fCurrentEvent; public CompilationUnitAnnotationModel(IResource resource) { super(resource); fCurrentEvent= new CompilationUnitAnnotationModelEvent(this, getResource()); } public void setCompilationUnit(ICompilationUnit unit) { fCompilationUnit= unit; } protected MarkerAnnotation createMarkerAnnotation(IMarker marker) { return new JavaMarkerAnnotation(marker); } protected Position createPositionFromProblem(IProblem problem) { int start= problem.getSourceStart(); if (start < 0) return null; int length= problem.getSourceEnd() - problem.getSourceStart() + 1; if (length < 0) return null; return new Position(start, length); } protected void update(IMarkerDelta[] markerDeltas) { super.update(markerDeltas); if (markerDeltas != null && markerDeltas.length > 0) { try { if (fCompilationUnit != null) fCompilationUnit.reconcile(true, null); } catch (JavaModelException ex) { if (!ex.isDoesNotExist()) handleCoreException(ex, ex.getMessage()); } } } /* * @see IProblemRequestor#beginReporting() */ public void beginReporting() { if (fCompilationUnit != null && fCompilationUnit.getJavaProject().isOnClasspath(fCompilationUnit)) fCollectedProblems= new ArrayList(); else fCollectedProblems= null; } /* * @see IProblemRequestor#acceptProblem(IProblem) */ public void acceptProblem(IProblem problem) { if (isActive()) fCollectedProblems.add(problem); } /* * @see IProblemRequestor#endReporting() */ public void endReporting() { if (!isActive()) return; if (fProgressMonitor != null && fProgressMonitor.isCanceled()) return; boolean isCanceled= false; boolean temporaryProblemsChanged= false; synchronized (fAnnotations) { fPreviouslyOverlaid= fCurrentlyOverlaid; fCurrentlyOverlaid= new ArrayList(); if (fGeneratedAnnotations.size() > 0) { temporaryProblemsChanged= true; removeAnnotations(fGeneratedAnnotations, false, true); fGeneratedAnnotations.clear(); } if (fCollectedProblems != null && fCollectedProblems.size() > 0) { Iterator e= fCollectedProblems.iterator(); while (e.hasNext()) { IProblem problem= (IProblem) e.next(); if (fProgressMonitor != null && fProgressMonitor.isCanceled()) { isCanceled= true; break; } Position position= createPositionFromProblem(problem); if (position != null) { try { ProblemAnnotation annotation= new ProblemAnnotation(problem, fCompilationUnit); addAnnotation(annotation, position, false); overlayMarkers(position, annotation); fGeneratedAnnotations.add(annotation); temporaryProblemsChanged= true; } catch (BadLocationException x) { // ignore invalid position } } } fCollectedProblems.clear(); } removeMarkerOverlays(isCanceled); fPreviouslyOverlaid.clear(); fPreviouslyOverlaid= null; } if (temporaryProblemsChanged) fireModelChanged(); } private void removeMarkerOverlays(boolean isCanceled) { if (isCanceled) { fCurrentlyOverlaid.addAll(fPreviouslyOverlaid); } else if (fPreviouslyOverlaid != null) { Iterator e= fPreviouslyOverlaid.iterator(); while (e.hasNext()) { JavaMarkerAnnotation annotation= (JavaMarkerAnnotation) e.next(); annotation.setOverlay(null); } } } /** * Overlays value with problem annotation. * @param problemAnnotation */ private void setOverlay(Object value, ProblemAnnotation problemAnnotation) { if (value instanceof JavaMarkerAnnotation) { JavaMarkerAnnotation annotation= (JavaMarkerAnnotation) value; if (annotation.isProblem()) { annotation.setOverlay(problemAnnotation); fPreviouslyOverlaid.remove(annotation); fCurrentlyOverlaid.add(annotation); } } } private void overlayMarkers(Position position, ProblemAnnotation problemAnnotation) { Object value= getAnnotations(position); if (value instanceof List) { List list= (List) value; for (Iterator e = list.iterator(); e.hasNext();) setOverlay(e.next(), problemAnnotation); } else { setOverlay(value, problemAnnotation); } } /** * Tells this annotation model to collect temporary problems from now on. */ private void startCollectingProblems() { fCollectedProblems= new ArrayList(); fGeneratedAnnotations= new ArrayList(); } /** * Tells this annotation model to no longer collect temporary problems. */ private void stopCollectingProblems() { if (fGeneratedAnnotations != null) { removeAnnotations(fGeneratedAnnotations, true, true); fGeneratedAnnotations.clear(); } fCollectedProblems= null; fGeneratedAnnotations= null; } /* * @see AnnotationModel#fireModelChanged() */ protected void fireModelChanged() { fireModelChanged(fCurrentEvent); fCurrentEvent= new CompilationUnitAnnotationModelEvent(this, getResource()); } /* * @see IProblemRequestor#isActive() */ public boolean isActive() { return fIsActive && (fCollectedProblems != null); } /* * @see IProblemRequestorExtension#setProgressMonitor(IProgressMonitor) */ public void setProgressMonitor(IProgressMonitor monitor) { fProgressMonitor= monitor; } /* * @see IProblemRequestorExtension#setIsActive(boolean) */ public void setIsActive(boolean isActive) { if (fIsActive != isActive) { fIsActive= isActive; if (fIsActive) startCollectingProblems(); else stopCollectingProblems(); } } private Object getAnnotations(Position position) { return fReverseMap.get(position); } /* * @see AnnotationModel#addAnnotation(Annotation, Position, boolean) */ protected void addAnnotation(Annotation annotation, Position position, boolean fireModelChanged) throws BadLocationException { super.addAnnotation(annotation, position, fireModelChanged); fCurrentEvent.annotationAdded(annotation); Object cached= fReverseMap.get(position); if (cached == null) fReverseMap.put(position, annotation); else if (cached instanceof List) { List list= (List) cached; list.add(annotation); } else if (cached instanceof Annotation) { List list= new ArrayList(2); list.add(cached); list.add(annotation); fReverseMap.put(position, list); } } /* * @see AnnotationModel#removeAllAnnotations(boolean) */ protected void removeAllAnnotations(boolean fireModelChanged) { for (Iterator iter= getAnnotationIterator(); iter.hasNext();) { fCurrentEvent.annotationRemoved((Annotation) iter.next()); } super.removeAllAnnotations(fireModelChanged); fReverseMap.clear(); } /* * @see AnnotationModel#removeAnnotation(Annotation, boolean) */ protected void removeAnnotation(Annotation annotation, boolean fireModelChanged) { fCurrentEvent.annotationRemoved(annotation); Position position= getPosition(annotation); Object cached= fReverseMap.get(position); if (cached instanceof List) { List list= (List) cached; list.remove(annotation); if (list.size() == 1) { fReverseMap.put(position, list.get(0)); list.clear(); } } else if (cached instanceof Annotation) { fReverseMap.remove(position); } super.removeAnnotation(annotation, fireModelChanged); } } protected static class GlobalAnnotationModelListener implements IAnnotationModelListener, IAnnotationModelListenerExtension { private ListenerList fListenerList; public GlobalAnnotationModelListener() { fListenerList= new ListenerList(); } /** * @see IAnnotationModelListener#modelChanged(IAnnotationModel) */ public void modelChanged(IAnnotationModel model) { Object[] listeners= fListenerList.getListeners(); for (int i= 0; i < listeners.length; i++) { ((IAnnotationModelListener) listeners[i]).modelChanged(model); } } /** * @see IAnnotationModelListenerExtension#modelChanged(AnnotationModelEvent) */ public void modelChanged(AnnotationModelEvent event) { Object[] listeners= fListenerList.getListeners(); for (int i= 0; i < listeners.length; i++) { Object curr= listeners[i]; if (curr instanceof IAnnotationModelListenerExtension) { ((IAnnotationModelListenerExtension) curr).modelChanged(event); } } } public void addListener(IAnnotationModelListener listener) { fListenerList.add(listener); } public void removeListener(IAnnotationModelListener listener) { fListenerList.remove(listener); } } /** Preference key for temporary problems */ private final static String HANDLE_TEMPORARY_PROBLEMS= PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS; /** Indicates whether the save has been initialized by this provider */ private boolean fIsAboutToSave= false; /** The save policy used by this provider */ private ISavePolicy fSavePolicy; /** Internal property changed listener */ private IPropertyChangeListener fPropertyListener; /** Annotation model listener added to all created CU annotation models */ private GlobalAnnotationModelListener fGlobalAnnotationModelListener; /** * Constructor */ public CompilationUnitDocumentProvider2() { setParentDocumentProvider(new TextFileDocumentProvider(new JavaStorageDocumentProvider())); fGlobalAnnotationModelListener= new GlobalAnnotationModelListener(); fPropertyListener= new IPropertyChangeListener() { public void propertyChange(PropertyChangeEvent event) { if (HANDLE_TEMPORARY_PROBLEMS.equals(event.getProperty())) enableHandlingTemporaryProblems(); } }; JavaPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(fPropertyListener); } /** * Creates a compilation unit from the given file. * * @param file the file from which to create the compilation unit */ protected ICompilationUnit createCompilationUnit(IFile file) { Object element= JavaCore.create(file); if (element instanceof ICompilationUnit) return (ICompilationUnit) element; return null; } /* * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#createEmptyFileInfo() */ protected FileInfo createEmptyFileInfo() { return new CompilationUnitInfo(); } /* * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#createAnnotationModel(org.eclipse.core.resources.IFile) */ protected IAnnotationModel createAnnotationModel(IFile file) { return new CompilationUnitAnnotationModel(file); } /* * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#createFileInfo(java.lang.Object) */ protected FileInfo createFileInfo(Object element) throws CoreException { if (!(element instanceof IFileEditorInput)) return null; IFileEditorInput input= (IFileEditorInput) element; ICompilationUnit original= createCompilationUnit(input.getFile()); if (original == null) return null; FileInfo info= super.createFileInfo(element); if (!(info instanceof CompilationUnitInfo)) return null; CompilationUnitInfo cuInfo= (CompilationUnitInfo) info; IProblemRequestor requestor= cuInfo.fModel instanceof IProblemRequestor ? (IProblemRequestor) cuInfo.fModel : null; if (JavaPlugin.USE_WORKING_COPY_OWNERS) { original.becomeWorkingCopy(requestor, getProgressMonitor()); cuInfo.fCopy= original; } else { cuInfo.fCopy= (ICompilationUnit) original.getSharedWorkingCopy(getProgressMonitor(), JavaPlugin.getDefault().getBufferFactory(), requestor); } if (cuInfo.fModel instanceof CompilationUnitAnnotationModel) { CompilationUnitAnnotationModel model= (CompilationUnitAnnotationModel) cuInfo.fModel; model.setCompilationUnit(cuInfo.fCopy); } cuInfo.fModel.addAnnotationModelListener(fGlobalAnnotationModelListener); if (requestor instanceof IProblemRequestorExtension) { IProblemRequestorExtension extension= (IProblemRequestorExtension) requestor; extension.setIsActive(isHandlingTemporaryProblems()); } return cuInfo; } /* * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#disposeFileInfo(java.lang.Object, org.eclipse.ui.editors.text.TextFileDocumentProvider.FileInfo) */ protected void disposeFileInfo(Object element, FileInfo info) { if (info instanceof CompilationUnitInfo) { CompilationUnitInfo cuInfo= (CompilationUnitInfo) info; if (JavaPlugin.USE_WORKING_COPY_OWNERS) { try { cuInfo.fCopy.discardWorkingCopy(); } catch (JavaModelException x) { handleCoreException(x, x.getMessage()); } } else { cuInfo.fCopy.destroy(); } cuInfo.fModel.removeAnnotationModelListener(fGlobalAnnotationModelListener); } super.disposeFileInfo(element, info); } /* * @see org.eclipse.ui.editors.text.TextFileDocumentProvider#saveDocument(org.eclipse.core.runtime.IProgressMonitor, java.lang.Object, org.eclipse.jface.text.IDocument, boolean) */ public void saveDocument(IProgressMonitor monitor, Object element, IDocument ignore, boolean overwrite) throws CoreException { FileInfo fileInfo= getFileInfo(element); if (fileInfo instanceof CompilationUnitInfo) { CompilationUnitInfo info= (CompilationUnitInfo) fileInfo; // Workaround for bug 41583: [misc] Eclipse cannot save or compile files in non-Java project anymore IJavaProject jProject= info.fCopy.getJavaProject(); if (jProject == null || !jProject.getProject().hasNature(JavaCore.NATURE_ID)) { super.saveDocument(monitor, element, ignore, overwrite); return; } synchronized (info.fCopy) { info.fCopy.reconcile(); } ICompilationUnit original= (ICompilationUnit) info.fCopy.getOriginalElement(); IResource resource= original.getResource(); if (resource == null) { // underlying resource has been deleted, just recreate file, ignore the rest super.saveDocument(monitor, element, ignore, overwrite); return; } if (fSavePolicy != null) fSavePolicy.preSave(info.fCopy); try { fIsAboutToSave= true; // commit working copy if (JavaPlugin.USE_WORKING_COPY_OWNERS) { info.fCopy.commitWorkingCopy(overwrite, monitor); } else { info.fCopy.commit(overwrite, monitor); // next call required as commiting working copies changed to no longer walk through the right buffer saveDocumentContent(monitor, element, ignore, overwrite); } } catch (CoreException x) { // inform about the failure fireElementStateChangeFailed(element); throw x; } catch (RuntimeException x) { // inform about the failure fireElementStateChangeFailed(element); throw x; } finally { fIsAboutToSave= false; } // If here, the dirty state of the editor will change to "not dirty". // Thus, the state changing flag will be reset. AbstractMarkerAnnotationModel model= (AbstractMarkerAnnotationModel) info.fModel; IDocument document= getDocument(element); model.updateMarkers(document); if (fSavePolicy != null) { ICompilationUnit unit= fSavePolicy.postSave(original); if (unit != null) { IResource r= unit.getResource(); IMarker[] markers= r.findMarkers(IMarker.MARKER, true, IResource.DEPTH_ZERO); if (markers != null && markers.length > 0) { for (int i= 0; i < markers.length; i++) model.updateMarker(markers[i], document, null); } } } } else { getParentProvider().saveDocument(monitor, element, ignore, overwrite); } } /** * Returns the preference whether handling temporary problems is enabled. */ protected boolean isHandlingTemporaryProblems() { IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); return store.getBoolean(HANDLE_TEMPORARY_PROBLEMS); } /** * Switches the state of problem acceptance according to the value in the preference store. */ protected void enableHandlingTemporaryProblems() { boolean enable= isHandlingTemporaryProblems(); for (Iterator iter= getFileInfosIterator(); iter.hasNext();) { FileInfo info= (FileInfo) iter.next(); if (info.fModel instanceof IProblemRequestorExtension) { IProblemRequestorExtension extension= (IProblemRequestorExtension) info.fModel; extension.setIsActive(enable); } } } /* * @see org.eclipse.jdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#setSavePolicy(org.eclipse.jdt.internal.ui.javaeditor.ISavePolicy) */ public void setSavePolicy(ISavePolicy savePolicy) { fSavePolicy= savePolicy; } /* * @see org.eclipse.jdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#addGlobalAnnotationModelListener(org.eclipse.jface.text.source.IAnnotationModelListener) */ public void addGlobalAnnotationModelListener(IAnnotationModelListener listener) { fGlobalAnnotationModelListener.addListener(listener); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#removeGlobalAnnotationModelListener(org.eclipse.jface.text.source.IAnnotationModelListener) */ public void removeGlobalAnnotationModelListener(IAnnotationModelListener listener) { fGlobalAnnotationModelListener.removeListener(listener); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#getWorkingCopy(java.lang.Object) */ public ICompilationUnit getWorkingCopy(Object element) { FileInfo fileInfo= getFileInfo(element); if (fileInfo instanceof CompilationUnitInfo) { CompilationUnitInfo info= (CompilationUnitInfo) fileInfo; return info.fCopy; } return null; } /* * @see org.eclipse.jdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#shutdown() */ public void shutdown() { JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(fPropertyListener); Iterator e= getConnectedElementsIterator(); while (e.hasNext()) disconnect(e.next()); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#saveDocumentContent(org.eclipse.core.runtime.IProgressMonitor, java.lang.Object, org.eclipse.jface.text.IDocument, boolean) */ public void saveDocumentContent(IProgressMonitor monitor, Object element, IDocument document, boolean overwrite) throws CoreException { if (!fIsAboutToSave) return; super.saveDocument(monitor, element, document, overwrite); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider#createLineTracker(java.lang.Object) */ public ILineTracker createLineTracker(Object element) { return new DefaultLineTracker(); } }
42,367
Bug 42367 StyledText - StringIndexOutOfBoundsException in StyledTextRenderer
200308281813 When hovering over the quick diff ruler to display the diff hover. Not reproducable, but consistently failing for a certain hover (I suspect an empty hover message, but not sure). java.lang.StringIndexOutOfBoundsException: String index out of range: -1 at java.lang.Throwable.<init>(Throwable.java) at java.lang.Throwable.<init>(Throwable.java) at java.lang.StringIndexOutOfBoundsException.<init>(StringIndexOutOfBoundsException.java:67) at java.lang.String.substring(String.java) at org.eclipse.swt.custom.DisplayRenderer.getStyledTextWidth(DisplayRenderer.java) at org.eclipse.swt.custom.StyledTextRenderer.getTextWidth(StyledTextRenderer.java) at org.eclipse.swt.custom.StyledText$ContentWidthCache.contentWidth(StyledText.java) at org.eclipse.swt.custom.StyledText$ContentWidthCache.calculate(StyledText.java) at org.eclipse.swt.custom.StyledText.computeSize(StyledText.java:2116) at org.eclipse.swt.layout.GridLayout.calculateGridDimensions(GridLayout.java) at org.eclipse.swt.layout.GridLayout.computeLayoutSize(GridLayout.java) at org.eclipse.swt.layout.GridLayout.computeSize(GridLayout.java) at org.eclipse.swt.widgets.Composite.computeSize(Composite.java) at org.eclipse.swt.widgets.Control.computeSize(Control.java) at org.eclipse.jdt.internal.ui.text.java.hover.SourceViewerInformationControl.computeSizeHint(SourceViewerInformationControl.java:315) at org.eclipse.jdt.internal.ui.text.CustomSourceInformationControl.computeSizeHint(CustomSourceInformationControl.java:70) at org.eclipse.jface.text.AbstractInformationControlManager.internalShowInformationControl(AbstractInformationControlManager.java:708) at org.eclipse.jface.text.AbstractInformationControlManager.presentInformation(AbstractInformationControlManager.java:677) at org.eclipse.jface.text.AbstractHoverInformationControlManager.presentInformation(AbstractHoverInformationControlManager.java:423) at org.eclipse.jface.text.AbstractInformationControlManager.setInformation(AbstractInformationControlManager.java:224) at org.eclipse.jface.text.source.AnnotationBarHoverManager.computeInformation(AnnotationBarHoverManager.java:97) at org.eclipse.jface.text.AbstractInformationControlManager.doShowInformation(AbstractInformationControlManager.java:661) at org.eclipse.jface.text.AbstractHoverInformationControlManager$MouseTracker.mouseHover(AbstractHoverInformationControlManager.java) 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.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)
resolved fixed
a91f3e9
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-09-30T08:49:45Z
2003-09-02T10:53:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/CustomSourceInformationControl.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; import org.eclipse.swt.custom.StyledText; 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.swt.widgets.Shell; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.ITextViewerExtension; import org.eclipse.jdt.internal.ui.text.java.hover.SourceViewerInformationControl; /** * Source viewer used to display quick diff hovers. * * @since 3.0 */ public class CustomSourceInformationControl extends SourceViewerInformationControl { /** The font name for the viewer font - the same as the java editor's. */ private static final String SYMBOLIC_FONT_NAME= "org.eclipse.jdt.ui.editors.textfont"; //$NON-NLS-1$ /** The maximum width of the control, set in <code>setSizeConstraints(int, int)</code>. */ int fMaxWidth= Integer.MAX_VALUE; /** The maximum height of the control, set in <code>setSizeConstraints(int, int)</code>. */ int fMaxHeight= Integer.MAX_VALUE; /** The partition type to be used as the starting partition type by the paritition scanner. */ private String fPartition; /* * @see org.eclipse.jface.text.IInformationControl#setSizeConstraints(int, int) */ public void setSizeConstraints(int maxWidth, int maxHeight) { fMaxWidth= maxWidth; fMaxHeight= maxHeight; } /** * Creates a new information control. * * @param parent the shell that is the parent of this hover / control * @param partition the initial partition type to be used for the underlying viewer */ public CustomSourceInformationControl(Shell parent, String partition) { super(parent); setViewerFont(); setStartingPartitionType(partition); } /* * @see org.eclipse.jface.text.IInformationControl#computeSizeHint() */ public Point computeSizeHint() { Point size= super.computeSizeHint(); size.x= Math.min(size.x, fMaxWidth); size.y= Math.min(size.y, fMaxHeight); return size; } /** * Sets the font for this viewer sustaining selection and scroll position. */ private void setViewerFont() { Font font= JFaceResources.getFont(SYMBOLIC_FONT_NAME); if (getViewer().getDocument() != null) { Point selection= getViewer().getSelectedRange(); int topIndex= getViewer().getTopIndex(); StyledText styledText= getViewer().getTextWidget(); Control parent= styledText; if (getViewer() instanceof ITextViewerExtension) { ITextViewerExtension extension= (ITextViewerExtension) getViewer(); parent= extension.getControl(); } parent.setRedraw(false); styledText.setFont(font); getViewer().setSelectedRange(selection.x , selection.y); getViewer().setTopIndex(topIndex); if (parent instanceof Composite) { Composite composite= (Composite) parent; composite.layout(true); } parent.setRedraw(true); } else { StyledText styledText= getViewer().getTextWidget(); styledText.setFont(font); } } /** * Sets the initial partition for the underlying source viewer. * * @param partition the partition type */ public void setStartingPartitionType(String partition) { if (partition == null) fPartition= IDocument.DEFAULT_CONTENT_TYPE; else fPartition= partition; } /* * @see org.eclipse.jface.text.IInformationControl#setInformation(java.lang.String) */ public void setInformation(String content) { super.setInformation(content); IDocument doc= getViewer().getDocument(); if (doc == null) return; String start= null; if (IJavaPartitions.JAVA_DOC.equals(fPartition)) { start= "/**\n"; //$NON-NLS-1$ } else if (IJavaPartitions.JAVA_MULTI_LINE_COMMENT.equals(fPartition)) { start= "/* \n"; //$NON-NLS-1$ } if (start != null) { try { doc.replace(0, 0, start); getViewer().setDocument(doc, 4, doc.getLength() - 4); } catch (BadLocationException e) { } } } }
43,750
Bug 43750 synchronized follows generated delegate [code manipulation]
Using the Source->Generate Delegate Methods . . ., given, public class Foo { public synchronized int doThis() { . . . } } Eclipse will generate the delegate for foo.doThis as, public class Bar { private Foo foo; public synchronized int doThis() { return foo.doThis();} } which amounts to double synchronization, bad karma. It should IMHO do the following. public class Bar { private Foo foo; public int doThis() { return foo.doThis();} }
resolved fixed
f092d5d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-01T08:52:16Z
2003-09-26T15:26:40Z
org.eclipse.jdt.ui/core
43,750
Bug 43750 synchronized follows generated delegate [code manipulation]
Using the Source->Generate Delegate Methods . . ., given, public class Foo { public synchronized int doThis() { . . . } } Eclipse will generate the delegate for foo.doThis as, public class Bar { private Foo foo; public synchronized int doThis() { return foo.doThis();} } which amounts to double synchronization, bad karma. It should IMHO do the following. public class Bar { private Foo foo; public int doThis() { return foo.doThis();} }
resolved fixed
f092d5d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-01T08:52:16Z
2003-09-26T15:26:40Z
extension/org/eclipse/jdt/internal/corext/codemanipulation/AddDelegateMethodsOperation.java
43,868
Bug 43868 Anonymous classes do not sort properly in Hierarchy view [type hierarchy] [render]
build I20030925 - open hierarchy on ViewerSorter - there are lots of "Anonymous of ViewerSorter" entries sprinkled throughout the otherwise sorted list
resolved fixed
5e7e6f9
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-01T08:53:31Z
2003-09-29T21:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/JavaElementSorter.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.ui; import java.text.Collator; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IStorage; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IPath; import org.eclipse.jface.viewers.ContentViewer; import org.eclipse.jface.viewers.IBaseLabelProvider; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.ui.model.IWorkbenchAdapter; import org.eclipse.jdt.core.Flags; import org.eclipse.jdt.core.IField; import org.eclipse.jdt.core.IInitializer; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.packageview.ClassPathContainer; import org.eclipse.jdt.internal.ui.preferences.MembersOrderPreferenceCache; /** * Sorter for Java elements. Ordered by element category, then by element name. * Package fragment roots are sorted as ordered on the classpath. * * <p> * This class may be instantiated; it is not intended to be subclassed. * </p> * * @since 2.0 */ public class JavaElementSorter extends ViewerSorter { private static final int PROJECTS= 1; private static final int PACKAGEFRAGMENTROOTS= 2; private static final int PACKAGEFRAGMENT= 3; private static final int COMPILATIONUNITS= 4; private static final int CLASSFILES= 5; private static final int RESOURCEFOLDERS= 7; private static final int RESOURCES= 8; private static final int STORAGE= 9; private static final int PACKAGE_DECL= 10; private static final int IMPORT_CONTAINER= 11; private static final int IMPORT_DECLARATION= 12; // Includes all categories ordered using the OutlineSortOrderPage: // types, initializers, methods & fields private static final int MEMBERSOFFSET= 15; private static final int JAVAELEMENTS= 50; private static final int OTHERS= 51; public JavaElementSorter() { super(null); // delay initialization of collator } /** * @deprecated Bug 22518. Method never used: does not override ViewerSorter#isSorterProperty(Object, String). * Method could be removed, but kept for API compatibility. */ public boolean isSorterProperty(Object element, Object property) { return true; } /* * @see ViewerSorter#category */ public int category(Object element) { if (element instanceof IJavaElement) { try { IJavaElement je= (IJavaElement) element; switch (je.getElementType()) { case IJavaElement.METHOD: { IMethod method= (IMethod) je; if (method.isConstructor()) { return getMemberCategory(MembersOrderPreferenceCache.CONSTRUCTORS_INDEX); } int flags= method.getFlags(); if (Flags.isStatic(flags)) return getMemberCategory(MembersOrderPreferenceCache.STATIC_METHODS_INDEX); else return getMemberCategory(MembersOrderPreferenceCache.METHOD_INDEX); } case IJavaElement.FIELD : { int flags= ((IField) je).getFlags(); if (Flags.isStatic(flags)) return getMemberCategory(MembersOrderPreferenceCache.STATIC_FIELDS_INDEX); else return getMemberCategory(MembersOrderPreferenceCache.FIELDS_INDEX); } case IJavaElement.INITIALIZER : { int flags= ((IInitializer) je).getFlags(); if (Flags.isStatic(flags)) return getMemberCategory(MembersOrderPreferenceCache.STATIC_INIT_INDEX); else return getMemberCategory(MembersOrderPreferenceCache.INIT_INDEX); } case IJavaElement.TYPE : return getMemberCategory(MembersOrderPreferenceCache.TYPE_INDEX); case IJavaElement.PACKAGE_DECLARATION : return PACKAGE_DECL; case IJavaElement.IMPORT_CONTAINER : return IMPORT_CONTAINER; case IJavaElement.IMPORT_DECLARATION : return IMPORT_DECLARATION; case IJavaElement.PACKAGE_FRAGMENT : IPackageFragment pack= (IPackageFragment) je; if (pack.getParent().getResource() instanceof IProject) { return PACKAGEFRAGMENTROOTS; } return PACKAGEFRAGMENT; case IJavaElement.PACKAGE_FRAGMENT_ROOT : return PACKAGEFRAGMENTROOTS; case IJavaElement.JAVA_PROJECT : return PROJECTS; case IJavaElement.CLASS_FILE : return CLASSFILES; case IJavaElement.COMPILATION_UNIT : return COMPILATIONUNITS; } } catch (JavaModelException e) { if (!e.isDoesNotExist()) JavaPlugin.log(e); } return JAVAELEMENTS; } else if (element instanceof IFile) { return RESOURCES; } else if (element instanceof IProject) { return PROJECTS; } else if (element instanceof IContainer) { return RESOURCEFOLDERS; } else if (element instanceof IStorage) { return STORAGE; } else if (element instanceof ClassPathContainer) { return PACKAGEFRAGMENTROOTS; } return OTHERS; } private int getMemberCategory(int kind) { int offset= JavaPlugin.getDefault().getMemberOrderPreferenceCache().getIndex(kind); return offset + MEMBERSOFFSET; } /* * @see ViewerSorter#compare */ public int compare(Viewer viewer, Object e1, Object e2) { int cat1= category(e1); int cat2= category(e2); if (cat1 != cat2) return cat1 - cat2; if (cat1 == PROJECTS) { IWorkbenchAdapter a1= (IWorkbenchAdapter)((IAdaptable)e1).getAdapter(IWorkbenchAdapter.class); IWorkbenchAdapter a2= (IWorkbenchAdapter)((IAdaptable)e2).getAdapter(IWorkbenchAdapter.class); return getCollator().compare(a1.getLabel(e1), a2.getLabel(e2)); } if (cat1 == PACKAGEFRAGMENTROOTS) { IPackageFragmentRoot root1= getPackageFragmentRoot(e1); IPackageFragmentRoot root2= getPackageFragmentRoot(e2); if (!root1.getPath().equals(root2.getPath())) { int p1= getClassPathIndex(root1); int p2= getClassPathIndex(root2); if (p1 != p2) { return p1 - p2; } } } // non - java resources are sorted using the label from the viewers label provider if (cat1 == PROJECTS || cat1 == RESOURCES || cat1 == RESOURCEFOLDERS || cat1 == STORAGE || cat1 == OTHERS) { return compareWithLabelProvider(viewer, e1, e2); } String name1= ((IJavaElement) e1).getElementName(); String name2= ((IJavaElement) e2).getElementName(); // java element are sorted by name int cmp= getCollator().compare(name1, name2); if (cmp != 0) { return cmp; } if (e1 instanceof IMethod) { String[] params1= ((IMethod) e1).getParameterTypes(); String[] params2= ((IMethod) e2).getParameterTypes(); int len= Math.min(params1.length, params2.length); for (int i = 0; i < len; i++) { cmp= getCollator().compare(Signature.toString(params1[i]), Signature.toString(params2[i])); if (cmp != 0) { return cmp; } } return params1.length - params2.length; } return 0; } private IPackageFragmentRoot getPackageFragmentRoot(Object element) { if (element instanceof ClassPathContainer) { // return first package fragment root from the container ClassPathContainer cp= (ClassPathContainer)element; Object[] roots= cp.getPackageFragmentRoots(); if (roots.length > 0) return (IPackageFragmentRoot)roots[0]; // non resolvable - return a dummy package fragment root return cp.getJavaProject().getPackageFragmentRoot("Non-Resolvable"); //$NON-NLS-1$ } return JavaModelUtil.getPackageFragmentRoot((IJavaElement)element); } private int compareWithLabelProvider(Viewer viewer, Object e1, Object e2) { if (viewer == null || !(viewer instanceof ContentViewer)) { IBaseLabelProvider prov = ((ContentViewer) viewer).getLabelProvider(); if (prov instanceof ILabelProvider) { ILabelProvider lprov= (ILabelProvider) prov; String name1 = lprov.getText(e1); String name2 = lprov.getText(e2); if (name1 != null && name2 != null) { return getCollator().compare(name1, name2); } } } return 0; // can't compare } private int getClassPathIndex(IPackageFragmentRoot root) { try { IPath rootPath= root.getPath(); IPackageFragmentRoot[] roots= root.getJavaProject().getPackageFragmentRoots(); for (int i= 0; i < roots.length; i++) { if (roots[i].getPath().equals(rootPath)) { return i; } } } catch (JavaModelException e) { } return Integer.MAX_VALUE; } /* (non-Javadoc) * @see org.eclipse.jface.viewers.ViewerSorter#getCollator() */ public final Collator getCollator() { if (collator == null) { collator= Collator.getInstance(); } return collator; } }
43,850
Bug 43850 QuickAssist with linked mode has wrong default selection [quick assist]
I20030925 QuickAssist with linked mode has a default selection which is NOT the inserted (and green underlined) proposal. This is annoying, since it prevents quick acceptance with <Enter>. class X { public void foo(int jott) { } } - cursor on 'jott', Ctrl+1 - choose 'Assign parameter to new field' -> 'jott' is inserted in the editor, but 'i' is selected and inserted on <Enter> It's most probably a typo in LinkedModeProposal, line 101: "// keep first entry at first position Arrays.sort(res, 0, ..." should be "Arrays.sort(res, 1, ..."
resolved fixed
1b9692b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-01T10:33:12Z
2003-09-29T18:26:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/LinkedCorrectionProposal.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.text.correction; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.DocumentEvent; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.contentassist.ICompletionProposal; import org.eclipse.jface.text.contentassist.ICompletionProposalExtension2; import org.eclipse.jface.text.contentassist.IContextInformation; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal; import org.eclipse.jdt.internal.corext.codemanipulation.ImportsStructure; import org.eclipse.jdt.internal.corext.dom.ASTRewrite; import org.eclipse.jdt.internal.corext.textmanipulation.GroupDescription; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; import org.eclipse.jdt.internal.ui.text.java.JavaCompletionProposalComparator; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels; /** * */ public class LinkedCorrectionProposal extends ASTRewriteCorrectionProposal { private GroupDescription fSelectionDescription; private List fLinkedPositions; private Map fLinkProposals; public LinkedCorrectionProposal(String name, ICompilationUnit cu, ASTRewrite rewrite, int relevance, Image image) { super(name, cu, rewrite, relevance, image); fSelectionDescription= null; fLinkedPositions= null; fLinkProposals= null; } /* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal#getSelectionDescription() */ protected GroupDescription getSelectionDescription() { return fSelectionDescription; } /* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal#getLinkedRanges() */ protected GroupDescription[] getLinkedRanges() { if (fLinkedPositions != null && !fLinkedPositions.isEmpty()) { return (GroupDescription[]) fLinkedPositions.toArray(new GroupDescription[fLinkedPositions.size()]); } return null; } public GroupDescription markAsSelection(ASTRewrite rewrite, ASTNode node) { fSelectionDescription= new GroupDescription("selection"); //$NON-NLS-1$ rewrite.markAsTracked(node, fSelectionDescription); return fSelectionDescription; } /* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal#getLinkedModeProposals(java.lang.String) */ protected ICompletionProposal[] getLinkedModeProposals(String name) { if (fLinkProposals == null) { return null; } List proposals= (List) fLinkProposals.get(name); if (proposals != null) { ICompletionProposal[] res= (ICompletionProposal[]) proposals.toArray(new ICompletionProposal[proposals.size()]); if (res.length > 1) { // keep first entry at first position Arrays.sort(res, 0, res.length, new JavaCompletionProposalComparator()); } return res; } return null; } public void addLinkedModeProposal(String name, String proposal) { addLinkedModeProposal(name, new LinkedModeProposal(proposal)); } public void addLinkedModeProposal(String name, ITypeBinding proposal) { addLinkedModeProposal(name, new LinkedModeProposal(getCompilationUnit(), proposal)); } public void addLinkedModeProposal(String name, IJavaCompletionProposal proposal) { if (fLinkProposals == null) { fLinkProposals= new HashMap(); } List proposals= (List) fLinkProposals.get(name); if (proposals == null) { proposals= new ArrayList(10); fLinkProposals.put(name, proposals); } proposals.add(proposal); } public GroupDescription markAsLinked(ASTRewrite rewrite, ASTNode node, boolean isFirst, String kind) { GroupDescription description= new GroupDescription(kind); rewrite.markAsTracked(node, description); if (fLinkedPositions == null) { fLinkedPositions= new ArrayList(); } if (isFirst) { fLinkedPositions.add(0, description); } else { fLinkedPositions.add(description); } return description; } public void setSelectionDescription(GroupDescription desc) { fSelectionDescription= desc; } public static class LinkedModeProposal implements IJavaCompletionProposal, ICompletionProposalExtension2 { private String fProposal; private ITypeBinding fTypeProposal; private ICompilationUnit fCompilationUnit; public LinkedModeProposal(String proposal) { fProposal= proposal; } public LinkedModeProposal(ICompilationUnit unit, ITypeBinding typeProposal) { this(typeProposal.getName()); fTypeProposal= typeProposal; fCompilationUnit= unit; } private ImportsStructure getImportStructure() throws CoreException { IPreferenceStore store= PreferenceConstants.getPreferenceStore(); String[] prefOrder= JavaPreferencesSettings.getImportOrderPreference(store); int threshold= JavaPreferencesSettings.getImportNumberThreshold(store); ImportsStructure impStructure= new ImportsStructure(fCompilationUnit, prefOrder, threshold, true); return impStructure; } /* (non-Javadoc) * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#apply(org.eclipse.jface.text.ITextViewer, char, int, int) */ public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) { IDocument document= viewer.getDocument(); Point point= viewer.getSelectedRange(); try { String replaceString= fProposal; ImportsStructure impStructure= null; if (fTypeProposal != null) { impStructure= getImportStructure(); replaceString= impStructure.addImport(fTypeProposal); } document.replace(point.x, point.y, replaceString); if (impStructure != null) { impStructure.create(false, null); } } catch (BadLocationException e) { JavaPlugin.log(e); } catch (CoreException e) { JavaPlugin.log(e); } } /* (non-Javadoc) * @see org.eclipse.jface.text.contentassist.ICompletionProposal#getDisplayString() */ public String getDisplayString() { if (fTypeProposal == null || fTypeProposal.getPackage() == null) { return fProposal; } StringBuffer buf= new StringBuffer(); buf.append(fProposal); buf.append(JavaElementLabels.CONCAT_STRING); if (fTypeProposal.getPackage().isUnnamed()) { buf.append(JavaElementLabels.DEFAULT_PACKAGE); } else { buf.append(fTypeProposal.getPackage().getName()); } return buf.toString(); } /* (non-Javadoc) * @see org.eclipse.jface.text.contentassist.ICompletionProposal#getImage() */ public Image getImage() { if (fTypeProposal != null) { ITypeBinding binding= fTypeProposal; if (binding.isArray()) { binding= fTypeProposal.getElementType(); } if (binding.isPrimitive()) { return null; } ImageDescriptor descriptor= JavaElementImageProvider.getTypeImageDescriptor(binding.isInterface(), binding.isMember(), binding.getModifiers()); return JavaPlugin.getImageDescriptorRegistry().get(descriptor); } return null; } /* (non-Javadoc) * @see org.eclipse.jdt.ui.text.java.IJavaCompletionProposal#getRelevance() */ public int getRelevance() { return 0; } /* (non-Javadoc) * @see org.eclipse.jface.text.contentassist.ICompletionProposal#apply(org.eclipse.jface.text.IDocument) */ public void apply(IDocument document) { // not called } public Point getSelection(IDocument document) { return null; } public String getAdditionalProposalInfo() { return null; } public IContextInformation getContextInformation() { return null; } public void selected(ITextViewer viewer, boolean smartToggle) {} public void unselected(ITextViewer viewer) {} public boolean validate(IDocument document, int offset, DocumentEvent event) { return false;} } }
43,551
Bug 43551 Background conflicts with syntax highlighting in Edit Template of code gneration [code generation]
I have set my syntax highlighting colors. They use white foreground and black background for comments. In Preferences Java Code Generation Code & Comments If I edit an comment entry, eg Types I can not see the comments as it is using the syntax highlighting setting of white foreground but does not use the syntax highlighted background (black) but uses a default background of white. So I get white on white. It needs to either use all syntax highlight colors including background or default colors or no colors.
resolved fixed
15d9b60
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-01T13:19:04Z
2003-09-24T07:53:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/CodeFormatterConfigurationBlock.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.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Map; 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.TabFolder; import org.eclipse.swt.widgets.TabItem; import org.eclipse.swt.widgets.Text; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.Region; import org.eclipse.jface.text.formatter.FormattingContextProperties; import org.eclipse.jface.text.formatter.IContentFormatter; import org.eclipse.jface.text.formatter.IContentFormatterExtension2; import org.eclipse.jface.text.formatter.IFormattingContext; import org.eclipse.jface.text.source.SourceViewer; import org.eclipse.jface.text.source.SourceViewerConfiguration; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration; import org.eclipse.jdt.ui.text.JavaTextTools; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.javaeditor.JavaSourceViewer; import org.eclipse.jdt.internal.ui.text.IJavaPartitions; import org.eclipse.jdt.internal.ui.text.comment.CommentFormattingContext; import org.eclipse.jdt.internal.ui.util.PixelConverter; import org.eclipse.jdt.internal.ui.util.TabFolderLayout; import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener; /* * The page for setting code formatter options */ public class CodeFormatterConfigurationBlock extends OptionsConfigurationBlock { // Preference store keys, see JavaCore.getOptions private static final String PREF_NEWLINE_OPENING_BRACES= JavaCore.FORMATTER_NEWLINE_OPENING_BRACE; private static final String PREF_NEWLINE_CONTROL_STATEMENT= JavaCore.FORMATTER_NEWLINE_CONTROL; private static final String PREF_NEWLINE_CLEAR_ALL= JavaCore.FORMATTER_CLEAR_BLANK_LINES; private static final String PREF_NEWLINE_ELSE_IF= JavaCore.FORMATTER_NEWLINE_ELSE_IF; private static final String PREF_NEWLINE_EMPTY_BLOCK= JavaCore.FORMATTER_NEWLINE_EMPTY_BLOCK; private static final String PREF_CODE_SPLIT= JavaCore.FORMATTER_LINE_SPLIT; private static final String PREF_STYLE_COMPACT_ASSIGNEMENT= JavaCore.FORMATTER_COMPACT_ASSIGNMENT; private static final String PREF_TAB_CHAR= JavaCore.FORMATTER_TAB_CHAR; private static final String PREF_TAB_SIZE= JavaCore.FORMATTER_TAB_SIZE; private static final String PREF_SPACE_CASTEXPRESSION= JavaCore.FORMATTER_SPACE_CASTEXPRESSION; private static final String PREF_COMMENT_FORMATSOURCE= PreferenceConstants.FORMATTER_COMMENT_FORMATSOURCE; private static final String PREF_COMMENT_INDENTPARAMDESC= PreferenceConstants.FORMATTER_COMMENT_INDENTPARAMETERDESCRIPTION; private static final String PREF_COMMENT_FORMATHEADER= PreferenceConstants.FORMATTER_COMMENT_FORMATHEADER; private static final String PREF_COMMENT_INDENTROOTTAGS= PreferenceConstants.FORMATTER_COMMENT_INDENTROOTTAGS; private static final String PREF_COMMENT_FORMAT= PreferenceConstants.FORMATTER_COMMENT_FORMAT; private static final String PREF_COMMENT_NEWLINEPARAM= PreferenceConstants.FORMATTER_COMMENT_NEWLINEFORPARAMETER; private static final String PREF_COMMENT_SEPARATEROOTTAGS= PreferenceConstants.FORMATTER_COMMENT_SEPARATEROOTTAGS; private static final String PREF_COMMENT_CLEARBLANKLINES= PreferenceConstants.FORMATTER_COMMENT_CLEARBLANKLINES; private static final String PREF_COMMENT_LINELENGTH= PreferenceConstants.FORMATTER_COMMENT_LINELENGTH; private static final String PREF_COMMENT_FORMATHTML= PreferenceConstants.FORMATTER_COMMENT_FORMATHTML; // values private static final String INSERT= JavaCore.INSERT; private static final String DO_NOT_INSERT= JavaCore.DO_NOT_INSERT; private static final String COMPACT= JavaCore.COMPACT; private static final String NORMAL= JavaCore.NORMAL; private static final String TAB= JavaCore.TAB; private static final String SPACE= JavaCore.SPACE; private static final String CLEAR_ALL= JavaCore.CLEAR_ALL; private static final String PRESERVE_ONE= JavaCore.PRESERVE_ONE; private IDocument fPreviewDocument; private Text fTabSizeTextBox; private String fPreviewText; private SourceViewer fSourceViewer; private SourceViewerConfiguration fViewerConfiguration; private JavaTextTools fTextTools; private PixelConverter fPixelConverter; private IStatus fCodeLengthStatus; private IStatus fCommentLengthStatus; private IStatus fTabSizeStatus; public CodeFormatterConfigurationBlock(IStatusChangeListener context, IJavaProject project) { super(context, project); fTextTools= JavaPlugin.getDefault().getJavaTextTools(); fViewerConfiguration= new JavaSourceViewerConfiguration(fTextTools, null, IJavaPartitions.JAVA_PARTITIONING); fPreviewText= loadPreviewFile("CodeFormatterPreviewCode.txt"); //$NON-NLS-1$ fPreviewDocument= new Document(fPreviewText); fTextTools.setupJavaDocumentPartitioner(fPreviewDocument, IJavaPartitions.JAVA_PARTITIONING); fCodeLengthStatus= new StatusInfo(); fCommentLengthStatus= new StatusInfo(); fTabSizeStatus= new StatusInfo(); } protected String[] getAllKeys() { return new String[] { PREF_NEWLINE_OPENING_BRACES, PREF_NEWLINE_CONTROL_STATEMENT, PREF_NEWLINE_CLEAR_ALL, PREF_NEWLINE_ELSE_IF, PREF_NEWLINE_EMPTY_BLOCK, PREF_CODE_SPLIT, PREF_STYLE_COMPACT_ASSIGNEMENT, PREF_TAB_CHAR, PREF_TAB_SIZE, PREF_SPACE_CASTEXPRESSION }; } protected Control createContents(Composite parent) { fPixelConverter= new PixelConverter(parent); setShell(parent.getShell()); int textWidth= fPixelConverter.convertWidthInCharsToPixels(6); int nColumns= 3; GridLayout layout= new GridLayout(); layout.marginHeight= 0; layout.marginWidth= 0; Composite composite= new Composite(parent, SWT.NONE); composite.setLayout(layout); TabFolder folder= new TabFolder(composite, SWT.NONE); folder.setLayout(new TabFolderLayout()); folder.setLayoutData(new GridData(GridData.FILL_BOTH)); String[] insertNotInsert= new String[] { INSERT, DO_NOT_INSERT }; layout= new GridLayout(); layout.numColumns= nColumns; Composite newlineComposite= new Composite(folder, SWT.NULL); newlineComposite.setLayout(layout); String label= PreferencesMessages.getString("CodeFormatterPreferencePage.newline_opening_braces.label"); //$NON-NLS-1$ addCheckBox(newlineComposite, label, PREF_NEWLINE_OPENING_BRACES, insertNotInsert, 0); label= PreferencesMessages.getString("CodeFormatterPreferencePage.newline_control_statement.label"); //$NON-NLS-1$ addCheckBox(newlineComposite, label, PREF_NEWLINE_CONTROL_STATEMENT, insertNotInsert, 0); label= PreferencesMessages.getString("CodeFormatterPreferencePage.newline_clear_lines"); //$NON-NLS-1$ addCheckBox(newlineComposite, label, PREF_NEWLINE_CLEAR_ALL, new String[] { CLEAR_ALL, PRESERVE_ONE }, 0); label= PreferencesMessages.getString("CodeFormatterPreferencePage.newline_else_if.label"); //$NON-NLS-1$ addCheckBox(newlineComposite, label, PREF_NEWLINE_ELSE_IF, insertNotInsert, 0); label= PreferencesMessages.getString("CodeFormatterPreferencePage.newline_empty_block.label"); //$NON-NLS-1$ addCheckBox(newlineComposite, label, PREF_NEWLINE_EMPTY_BLOCK, insertNotInsert, 0); layout= new GridLayout(); layout.numColumns= nColumns; Composite lineSplittingComposite= new Composite(folder, SWT.NULL); lineSplittingComposite.setLayout(layout); label= PreferencesMessages.getString("CodeFormatterPreferencePage.split_code.label"); //$NON-NLS-1$ addTextField(lineSplittingComposite, label, PREF_CODE_SPLIT, 0, textWidth); label= PreferencesMessages.getString("CodeFormatterPreferencePage.split_comment.label"); //$NON-NLS-1$ addTextField(lineSplittingComposite, label, PREF_COMMENT_LINELENGTH, 0, textWidth); layout= new GridLayout(); layout.numColumns= nColumns; Composite styleComposite= new Composite(folder, SWT.NULL); styleComposite.setLayout(layout); label= PreferencesMessages.getString("CodeFormatterPreferencePage.style_compact_assignement.label"); //$NON-NLS-1$ addCheckBox(styleComposite, label, PREF_STYLE_COMPACT_ASSIGNEMENT, new String[] { COMPACT, NORMAL }, 0); label= PreferencesMessages.getString("CodeFormatterPreferencePage.style_space_castexpression.label"); //$NON-NLS-1$ addCheckBox(styleComposite, label, PREF_SPACE_CASTEXPRESSION, insertNotInsert, 0); label= PreferencesMessages.getString("CodeFormatterPreferencePage.tab_char.label"); //$NON-NLS-1$ addCheckBox(styleComposite, label, PREF_TAB_CHAR, new String[] { TAB, SPACE }, 0); label= PreferencesMessages.getString("CodeFormatterPreferencePage.tab_size.label"); //$NON-NLS-1$ fTabSizeTextBox= addTextField(styleComposite, label, PREF_TAB_SIZE, 0, textWidth); fTabSizeTextBox.setTextLimit(3); layout= new GridLayout(); layout.numColumns= 1; Composite commentComposite= new Composite(folder, SWT.NULL); commentComposite.setLayout(layout); final String[] trueFalse= new String[] { IPreferenceStore.TRUE, IPreferenceStore.FALSE }; label= PreferencesMessages.getString("CodeFormatterPreferencePage.comment_format.label"); //$NON-NLS-1$ Button master= addCheckBox(commentComposite, label, PREF_COMMENT_FORMAT, trueFalse, 0); label= PreferencesMessages.getString("CodeFormatterPreferencePage.comment_formatheader.label"); //$NON-NLS-1$ Button slave= addCheckBox(commentComposite, label, PREF_COMMENT_FORMATHEADER, trueFalse, 20); createSelectionDependency(master, slave); label= PreferencesMessages.getString("CodeFormatterPreferencePage.comment_formathtml.label"); //$NON-NLS-1$ slave= addCheckBox(commentComposite, label, PREF_COMMENT_FORMATHTML, trueFalse, 20); createSelectionDependency(master, slave); label= PreferencesMessages.getString("CodeFormatterPreferencePage.comment_formatsource.label"); //$NON-NLS-1$ slave= addCheckBox(commentComposite, label, PREF_COMMENT_FORMATSOURCE, trueFalse, 20); createSelectionDependency(master, slave); label= PreferencesMessages.getString("CodeFormatterPreferencePage.newline_clear_lines"); //$NON-NLS-1$ slave= addCheckBox(commentComposite, label, PREF_COMMENT_CLEARBLANKLINES, trueFalse, 20); createSelectionDependency(master, slave); label= PreferencesMessages.getString("CodeFormatterPreferencePage.comment_separateroottags.label"); //$NON-NLS-1$ slave= addCheckBox(commentComposite, label, PREF_COMMENT_SEPARATEROOTTAGS, trueFalse, 20); createSelectionDependency(master, slave); label= PreferencesMessages.getString("CodeFormatterPreferencePage.comment_newlineparam.label"); //$NON-NLS-1$ slave= addCheckBox(commentComposite, label, PREF_COMMENT_NEWLINEPARAM, trueFalse, 20); createSelectionDependency(master, slave); label= PreferencesMessages.getString("CodeFormatterPreferencePage.comment_indentroottags.label"); //$NON-NLS-1$ Button indentRootTags= addCheckBox(commentComposite, label, PREF_COMMENT_INDENTROOTTAGS, trueFalse, 20); createSelectionDependency(master, indentRootTags); label= PreferencesMessages.getString("CodeFormatterPreferencePage.comment_indentparamdesc.label"); //$NON-NLS-1$ slave= addCheckBox(commentComposite, label, PREF_COMMENT_INDENTPARAMDESC, trueFalse, 20); createEnableDependency(master, indentRootTags, slave); TabItem item= new TabItem(folder, SWT.NONE); item.setText(PreferencesMessages.getString("CodeFormatterPreferencePage.tab.newline.tabtitle")); //$NON-NLS-1$ item.setControl(newlineComposite); item= new TabItem(folder, SWT.NONE); item.setText(PreferencesMessages.getString("CodeFormatterPreferencePage.tab.linesplit.tabtitle")); //$NON-NLS-1$ item.setControl(lineSplittingComposite); item= new TabItem(folder, SWT.NONE); item.setText(PreferencesMessages.getString("CodeFormatterPreferencePage.tab.style.tabtitle")); //$NON-NLS-1$ item.setControl(styleComposite); item= new TabItem(folder, SWT.NONE); item.setText(PreferencesMessages.getString("CodeFormatterPreferencePage.tab.comment.tabtitle")); //$NON-NLS-1$ item.setControl(commentComposite); fSourceViewer= createPreview(parent); updatePreview(); return composite; } private static void createEnableDependency(final Button chief, final Button master, final Control slave) { SelectionListener listener= new SelectionListener() { public void widgetSelected(SelectionEvent e) { slave.setEnabled(master.getSelection() && chief.getSelection()); } public void widgetDefaultSelected(SelectionEvent e) { } }; chief.addSelectionListener(listener); master.addSelectionListener(listener); slave.setEnabled(master.getSelection() && chief.getSelection()); } private static void createSelectionDependency(final Button master, final Control slave) { master.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { slave.setEnabled(master.getSelection()); } public void widgetDefaultSelected(SelectionEvent e) { } }); slave.setEnabled(master.getSelection()); } private SourceViewer createPreview(Composite parent) { SourceViewer previewViewer= new JavaSourceViewer(parent, null, null, false, SWT.READ_ONLY | SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER); previewViewer.configure(fViewerConfiguration); previewViewer.getTextWidget().setFont(JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT)); previewViewer.getTextWidget().setTabs(getPositiveIntValue((String) fWorkingValues.get(PREF_TAB_SIZE), 0)); previewViewer.setDocument(fPreviewDocument); Control control= previewViewer.getControl(); GridData gdata= new GridData(GridData.FILL_BOTH); gdata.widthHint= fPixelConverter.convertWidthInCharsToPixels(30); gdata.heightHint= fPixelConverter.convertHeightInCharsToPixels(12); control.setLayoutData(gdata); return previewViewer; } /* * @see org.eclipse.jdt.internal.ui.preferences.OptionsConfigurationBlock#validateSettings(java.lang.String, java.lang.String) */ protected void validateSettings(String changedKey, String newValue) { if (changedKey == null || PREF_CODE_SPLIT.equals(changedKey)) { String lineNumber= (String)fWorkingValues.get(PREF_CODE_SPLIT); fCodeLengthStatus= validatePositiveNumber(lineNumber, 4); } if (changedKey == null || PREF_COMMENT_LINELENGTH.equals(changedKey)) { String lineNumber= (String)fWorkingValues.get(PREF_COMMENT_LINELENGTH); fCommentLengthStatus= validatePositiveNumber(lineNumber, 4); } if (changedKey == null || PREF_TAB_SIZE.equals(changedKey)) { String tabSize= (String)fWorkingValues.get(PREF_TAB_SIZE); fTabSizeStatus= validatePositiveNumber(tabSize, 0); int oldTabSize= fSourceViewer.getTextWidget().getTabs(); if (fTabSizeStatus.matches(IStatus.ERROR)) { fWorkingValues.put(PREF_TAB_SIZE, String.valueOf(oldTabSize)); // set back } else { fSourceViewer.getTextWidget().setTabs(getPositiveIntValue(tabSize, 0)); } } final IStatus status= StatusUtil.getMostSevere(new IStatus[] { fCodeLengthStatus, fCommentLengthStatus, fTabSizeStatus }); fContext.statusChanged(status); if (!status.matches(IStatus.ERROR)) updatePreview(); } private String loadPreviewFile(String filename) { String separator= System.getProperty("line.separator"); //$NON-NLS-1$ StringBuffer btxt= new StringBuffer(512); BufferedReader rin= null; try { rin= new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(filename))); String line; while ((line= rin.readLine()) != null) { if (btxt.length() > 0) { btxt.append(separator); } btxt.append(line); } } catch (IOException io) { JavaPlugin.log(io); } finally { if (rin != null) { try { rin.close(); } catch (IOException e) {} } } return btxt.toString(); } private void updatePreview() { fSourceViewer.setRedraw(false); fPreviewDocument.set(fPreviewText); final IFormattingContext context= new CommentFormattingContext(); try { final IContentFormatter formatter= fViewerConfiguration.getContentFormatter(fSourceViewer); if (formatter instanceof IContentFormatterExtension2) { final IContentFormatterExtension2 extension= (IContentFormatterExtension2)formatter; context.setProperty(FormattingContextProperties.CONTEXT_PREFERENCES, fWorkingValues); context.setProperty(FormattingContextProperties.CONTEXT_DOCUMENT, Boolean.valueOf(true)); extension.format(fPreviewDocument, context); } else formatter.format(fPreviewDocument, new Region(0, fPreviewDocument.getLength())); } finally { fSourceViewer.setSelectedRange(0, 0); context.dispose(); fSourceViewer.setRedraw(true); } } private IStatus validatePositiveNumber(String number, int threshold) { StatusInfo status= new StatusInfo(); if (number.length() == 0) { status.setError(PreferencesMessages.getString("CodeFormatterPreferencePage.empty_input")); //$NON-NLS-1$ } else { try { int value= Integer.parseInt(number); if (value < threshold) { status.setError(PreferencesMessages.getFormattedString("CodeFormatterPreferencePage.invalid_input", number)); //$NON-NLS-1$ } } catch (NumberFormatException e) { status.setError(PreferencesMessages.getFormattedString("CodeFormatterPreferencePage.invalid_input", number)); //$NON-NLS-1$ } } return status; } private static int getPositiveIntValue(String string, int dflt) { try { int i= Integer.parseInt(string); if (i >= 0) { return i; } } catch (NumberFormatException e) { } return dflt; } /* * @see org.eclipse.jdt.internal.ui.preferences.OptionsConfigurationBlock#getFullBuildDialogStrings(boolean) */ protected String[] getFullBuildDialogStrings(boolean workspaceSettings) { return null; // no build required } /* * @see org.eclipse.jdt.internal.ui.preferences.OptionsConfigurationBlock#getDefaultOptions() */ protected Map getDefaultOptions() { final Map map= super.getDefaultOptions(); final IFormattingContext context= new CommentFormattingContext(); context.storeToMap(PreferenceConstants.getPreferenceStore(), map, true); return map; } /* * @see org.eclipse.jdt.internal.ui.preferences.OptionsConfigurationBlock#getOptions(boolean) */ protected Map getOptions(boolean inheritJavaCoreOptions) { final Map map= super.getOptions(inheritJavaCoreOptions); final IFormattingContext context= new CommentFormattingContext(); context.storeToMap(PreferenceConstants.getPreferenceStore(), map, false); return map; } /* * @see org.eclipse.jdt.internal.ui.preferences.OptionsConfigurationBlock#performOk(boolean) */ public boolean performOk(boolean enabled) { if (super.performOk(enabled)) { final IFormattingContext context= new CommentFormattingContext(); context.mapToStore(fWorkingValues, PreferenceConstants.getPreferenceStore()); return true; } return false; } }
43,551
Bug 43551 Background conflicts with syntax highlighting in Edit Template of code gneration [code generation]
I have set my syntax highlighting colors. They use white foreground and black background for comments. In Preferences Java Code Generation Code & Comments If I edit an comment entry, eg Types I can not see the comments as it is using the syntax highlighting setting of white foreground but does not use the syntax highlighted background (black) but uses a default background of white. So I get white on white. It needs to either use all syntax highlight colors including background or default colors or no colors.
resolved fixed
15d9b60
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-01T13:19:04Z
2003-09-24T07:53:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/EditTemplateDialog.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.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.custom.VerifyKeyListener; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.Widget; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.GroupMarker; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferenceConverter; import org.eclipse.jface.resource.JFaceResources; 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.ITextHover; import org.eclipse.jface.text.ITextListener; import org.eclipse.jface.text.ITextOperationTarget; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.ITextViewerExtension; import org.eclipse.jface.text.TextEvent; import org.eclipse.jface.text.contentassist.ContentAssistant; import org.eclipse.jface.text.contentassist.IContentAssistant; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.jface.text.source.SourceViewer; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.ui.texteditor.ITextEditorActionConstants; import org.eclipse.ui.texteditor.IUpdate; import org.eclipse.jdt.ui.IContextMenuConstants; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.text.IColorManager; import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration; import org.eclipse.jdt.ui.text.JavaTextTools; import org.eclipse.jdt.internal.corext.template.ContextType; import org.eclipse.jdt.internal.corext.template.ContextTypeRegistry; import org.eclipse.jdt.internal.corext.template.Template; import org.eclipse.jdt.internal.corext.template.TemplateMessages; import org.eclipse.jdt.internal.corext.template.TemplateVariable; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dialogs.StatusDialog; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.text.IJavaPartitions; import org.eclipse.jdt.internal.ui.text.JavaWordFinder; import org.eclipse.jdt.internal.ui.text.template.TemplateVariableProcessor; import org.eclipse.jdt.internal.ui.util.SWTUtil; /** * Dialog to edit a template. */ public class EditTemplateDialog extends StatusDialog { private static class SimpleJavaSourceViewerConfiguration extends JavaSourceViewerConfiguration { private final TemplateVariableProcessor fProcessor; SimpleJavaSourceViewerConfiguration(JavaTextTools tools, ITextEditor editor, TemplateVariableProcessor processor) { super(tools, editor); fProcessor= processor; } /* * @see SourceViewerConfiguration#getContentAssistant(ISourceViewer) */ public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) { IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools(); IColorManager manager= textTools.getColorManager(); ContentAssistant assistant= new ContentAssistant(); assistant.setContentAssistProcessor(fProcessor, IDocument.DEFAULT_CONTENT_TYPE); // Register the same processor for strings and single line comments to get code completion at the start of those partitions. assistant.setContentAssistProcessor(fProcessor, IJavaPartitions.JAVA_STRING); assistant.setContentAssistProcessor(fProcessor, IJavaPartitions.JAVA_CHARACTER); assistant.setContentAssistProcessor(fProcessor, IJavaPartitions.JAVA_SINGLE_LINE_COMMENT); assistant.setContentAssistProcessor(fProcessor, IJavaPartitions.JAVA_MULTI_LINE_COMMENT); assistant.setContentAssistProcessor(fProcessor, IJavaPartitions.JAVA_DOC); assistant.enableAutoInsert(store.getBoolean(PreferenceConstants.CODEASSIST_AUTOINSERT)); assistant.enableAutoActivation(store.getBoolean(PreferenceConstants.CODEASSIST_AUTOACTIVATION)); assistant.setAutoActivationDelay(store.getInt(PreferenceConstants.CODEASSIST_AUTOACTIVATION_DELAY)); assistant.setProposalPopupOrientation(ContentAssistant.PROPOSAL_OVERLAY); assistant.setContextInformationPopupOrientation(ContentAssistant.CONTEXT_INFO_ABOVE); assistant.setInformationControlCreator(getInformationControlCreator(sourceViewer)); Color background= getColor(store, PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND, manager); assistant.setContextInformationPopupBackground(background); assistant.setContextSelectorBackground(background); assistant.setProposalSelectorBackground(background); Color foreground= getColor(store, PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND, manager); assistant.setContextInformationPopupForeground(foreground); assistant.setContextSelectorForeground(foreground); assistant.setProposalSelectorForeground(foreground); return assistant; } private Color getColor(IPreferenceStore store, String key, IColorManager manager) { RGB rgb= PreferenceConverter.getColor(store, key); return manager.getColor(rgb); } /* * @see SourceViewerConfiguration#getTextHover(ISourceViewer, String, int) * @since 2.1 */ public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType, int stateMask) { return new TemplateVariableTextHover(fProcessor); } } private static class TemplateVariableTextHover implements ITextHover { private TemplateVariableProcessor fProcessor; /** * @param type */ public TemplateVariableTextHover(TemplateVariableProcessor processor) { fProcessor= processor; } /* (non-Javadoc) * @see org.eclipse.jface.text.ITextHover#getHoverInfo(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion) */ public String getHoverInfo(ITextViewer textViewer, IRegion subject) { try { IDocument doc= textViewer.getDocument(); int offset= subject.getOffset(); if (offset >= 2 && "${".equals(doc.get(offset-2, 2))) { //$NON-NLS-1$ String varName= doc.get(offset, subject.getLength()); Iterator iter= fProcessor.getContextType().variableIterator(); while (iter.hasNext()) { TemplateVariable var= (TemplateVariable) iter.next(); if (varName.equals(var.getName())) { return var.getDescription(); } } } } catch (BadLocationException e) { } return null; } /* (non-Javadoc) * @see org.eclipse.jface.text.ITextHover#getHoverRegion(org.eclipse.jface.text.ITextViewer, int) */ public IRegion getHoverRegion(ITextViewer textViewer, int offset) { if (textViewer != null) { return JavaWordFinder.findWord(textViewer.getDocument(), offset); } return null; } } private static class TextViewerAction extends Action implements IUpdate { private int fOperationCode= -1; private ITextOperationTarget fOperationTarget; public TextViewerAction(ITextViewer viewer, int operationCode) { fOperationCode= operationCode; fOperationTarget= viewer.getTextOperationTarget(); update(); } /** * Updates the enabled state of the action. * Fires a property change if the enabled state changes. * * @see Action#firePropertyChange(String, Object, Object) */ public void update() { boolean wasEnabled= isEnabled(); boolean isEnabled= (fOperationTarget != null && fOperationTarget.canDoOperation(fOperationCode)); setEnabled(isEnabled); if (wasEnabled != isEnabled) { firePropertyChange(ENABLED, wasEnabled ? Boolean.TRUE : Boolean.FALSE, isEnabled ? Boolean.TRUE : Boolean.FALSE); } } /** * @see Action#run() */ public void run() { if (fOperationCode != -1 && fOperationTarget != null) { fOperationTarget.doOperation(fOperationCode); } } } private final Template fTemplate; private Text fNameText; private Text fDescriptionText; private Combo fContextCombo; private SourceViewer fPatternEditor; private Button fInsertVariableButton; private boolean fIsNameModifiable; private StatusInfo fValidationStatus; private boolean fSuppressError= true; // #4354 private Map fGlobalActions= new HashMap(10); private List fSelectionActions = new ArrayList(3); private String[] fContextTypes; private final TemplateVariableProcessor fProcessor= new TemplateVariableProcessor(); public EditTemplateDialog(Shell parent, Template template, boolean edit, boolean isNameModifiable, String[] contextTypes) { super(parent); setShellStyle(getShellStyle() | SWT.MAX | SWT.RESIZE); String title= edit ? TemplateMessages.getString("EditTemplateDialog.title.edit") //$NON-NLS-1$ : TemplateMessages.getString("EditTemplateDialog.title.new"); //$NON-NLS-1$ setTitle(title); fTemplate= template; fIsNameModifiable= isNameModifiable; fContextTypes= contextTypes; fValidationStatus= new StatusInfo(); ContextType type= ContextTypeRegistry.getInstance().getContextType(template.getContextTypeName()); fProcessor.setContextType(type); } /* * @see Dialog#createDialogArea(Composite) */ protected Control createDialogArea(Composite ancestor) { Composite parent= new Composite(ancestor, SWT.NONE); GridLayout layout= new GridLayout(); layout.numColumns= 2; parent.setLayout(layout); parent.setLayoutData(new GridData(GridData.FILL_BOTH)); ModifyListener listener= new ModifyListener() { public void modifyText(ModifyEvent e) { doTextWidgetChanged(e.widget); } }; if (fIsNameModifiable) { createLabel(parent, TemplateMessages.getString("EditTemplateDialog.name")); //$NON-NLS-1$ Composite composite= new Composite(parent, SWT.NONE); composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); layout= new GridLayout(); layout.numColumns= 3; layout.marginWidth= 0; layout.marginHeight= 0; composite.setLayout(layout); fNameText= createText(composite); fNameText.addModifyListener(listener); createLabel(composite, TemplateMessages.getString("EditTemplateDialog.context")); //$NON-NLS-1$ fContextCombo= new Combo(composite, SWT.READ_ONLY); for (int i= 0; i < fContextTypes.length; i++) { fContextCombo.add(fContextTypes[i]); } fContextCombo.addModifyListener(listener); } createLabel(parent, TemplateMessages.getString("EditTemplateDialog.description")); //$NON-NLS-1$ int descFlags= fIsNameModifiable ? SWT.BORDER : SWT.BORDER | SWT.READ_ONLY; fDescriptionText= new Text(parent, descFlags ); fDescriptionText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); fDescriptionText.addModifyListener(listener); Label patternLabel= createLabel(parent, TemplateMessages.getString("EditTemplateDialog.pattern")); //$NON-NLS-1$ patternLabel.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING)); fPatternEditor= createEditor(parent); Label filler= new Label(parent, SWT.NONE); filler.setLayoutData(new GridData()); Composite composite= new Composite(parent, SWT.NONE); layout= new GridLayout(); layout.marginWidth= 0; layout.marginHeight= 0; composite.setLayout(layout); composite.setLayoutData(new GridData()); fInsertVariableButton= new Button(composite, SWT.NONE); fInsertVariableButton.setLayoutData(getButtonGridData(fInsertVariableButton)); fInsertVariableButton.setText(TemplateMessages.getString("EditTemplateDialog.insert.variable")); //$NON-NLS-1$ fInsertVariableButton.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { fPatternEditor.getTextWidget().setFocus(); fPatternEditor.doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS); } public void widgetDefaultSelected(SelectionEvent e) {} }); fDescriptionText.setText(fTemplate.getDescription()); if (fIsNameModifiable) { fNameText.setText(fTemplate.getName()); fContextCombo.select(getIndex(fTemplate.getContextTypeName())); } else { fPatternEditor.getControl().setFocus(); } initializeActions(); applyDialogFont(parent); return composite; } protected void doTextWidgetChanged(Widget w) { if (w == fNameText) { String name= fNameText.getText(); if (fSuppressError && (name.trim().length() != 0)) fSuppressError= false; fTemplate.setName(name); updateButtons(); } else if (w == fContextCombo) { String name= fContextCombo.getText(); fTemplate.setContext(name); fProcessor.setContextType(ContextTypeRegistry.getInstance().getContextType(name)); } else if (w == fDescriptionText) { String desc= fDescriptionText.getText(); fTemplate.setDescription(desc); } } protected void doSourceChanged(IDocument document) { String text= document.get(); fTemplate.setPattern(text); fValidationStatus.setOK(); ContextType contextType= ContextTypeRegistry.getInstance().getContextType(fTemplate.getContextTypeName()); if (contextType != null) { try { String errorMessage= contextType.validate(text); if (errorMessage != null) { fValidationStatus.setError(errorMessage); } } catch (CoreException e) { JavaPlugin.log(e); } } updateUndoAction(); updateButtons(); } private static GridData getButtonGridData(Button button) { GridData data= new GridData(GridData.FILL_HORIZONTAL); data.heightHint= SWTUtil.getButtonHeightHint(button); return data; } private static Label createLabel(Composite parent, String name) { Label label= new Label(parent, SWT.NULL); label.setText(name); label.setLayoutData(new GridData()); return label; } private static Text createText(Composite parent) { Text text= new Text(parent, SWT.BORDER); text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); return text; } private SourceViewer createEditor(Composite parent) { SourceViewer viewer= new SourceViewer(parent, null, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL); IDocument document= new Document(fTemplate.getPattern()); JavaTextTools tools= JavaPlugin.getDefault().getJavaTextTools(); tools.setupJavaDocumentPartitioner(document); viewer.configure(new SimpleJavaSourceViewerConfiguration(tools, null, fProcessor)); viewer.setEditable(true); viewer.setDocument(document); Font font= JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT); viewer.getTextWidget().setFont(font); int nLines= document.getNumberOfLines(); if (nLines < 5) { nLines= 5; } else if (nLines > 12) { nLines= 12; } Control control= viewer.getControl(); GridData data= new GridData(GridData.FILL_BOTH); data.widthHint= convertWidthInCharsToPixels(80); data.heightHint= convertHeightInCharsToPixels(nLines); control.setLayoutData(data); viewer.addTextListener(new ITextListener() { public void textChanged(TextEvent event) { if (event .getDocumentEvent() != null) doSourceChanged(event.getDocumentEvent().getDocument()); } }); viewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { updateSelectionDependentActions(); } }); if (viewer instanceof ITextViewerExtension) { ((ITextViewerExtension) viewer).prependVerifyKeyListener(new VerifyKeyListener() { public void verifyKey(VerifyEvent event) { handleVerifyKeyPressed(event); } }); } else { viewer.getTextWidget().addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { handleKeyPressed(e); } public void keyReleased(KeyEvent e) {} }); } return viewer; } private void handleKeyPressed(KeyEvent event) { if (event.stateMask != SWT.MOD1) return; switch (event.character) { case ' ': fPatternEditor.doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS); break; // CTRL-Z case 'z' - 'a' + 1: fPatternEditor.doOperation(ITextOperationTarget.UNDO); break; } } private void handleVerifyKeyPressed(VerifyEvent event) { if (!event.doit) return; if (event.stateMask != SWT.MOD1) return; switch (event.character) { case ' ': fPatternEditor.doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS); event.doit= false; break; // CTRL-Z case 'z' - 'a' + 1: fPatternEditor.doOperation(ITextOperationTarget.UNDO); event.doit= false; break; } } private void initializeActions() { TextViewerAction action= new TextViewerAction(fPatternEditor, SourceViewer.UNDO); action.setText(TemplateMessages.getString("EditTemplateDialog.undo")); //$NON-NLS-1$ fGlobalActions.put(ITextEditorActionConstants.UNDO, action); action= new TextViewerAction(fPatternEditor, SourceViewer.CUT); action.setText(TemplateMessages.getString("EditTemplateDialog.cut")); //$NON-NLS-1$ fGlobalActions.put(ITextEditorActionConstants.CUT, action); action= new TextViewerAction(fPatternEditor, SourceViewer.COPY); action.setText(TemplateMessages.getString("EditTemplateDialog.copy")); //$NON-NLS-1$ fGlobalActions.put(ITextEditorActionConstants.COPY, action); action= new TextViewerAction(fPatternEditor, SourceViewer.PASTE); action.setText(TemplateMessages.getString("EditTemplateDialog.paste")); //$NON-NLS-1$ fGlobalActions.put(ITextEditorActionConstants.PASTE, action); action= new TextViewerAction(fPatternEditor, SourceViewer.SELECT_ALL); action.setText(TemplateMessages.getString("EditTemplateDialog.select.all")); //$NON-NLS-1$ fGlobalActions.put(ITextEditorActionConstants.SELECT_ALL, action); action= new TextViewerAction(fPatternEditor, SourceViewer.CONTENTASSIST_PROPOSALS); action.setText(TemplateMessages.getString("EditTemplateDialog.content.assist")); //$NON-NLS-1$ fGlobalActions.put("ContentAssistProposal", action); //$NON-NLS-1$ fSelectionActions.add(ITextEditorActionConstants.CUT); fSelectionActions.add(ITextEditorActionConstants.COPY); fSelectionActions.add(ITextEditorActionConstants.PASTE); // create context menu MenuManager manager= new MenuManager(null, null); manager.setRemoveAllWhenShown(true); manager.addMenuListener(new IMenuListener() { public void menuAboutToShow(IMenuManager mgr) { fillContextMenu(mgr); } }); StyledText text= fPatternEditor.getTextWidget(); Menu menu= manager.createContextMenu(text); text.setMenu(menu); } private void fillContextMenu(IMenuManager menu) { menu.add(new GroupMarker(ITextEditorActionConstants.GROUP_UNDO)); menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, (IAction) fGlobalActions.get(ITextEditorActionConstants.UNDO)); menu.add(new Separator(ITextEditorActionConstants.GROUP_EDIT)); menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.CUT)); menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.COPY)); menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.PASTE)); menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.SELECT_ALL)); menu.add(new Separator(IContextMenuConstants.GROUP_GENERATE)); menu.appendToGroup(IContextMenuConstants.GROUP_GENERATE, (IAction) fGlobalActions.get("ContentAssistProposal")); //$NON-NLS-1$ } protected void updateSelectionDependentActions() { Iterator iterator= fSelectionActions.iterator(); while (iterator.hasNext()) updateAction((String)iterator.next()); } protected void updateUndoAction() { IAction action= (IAction) fGlobalActions.get(ITextEditorActionConstants.UNDO); if (action instanceof IUpdate) ((IUpdate) action).update(); } protected void updateAction(String actionId) { IAction action= (IAction) fGlobalActions.get(actionId); if (action instanceof IUpdate) ((IUpdate) action).update(); } private int getIndex(String context) { ContextTypeRegistry registry= ContextTypeRegistry.getInstance(); registry.getContextType(context); if (context == null) return -1; for (int i= 0; i < fContextTypes.length; i++) { if (context.equals(fContextTypes[i])) { return i; } } return -1; } protected void okPressed() { super.okPressed(); } private void updateButtons() { StatusInfo status; boolean valid= fNameText == null || fNameText.getText().trim().length() != 0; if (!valid) { status = new StatusInfo(); if (!fSuppressError) { status.setError(TemplateMessages.getString("EditTemplateDialog.error.noname")); //$NON-NLS-1$ } } else { status= fValidationStatus; } updateStatus(status); } /* * @see org.eclipse.jface.window.Window#configureShell(Shell) */ protected void configureShell(Shell newShell) { super.configureShell(newShell); WorkbenchHelp.setHelp(newShell, IJavaHelpContextIds.EDIT_TEMPLATE_DIALOG); } }
42,690
Bug 42690 Loading .importorder file fails when package prefix entry starts with an uppercase letter [code manipulation]
After saving my manually configured import order definition in the organize imports preferences page, I can't load it again ( Error Box: Not a valid import order file). The reason seems to be the existence of package prefix entrys which start with an uppercase letter.
resolved fixed
397fa9b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-01T13:21:05Z
2003-09-08T11:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/ImportOrganizePreferencePage.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.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.StringTokenizer; import org.eclipse.core.runtime.IStatus; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.window.Window; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.core.JavaConventions; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.PreferenceConstants; 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.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener; 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; import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField; /* * The page for setting the organize import settings */ public class ImportOrganizePreferencePage extends PreferencePage implements IWorkbenchPreferencePage { private static final String PREF_IMPORTORDER= PreferenceConstants.ORGIMPORTS_IMPORTORDER; private static final String PREF_ONDEMANDTHRESHOLD= PreferenceConstants.ORGIMPORTS_ONDEMANDTHRESHOLD; private static final String PREF_IGNORELOWERCASE= PreferenceConstants.ORGIMPORTS_IGNORELOWERCASE; private static final String PREF_LASTLOADPATH= JavaUI.ID_PLUGIN + ".importorder.loadpath"; //$NON-NLS-1$ private static final String PREF_LASTSAVEPATH= JavaUI.ID_PLUGIN + ".importorder.savepath"; //$NON-NLS-1$ /** * @deprecated Inline to avoid reference to preference page */ public static String[] getImportOrderPreference() { IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore(); String str= prefs.getString(PREF_IMPORTORDER); if (str != null) { return unpackOrderList(str); } return new String[0]; } private static String[] unpackOrderList(String str) { StringTokenizer tok= new StringTokenizer(str, ";"); //$NON-NLS-1$ int nTokens= tok.countTokens(); String[] res= new String[nTokens]; for (int i= 0; i < nTokens; i++) { res[i]= tok.nextToken(); } return res; } private static String packOrderList(List orderList) { StringBuffer buf= new StringBuffer(); for (int i= 0; i < orderList.size(); i++) { buf.append((String) orderList.get(i)); buf.append(';'); } return buf.toString(); } /** * @deprecated Inline to avoid reference to preference page */ public static int getImportNumberThreshold() { IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore(); int threshold= prefs.getInt(PREF_ONDEMANDTHRESHOLD); if (threshold < 0) { threshold= Integer.MAX_VALUE; } return threshold; } /** * @deprecated Inline to avoid reference to preference page */ public static boolean doIgnoreLowerCaseNames() { IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore(); return prefs.getBoolean(PREF_IGNORELOWERCASE); } private static class ImportOrganizeLabelProvider extends LabelProvider { private static final Image PCK_ICON= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_PACKAGE); public Image getImage(Object element) { return PCK_ICON; } } private class ImportOrganizeAdapter implements IListAdapter, IDialogFieldListener { private boolean canEdit(ListDialogField field) { return field.getSelectedElements().size() == 1; } public void customButtonPressed(ListDialogField field, int index) { doButtonPressed(index); } public void selectionChanged(ListDialogField field) { fOrderListField.enableButton(1, canEdit(field)); } public void dialogFieldChanged(DialogField field) { if (field == fThresholdField) { doThresholdChanged(); } } public void doubleClicked(ListDialogField field) { if (canEdit(field)) { doButtonPressed(1); } } } private ListDialogField fOrderListField; private StringDialogField fThresholdField; private SelectionButtonDialogField fIgnoreLowerCaseTypesField; public ImportOrganizePreferencePage() { super(); setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore()); setDescription(PreferencesMessages.getString("ImportOrganizePreferencePage.description")); //$NON-NLS-1$ String[] buttonLabels= new String[] { /* 0 */ PreferencesMessages.getString("ImportOrganizePreferencePage.order.add.button"), //$NON-NLS-1$ /* 1 */ PreferencesMessages.getString("ImportOrganizePreferencePage.order.edit.button"), //$NON-NLS-1$ /* 2 */ null, /* 3 */ PreferencesMessages.getString("ImportOrganizePreferencePage.order.up.button"), //$NON-NLS-1$ /* 4 */ PreferencesMessages.getString("ImportOrganizePreferencePage.order.down.button"), //$NON-NLS-1$ /* 5 */ null, /* 6 */ PreferencesMessages.getString("ImportOrganizePreferencePage.order.remove.button"), //$NON-NLS-1$ /* 7 */ null, /* 8 */ PreferencesMessages.getString("ImportOrganizePreferencePage.order.load.button"), //$NON-NLS-1$ /* 9 */ PreferencesMessages.getString("ImportOrganizePreferencePage.order.save.button") //$NON-NLS-1$ }; ImportOrganizeAdapter adapter= new ImportOrganizeAdapter(); fOrderListField= new ListDialogField(adapter, buttonLabels, new ImportOrganizeLabelProvider()); fOrderListField.setDialogFieldListener(adapter); fOrderListField.setLabelText(PreferencesMessages.getString("ImportOrganizePreferencePage.order.label")); //$NON-NLS-1$ fOrderListField.setUpButtonIndex(3); fOrderListField.setDownButtonIndex(4); fOrderListField.setRemoveButtonIndex(6); fOrderListField.enableButton(1, false); fThresholdField= new StringDialogField(); fThresholdField.setDialogFieldListener(adapter); fThresholdField.setLabelText(PreferencesMessages.getString("ImportOrganizePreferencePage.threshold.label")); //$NON-NLS-1$ fIgnoreLowerCaseTypesField= new SelectionButtonDialogField(SWT.CHECK); fIgnoreLowerCaseTypesField.setLabelText(PreferencesMessages.getString("ImportOrganizePreferencePage.ignoreLowerCase.label")); //$NON-NLS-1$ } /** * @see PreferencePage#createControl(org.eclipse.swt.widgets.Composite) */ public void createControl(Composite parent) { // added for 1GEUGE6: ITPJUI:WIN2000 - Help is the same on all preference pages super.createControl(parent); WorkbenchHelp.setHelp(getControl(), IJavaHelpContextIds.ORGANIZE_IMPORTS_PREFERENCE_PAGE); } protected Control createContents(Composite parent) { initializeDialogUnits(parent); initialize(getImportOrderPreference(), getImportNumberThreshold(), doIgnoreLowerCaseNames()); Composite composite= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(); layout.numColumns= 2; layout.marginWidth= 0; layout.marginHeight= 0; composite.setLayout(layout); fOrderListField.doFillIntoGrid(composite, 3); LayoutUtil.setHorizontalSpan(fOrderListField.getLabelControl(null), 2); LayoutUtil.setWidthHint(fOrderListField.getLabelControl(null), convertWidthInCharsToPixels(40)); LayoutUtil.setHorizontalGrabbing(fOrderListField.getListControl(null)); fThresholdField.doFillIntoGrid(composite, 2); ((GridData) fThresholdField.getTextControl(null).getLayoutData()).grabExcessHorizontalSpace= false; fIgnoreLowerCaseTypesField.doFillIntoGrid(composite, 2); Dialog.applyDialogFont(composite); return composite; } private void initialize(String[] importOrder, int threshold, boolean ignoreLowerCase) { fOrderListField.removeAllElements(); for (int i= 0; i < importOrder.length; i++) { fOrderListField.addElement(importOrder[i]); } fThresholdField.setText(String.valueOf(threshold)); fIgnoreLowerCaseTypesField.setSelection(ignoreLowerCase); } private void doThresholdChanged() { StatusInfo status= new StatusInfo(); String thresholdString= fThresholdField.getText(); try { int threshold= Integer.parseInt(thresholdString); if (threshold < 0) { status.setError(PreferencesMessages.getString("ImportOrganizePreferencePage.error.invalidthreshold")); //$NON-NLS-1$ } } catch (NumberFormatException e) { status.setError(PreferencesMessages.getString("ImportOrganizePreferencePage.error.invalidthreshold")); //$NON-NLS-1$ } updateStatus(status); } private void doButtonPressed(int index) { if (index == 0) { // add new List existing= fOrderListField.getElements(); ImportOrganizeInputDialog dialog= new ImportOrganizeInputDialog(getShell(), existing); if (dialog.open() == Window.OK) { fOrderListField.addElement(dialog.getResult()); } } else if (index == 1) { // edit List selected= fOrderListField.getSelectedElements(); if (selected.isEmpty()) { return; } String editedEntry= (String) selected.get(0); List existing= fOrderListField.getElements(); existing.remove(editedEntry); ImportOrganizeInputDialog dialog= new ImportOrganizeInputDialog(getShell(), existing); dialog.setInitialString(editedEntry); if (dialog.open() == Window.OK) { fOrderListField.replaceElement(editedEntry, dialog.getResult()); } } else if (index == 8) { // load List order= loadImportOrder(); if (order != null) { fOrderListField.setElements(order); } } else if (index == 9) { // save saveImportOrder(fOrderListField.getElements()); } } /** * The import order file is a property file. The keys are * "0", "1" ... last entry. The values must be valid package names. */ private List loadFromProperties(Properties properties) { ArrayList res= new ArrayList(); int nEntries= properties.size(); for (int i= 0 ; i < nEntries; i++) { String curr= properties.getProperty(String.valueOf(i)); if (curr != null) { if (JavaConventions.validatePackageName(curr).isOK()) { res.add(curr); } else { return null; } } else { return res; } } return res; } private List loadImportOrder() { FileDialog dialog= new FileDialog(getShell(), SWT.OPEN); dialog.setText(PreferencesMessages.getString("ImportOrganizePreferencePage.loadDialog.title")); //$NON-NLS-1$) dialog.setFilterExtensions(new String[] {"*.importorder", "*.*"}); //$NON-NLS-1$ //$NON-NLS-2$ String lastPath= getPreferenceStore().getString(PREF_LASTLOADPATH); if (lastPath != null) { dialog.setFilterPath(lastPath); } String fileName= dialog.open(); if (fileName != null) { getPreferenceStore().putValue(PREF_LASTLOADPATH, dialog.getFilterPath()); Properties properties= new Properties(); FileInputStream fis= null; try { fis= new FileInputStream(fileName); properties.load(fis); List res= loadFromProperties(properties); if (res != null) { return res; } } catch (IOException e) { JavaPlugin.log(e); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) {} } } String title= PreferencesMessages.getString("ImportOrganizePreferencePage.loadDialog.error.title"); //$NON-NLS-1$ String message= PreferencesMessages.getString("ImportOrganizePreferencePage.loadDialog.error.message"); //$NON-NLS-1$ MessageDialog.openError(getShell(), title, message); } return null; } private void saveImportOrder(List elements) { FileDialog dialog= new FileDialog(getShell(), SWT.SAVE); dialog.setText(PreferencesMessages.getString("ImportOrganizePreferencePage.saveDialog.title")); //$NON-NLS-1$) dialog.setFilterExtensions(new String[] {"*.importorder", "*.*"}); //$NON-NLS-1$ //$NON-NLS-2$ dialog.setFileName("example.importorder"); //$NON-NLS-1$ String lastPath= getPreferenceStore().getString(PREF_LASTSAVEPATH); if (lastPath != null) { dialog.setFilterPath(lastPath); } String fileName= dialog.open(); if (fileName != null) { getPreferenceStore().putValue(PREF_LASTSAVEPATH, dialog.getFilterPath()); Properties properties= new Properties(); for (int i= 0; i < elements.size(); i++) { properties.setProperty(String.valueOf(i), (String) elements.get(i)); } FileOutputStream fos= null; try { fos= new FileOutputStream(fileName); properties.store(fos, "Organize Import Order"); //$NON-NLS-1$ } catch (IOException e) { JavaPlugin.log(e); String title= PreferencesMessages.getString("ImportOrganizePreferencePage.saveDialog.error.title"); //$NON-NLS-1$ String message= PreferencesMessages.getString("ImportOrganizePreferencePage.saveDialog.error.message"); //$NON-NLS-1$ MessageDialog.openError(getShell(), title, message); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) {} } } } } public void init(IWorkbench workbench) { } private void updateStatus(IStatus status) { setValid(!status.matches(IStatus.ERROR)); StatusUtil.applyToStatusLine(this, status); } /** * @see PreferencePage#performDefaults() */ protected void performDefaults() { String[] order; IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore(); String str= prefs.getDefaultString(PREF_IMPORTORDER); if (str != null) { order= unpackOrderList(str); } else { order= new String[0]; } int threshold= prefs.getDefaultInt(PREF_ONDEMANDTHRESHOLD); if (threshold < 0) { threshold= Integer.MAX_VALUE; } boolean ignoreLowerCase= prefs.getDefaultBoolean(PREF_IGNORELOWERCASE); initialize(order, threshold, ignoreLowerCase); super.performDefaults(); } /** * @see org.eclipse.jface.preference.IPreferencePage#performOk() */ public boolean performOk() { IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore(); prefs.setValue(PREF_IMPORTORDER, packOrderList(fOrderListField.getElements())); prefs.setValue(PREF_ONDEMANDTHRESHOLD, fThresholdField.getText()); prefs.setValue(PREF_IGNORELOWERCASE, fIgnoreLowerCaseTypesField.isSelected()); JavaPlugin.getDefault().savePluginPreferences(); return true; } }
43,985
Bug 43985 NPE in ProblemsLabelDecorator
!ENTRY org.eclipse.jface 4 2 Okt 01, 2003 15:14:43.853 !MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jface". !STACK 0 java.lang.NullPointerException at org.eclipse.jdt.ui.ProblemsLabelDecorator.isAnnotationInRange(ProblemsLabelDecorator.java:264) at org.eclipse.jdt.ui.ProblemsLabelDecorator.getErrorTicksFromWorkingCopy(ProblemsLabelDecorator.java:245) at org.eclipse.jdt.ui.ProblemsLabelDecorator.computeAdornmentFlags(ProblemsLabelDecorator.java:184) at org.eclipse.jdt.ui.ProblemsLabelDecorator.decorateImage(ProblemsLabelDecorator.java:146) at org.eclipse.jdt.internal.ui.viewsupport.JavaUILabelProvider.decorateImage(JavaUILabelProvider.java:119) at org.eclipse.jdt.internal.ui.viewsupport.JavaUILabelProvider.getImage(JavaUILabelProvider.java:134) at org.eclipse.jface.viewers.DecoratingLabelProvider.getImage(DecoratingLabelProvider.java:73) at org.eclipse.jdt.internal.ui.viewsupport.DecoratingJavaLabelProvider.getImage(DecoratingJavaLabelProvider.java:103) at org.eclipse.jface.viewers.TreeViewer.doUpdateItem(TreeViewer.java:96) at org.eclipse.jface.viewers.AbstractTreeViewer$UpdateItemSafeRunnable.run(AbstractTreeViewer.java:77) at org.eclipse.core.internal.runtime.InternalPlatform.run(InternalPlatform.java:1034) at org.eclipse.core.runtime.Platform.run(Platform.java:432) at org.eclipse.jface.viewers.AbstractTreeViewer.doUpdateItem(AbstractTreeViewer.java:457) at org.eclipse.jface.viewers.AbstractTreeViewer.internalRefresh(AbstractTreeViewer.java:1016) at org.eclipse.jface.viewers.AbstractTreeViewer.internalRefresh(AbstractTreeViewer.java:1031) at org.eclipse.jface.viewers.AbstractTreeViewer.internalRefresh(AbstractTreeViewer.java:1031) at org.eclipse.jface.viewers.AbstractTreeViewer.labelProviderChanged(AbstractTreeViewer.java:1147) at org.eclipse.jface.viewers.ContentViewer.handleLabelProviderChanged(ContentViewer.java:161) at org.eclipse.jface.viewers.StructuredViewer.handleLabelProviderChanged(StructuredViewer.java:636) at org.eclipse.jdt.internal.ui.javaeditor.JavaOutlinePage$JavaOutlineViewer.handleLabelProviderChanged(JavaOutlinePage.java:672) at org.eclipse.jface.viewers.ContentViewer$1.labelProviderChanged(ContentViewer.java:74) at org.eclipse.ui.internal.decorators.DecoratorManager$1.run(DecoratorManager.java:148) at org.eclipse.core.internal.runtime.InternalPlatform.run(InternalPlatform.java:1034) at org.eclipse.core.runtime.Platform.run(Platform.java:432) at org.eclipse.ui.internal.decorators.DecoratorManager.fireListeners(DecoratorManager.java:146) at org.eclipse.ui.internal.decorators.DecorationScheduler$2.runInUIThread(DecorationScheduler.java:335) at org.eclipse.ui.progress.UIJob$1.run(UIJob.java:81) at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35) at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:102) at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:2150) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1867) at org.eclipse.ui.internal.dialogs.EventLoopProgressMonitor.runEventLoop(EventLoopProgressMonitor.java:94) at org.eclipse.ui.internal.dialogs.EventLoopProgressMonitor.done(EventLoopProgressMonitor.java:60) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1565) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1572) at org.eclipse.ui.actions.WorkspaceModifyOperation.run(WorkspaceModifyOperation.java:85) at org.eclipse.ui.texteditor.AbstractTextEditor.performSaveOperation(AbstractTextEditor.java:3190) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor.performSaveOperation(CompilationUnitEditor.java:817) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor.doSave(CompilationUnitEditor.java:881) at org.eclipse.ui.internal.EditorManager$11.run(EditorManager.java:1090) at org.eclipse.ui.internal.EditorManager$8.run(EditorManager.java:960) at org.eclipse.jface.operation.ModalContext.runInCurrentThread(ModalContext.java:302) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:252) at org.eclipse.jface.window.ApplicationWindow$1.run(ApplicationWindow.java:444) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:84) at org.eclipse.jface.window.ApplicationWindow.run(ApplicationWindow.java:441) at org.eclipse.ui.internal.WorkbenchWindow.run(WorkbenchWindow.java:1596) at org.eclipse.ui.internal.EditorManager.runProgressMonitorOperation(EditorManager.java:966) at org.eclipse.ui.internal.EditorManager.savePart(EditorManager.java:1095) at org.eclipse.ui.internal.WorkbenchPage.savePart(WorkbenchPage.java:2381) at org.eclipse.ui.internal.WorkbenchPage.saveEditor(WorkbenchPage.java:2393) at org.eclipse.ui.internal.SaveAction.run(SaveAction.java:57) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:543) at org.eclipse.jface.action.ActionContributionItem.access$4(ActionContributionItem.java:496) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent(ActionContributionItem.java:468) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2173) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1863) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2106) at org.eclipse.ui.internal.Workbench.run(Workbench.java:2089) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:298) at org.eclipse.core.launcher.Main.run(Main.java:764) at org.eclipse.core.launcher.Main.main(Main.java:598)
resolved fixed
af4f2c8
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-01T21:10:06Z
2003-10-01T14:53:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/ProblemsLabelDecorator.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.ui; import java.util.Iterator; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.source.Annotation; import org.eclipse.jface.text.source.IAnnotationModel; import org.eclipse.jface.viewers.IBaseLabelProvider; import org.eclipse.jface.viewers.IDecoration; import org.eclipse.jface.viewers.ILabelDecorator; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.ILightweightLabelDecorator; import org.eclipse.jface.viewers.LabelProviderChangedEvent; import org.eclipse.ui.part.FileEditorInput; import org.eclipse.ui.texteditor.MarkerAnnotation; import org.eclipse.jdt.core.ICompilationUnit; 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.internal.corext.refactoring.ListenerList; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.viewsupport.IProblemChangedListener; import org.eclipse.jdt.internal.ui.viewsupport.ImageDescriptorRegistry; import org.eclipse.jdt.internal.ui.viewsupport.ImageImageDescriptor; /** * LabelDecorator that decorates an element's image with error and warning overlays that * represent the severity of markers attached to the element's underlying resource. To see * a problem decoration for a marker, the marker needs to be a subtype of <code>IMarker.PROBLEM</code>. * <p> * Note: Only images for elements in Java projects are currently updated on marker changes. * </p> * * @since 2.0 */ public class ProblemsLabelDecorator implements ILabelDecorator, ILightweightLabelDecorator { /** * This is a special <code>LabelProviderChangedEvent</code> carring additional * information whether the event orgins from a maker change. * <p> * <code>ProblemsLabelChangedEvent</code>s are only generated by <code> * ProblemsLabelDecorator</code>s. * </p> */ public static class ProblemsLabelChangedEvent extends LabelProviderChangedEvent { private boolean fMarkerChange; /** * Note: This constructor is for internal use only. Clients should not call this constructor. */ public ProblemsLabelChangedEvent(IBaseLabelProvider source, IResource[] changedResource, boolean isMarkerChange) { super(source, changedResource); fMarkerChange= isMarkerChange; } /** * Returns whether this event origins from marker changes. If <code>false</code> an annotation * model change is the origin. In this case viewers not displaying working copies can ignore these * events. * * @return if this event origins from a marker change. */ public boolean isMarkerChange() { return fMarkerChange; } } private static final int ERRORTICK_WARNING= JavaElementImageDescriptor.WARNING; private static final int ERRORTICK_ERROR= JavaElementImageDescriptor.ERROR; private ImageDescriptorRegistry fRegistry; private boolean fUseNewRegistry= false; private IProblemChangedListener fProblemChangedListener; private ListenerList fListeners; /** * Creates a new <code>ProblemsLabelDecorator</code>. */ public ProblemsLabelDecorator() { this(null); fUseNewRegistry= true; } /* * Creates decorator with a shared image registry. * * @param registry The registry to use or <code>null</code> to use the Java plugin's * image registry. */ /** * Note: This constructor is for internal use only. Clients should not call this constructor. */ public ProblemsLabelDecorator(ImageDescriptorRegistry registry) { fRegistry= registry; fProblemChangedListener= null; } private ImageDescriptorRegistry getRegistry() { if (fRegistry == null) { fRegistry= fUseNewRegistry ? new ImageDescriptorRegistry() : JavaPlugin.getImageDescriptorRegistry(); } return fRegistry; } /* (non-Javadoc) * @see ILabelDecorator#decorateText(String, Object) */ public String decorateText(String text, Object element) { return text; } /* (non-Javadoc) * @see ILabelDecorator#decorateImage(Image, Object) */ public Image decorateImage(Image image, Object obj) { int adornmentFlags= computeAdornmentFlags(obj); if (adornmentFlags != 0) { ImageDescriptor baseImage= new ImageImageDescriptor(image); Rectangle bounds= image.getBounds(); return getRegistry().get(new JavaElementImageDescriptor(baseImage, adornmentFlags, new Point(bounds.width, bounds.height))); } return image; } /** * Note: This method is for internal use only. Clients should not call this method. */ protected int computeAdornmentFlags(Object obj) { try { if (obj instanceof IJavaElement) { IJavaElement element= (IJavaElement) obj; int type= element.getElementType(); switch (type) { case IJavaElement.JAVA_PROJECT: case IJavaElement.PACKAGE_FRAGMENT_ROOT: return getErrorTicksFromMarkers(element.getResource(), IResource.DEPTH_INFINITE, null); case IJavaElement.PACKAGE_FRAGMENT: case IJavaElement.CLASS_FILE: return getErrorTicksFromMarkers(element.getResource(), IResource.DEPTH_ONE, null); case IJavaElement.COMPILATION_UNIT: case IJavaElement.PACKAGE_DECLARATION: case IJavaElement.IMPORT_DECLARATION: case IJavaElement.IMPORT_CONTAINER: case IJavaElement.TYPE: case IJavaElement.INITIALIZER: case IJavaElement.METHOD: case IJavaElement.FIELD: ICompilationUnit cu= (ICompilationUnit) element.getAncestor(IJavaElement.COMPILATION_UNIT); if (cu != null) { ISourceReference ref= (type == IJavaElement.COMPILATION_UNIT) ? null : (ISourceReference) element; // The assumption is that only source elements in compilation unit can have markers if (cu.isWorkingCopy()) { // working copy: look at annotation model return getErrorTicksFromWorkingCopy((ICompilationUnit) cu.getOriginalElement(), ref); } return getErrorTicksFromMarkers(cu.getResource(), IResource.DEPTH_ONE, ref); } break; default: } } else if (obj instanceof IResource) { return getErrorTicksFromMarkers((IResource) obj, IResource.DEPTH_INFINITE, null); } } catch (CoreException e) { if (e instanceof JavaModelException) { if (((JavaModelException) e).isDoesNotExist()) { return 0; } } JavaPlugin.log(e); } return 0; } private int getErrorTicksFromMarkers(IResource res, int depth, ISourceReference sourceElement) throws CoreException { if (res == null || !res.isAccessible()) { return 0; } int info= 0; IMarker[] markers= res.findMarkers(IMarker.PROBLEM, true, depth); if (markers != null) { for (int i= 0; i < markers.length && (info != ERRORTICK_ERROR); i++) { IMarker curr= markers[i]; if (sourceElement == null || isMarkerInRange(curr, sourceElement)) { int priority= curr.getAttribute(IMarker.SEVERITY, -1); if (priority == IMarker.SEVERITY_WARNING) { info= ERRORTICK_WARNING; } else if (priority == IMarker.SEVERITY_ERROR) { info= ERRORTICK_ERROR; } } } } return info; } private boolean isMarkerInRange(IMarker marker, ISourceReference sourceElement) throws CoreException { if (marker.isSubtypeOf(IMarker.TEXT)) { int pos= marker.getAttribute(IMarker.CHAR_START, -1); return isInside(pos, sourceElement); } return false; } private int getErrorTicksFromWorkingCopy(ICompilationUnit original, ISourceReference sourceElement) throws CoreException { int info= 0; FileEditorInput editorInput= new FileEditorInput((IFile) original.getResource()); IAnnotationModel model= JavaPlugin.getDefault().getCompilationUnitDocumentProvider().getAnnotationModel(editorInput); if (model != null) { Iterator iter= model.getAnnotationIterator(); while ((info != ERRORTICK_ERROR) && iter.hasNext()) { Annotation curr= (Annotation) iter.next(); IMarker marker= isAnnotationInRange(model, curr, sourceElement); if (marker != null) { int priority= marker.getAttribute(IMarker.SEVERITY, -1); if (priority == IMarker.SEVERITY_WARNING) { info= ERRORTICK_WARNING; } else if (priority == IMarker.SEVERITY_ERROR) { info= ERRORTICK_ERROR; } } } } return info; } private IMarker isAnnotationInRange(IAnnotationModel model, Annotation annot, ISourceReference sourceElement) throws CoreException { if (annot instanceof MarkerAnnotation) { IMarker marker= ((MarkerAnnotation) annot).getMarker(); if (marker.exists() && marker.isSubtypeOf(IMarker.PROBLEM)) { Position pos= model.getPosition(annot); if (sourceElement == null || isInside(pos.getOffset(), sourceElement)) { return marker; } } } return null; } /** * Tests if a position is inside the source range of an element. * @param pos Position to be tested. * @param sourceElement Source element (must be a IJavaElement) * @return boolean Return <code>true</code> if position is located inside the source element. * @throws CoreException Exception thrown if element range could not be accessed. * * @since 2.1 */ protected boolean isInside(int pos, ISourceReference sourceElement) throws CoreException { ISourceRange range= sourceElement.getSourceRange(); if (range != null) { int rangeOffset= range.getOffset(); return (rangeOffset <= pos && rangeOffset + range.getLength() > pos); } return false; } /* (non-Javadoc) * @see IBaseLabelProvider#dispose() */ public void dispose() { if (fProblemChangedListener != null) { JavaPlugin.getDefault().getProblemMarkerManager().removeListener(fProblemChangedListener); fProblemChangedListener= null; } if (fRegistry != null && fUseNewRegistry) { fRegistry.dispose(); } } /* (non-Javadoc) * @see IBaseLabelProvider#isLabelProperty(Object, String) */ public boolean isLabelProperty(Object element, String property) { return true; } /* (non-Javadoc) * @see IBaseLabelProvider#addListener(ILabelProviderListener) */ public void addListener(ILabelProviderListener listener) { if (fListeners == null) { fListeners= new ListenerList(); } fListeners.add(listener); if (fProblemChangedListener == null) { fProblemChangedListener= new IProblemChangedListener() { public void problemsChanged(IResource[] changedResources, boolean isMarkerChange) { fireProblemsChanged(changedResources, isMarkerChange); } }; JavaPlugin.getDefault().getProblemMarkerManager().addListener(fProblemChangedListener); } } /* (non-Javadoc) * @see IBaseLabelProvider#removeListener(ILabelProviderListener) */ public void removeListener(ILabelProviderListener listener) { if (fListeners != null) { fListeners.remove(listener); if (fListeners.isEmpty() && fProblemChangedListener != null) { JavaPlugin.getDefault().getProblemMarkerManager().removeListener(fProblemChangedListener); fProblemChangedListener= null; } } } private void fireProblemsChanged(IResource[] changedResources, boolean isMarkerChange) { if (fListeners != null && !fListeners.isEmpty()) { LabelProviderChangedEvent event= new ProblemsLabelChangedEvent(this, changedResources, isMarkerChange); Object[] listeners= fListeners.getListeners(); for (int i= 0; i < listeners.length; i++) { ((ILabelProviderListener) listeners[i]).labelProviderChanged(event); } } } /* (non-Javadoc) * @see org.eclipse.jface.viewers.ILightweightLabelDecorator#decorate(java.lang.Object, org.eclipse.jface.viewers.IDecoration) */ public void decorate(Object element, IDecoration decoration) { int adornmentFlags= computeAdornmentFlags(element); if (adornmentFlags == ERRORTICK_ERROR) { decoration.addOverlay(JavaPluginImages.DESC_OVR_ERROR); } else if (adornmentFlags == ERRORTICK_WARNING) { decoration.addOverlay(JavaPluginImages.DESC_OVR_WARNING); } } }
43,557
Bug 43557 Refactoring Extract method: Renaming of parameters doesn't work properly [refactoring]
To see the problem, take a look at the following example: public void test1() { String x = "x"; String y = "a" + x; System.out.println(x); } Select the last 2 code lines of the method and apply the refactoring extract method. In the dialog, give it a method name and rename parameter x to message. You'll get this: public void test1() { String x = "x"; extractedMethod(x); } private void extractedMethod(String message) { String y = "a" + x; System.out.println(x); } As you can see, x in the extracted method isn't renamed to message.
resolved fixed
0819508
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-02T10:03:16Z
2003-09-24T10:40:00Z
org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/parameterName_in/A_test905.java
43,557
Bug 43557 Refactoring Extract method: Renaming of parameters doesn't work properly [refactoring]
To see the problem, take a look at the following example: public void test1() { String x = "x"; String y = "a" + x; System.out.println(x); } Select the last 2 code lines of the method and apply the refactoring extract method. In the dialog, give it a method name and rename parameter x to message. You'll get this: public void test1() { String x = "x"; extractedMethod(x); } private void extractedMethod(String message) { String y = "a" + x; System.out.println(x); } As you can see, x in the extracted method isn't renamed to message.
resolved fixed
0819508
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-02T10:03:16Z
2003-09-24T10:40:00Z
org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/parameterName_out/A_test905.java
43,557
Bug 43557 Refactoring Extract method: Renaming of parameters doesn't work properly [refactoring]
To see the problem, take a look at the following example: public void test1() { String x = "x"; String y = "a" + x; System.out.println(x); } Select the last 2 code lines of the method and apply the refactoring extract method. In the dialog, give it a method name and rename parameter x to message. You'll get this: public void test1() { String x = "x"; extractedMethod(x); } private void extractedMethod(String message) { String y = "a" + x; System.out.println(x); } As you can see, x in the extracted method isn't renamed to message.
resolved fixed
0819508
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-02T10:03:16Z
2003-09-24T10:40:00Z
org.eclipse.jdt.ui.tests.refactoring/test
43,557
Bug 43557 Refactoring Extract method: Renaming of parameters doesn't work properly [refactoring]
To see the problem, take a look at the following example: public void test1() { String x = "x"; String y = "a" + x; System.out.println(x); } Select the last 2 code lines of the method and apply the refactoring extract method. In the dialog, give it a method name and rename parameter x to message. You'll get this: public void test1() { String x = "x"; extractedMethod(x); } private void extractedMethod(String message) { String y = "a" + x; System.out.println(x); } As you can see, x in the extracted method isn't renamed to message.
resolved fixed
0819508
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-02T10:03:16Z
2003-09-24T10:40:00Z
cases/org/eclipse/jdt/ui/tests/refactoring/ExtractMethodTests.java
43,557
Bug 43557 Refactoring Extract method: Renaming of parameters doesn't work properly [refactoring]
To see the problem, take a look at the following example: public void test1() { String x = "x"; String y = "a" + x; System.out.println(x); } Select the last 2 code lines of the method and apply the refactoring extract method. In the dialog, give it a method name and rename parameter x to message. You'll get this: public void test1() { String x = "x"; extractedMethod(x); } private void extractedMethod(String message) { String y = "a" + x; System.out.println(x); } As you can see, x in the extracted method isn't renamed to message.
resolved fixed
0819508
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-02T10:03:16Z
2003-09-24T10:40:00Z
org.eclipse.jdt.ui/core
43,557
Bug 43557 Refactoring Extract method: Renaming of parameters doesn't work properly [refactoring]
To see the problem, take a look at the following example: public void test1() { String x = "x"; String y = "a" + x; System.out.println(x); } Select the last 2 code lines of the method and apply the refactoring extract method. In the dialog, give it a method name and rename parameter x to message. You'll get this: public void test1() { String x = "x"; extractedMethod(x); } private void extractedMethod(String message) { String y = "a" + x; System.out.println(x); } As you can see, x in the extracted method isn't renamed to message.
resolved fixed
0819508
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-02T10:03:16Z
2003-09-24T10:40:00Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/ExtractMethodRefactoring.java
43,653
Bug 43653 Error while deleting resources
An error dialog is displayed while deleting resources, and a few exceptions are printed to the log. I haven't tested how reproducible this problem is. The machine is Eclipse-GTK-I20030925, GNOME, RedHat 9. STEPS: 1.) Make a workspace containing CVS projects for the platform-ui module, and binary projects with linked content for the remaining Eclipse projects. (this project is from a previous I-build) 2.) Select all the binary projects, from the top to the bottom. 3.) Press the "Delete" key. OBSERVED RESULTS: Deletion starts to occur, but stops at some point with an error dialog. Closing the dialog and pressing delete again completes the deletion.
resolved fixed
70ee165
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-02T11:13:23Z
2003-09-25T14:26:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/OrganizeImportsAction.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.Arrays; import java.util.Collection; import java.util.HashSet; import org.eclipse.core.resources.IWorkspaceRunnable; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.MultiStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IStatusLineManager; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.window.Window; import org.eclipse.ui.IEditorActionBarContributor; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IObjectActionDelegate; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchSite; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.part.EditorActionBarContributor; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.compiler.IProblem; import org.eclipse.jdt.ui.IWorkingCopyManager; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.internal.corext.ValidateEditException; import org.eclipse.jdt.internal.corext.codemanipulation.OrganizeImportsOperation; import org.eclipse.jdt.internal.corext.codemanipulation.OrganizeImportsOperation.IChooseImportQuery; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.corext.util.TypeInfo; 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.WorkbenchRunnableAdapter; import org.eclipse.jdt.internal.ui.browsing.LogicalPackage; import org.eclipse.jdt.internal.ui.dialogs.MultiElementListSelectionDialog; import org.eclipse.jdt.internal.ui.dialogs.ProblemDialog; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor; 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.util.TypeInfoLabelProvider; /** * Organizes the imports of a compilation unit. * <p> * The action is applicable to selections containing elements of * type <code>ICompilationUnit</code> or <code>IPackage * </code>. * * <p> * This class may be instantiated; it is not intended to be subclassed. * </p> * * @since 2.0 */ public class OrganizeImportsAction extends SelectionDispatchAction { private JavaEditor fEditor; /* (non-Javadoc) * Class implements IObjectActionDelegate */ public static class ObjectDelegate implements IObjectActionDelegate { private OrganizeImportsAction fAction; public void setActivePart(IAction action, IWorkbenchPart targetPart) { fAction= new OrganizeImportsAction(targetPart.getSite()); } public void run(IAction action) { fAction.run(); } public void selectionChanged(IAction action, ISelection selection) { if (fAction == null) action.setEnabled(false); } } /** * Creates a new <code>OrganizeImportsAction</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 OrganizeImportsAction(IWorkbenchSite site) { super(site); setText(ActionMessages.getString("OrganizeImportsAction.label")); //$NON-NLS-1$ setToolTipText(ActionMessages.getString("OrganizeImportsAction.tooltip")); //$NON-NLS-1$ setDescription(ActionMessages.getString("OrganizeImportsAction.description")); //$NON-NLS-1$ WorkbenchHelp.setHelp(this, IJavaHelpContextIds.ORGANIZE_IMPORTS_ACTION); } /** * Note: This constructor is for internal use only. Clients should not call this constructor. */ public OrganizeImportsAction(JavaEditor editor) { this(editor.getEditorSite()); fEditor= editor; setEnabled(getCompilationUnit(fEditor) != null); } /* (non-Javadoc) * Method declared on SelectionDispatchAction. */ public void selectionChanged(ITextSelection selection) { // do nothing } /* (non-Javadoc) * Method declared on SelectionDispatchAction. */ public void selectionChanged(IStructuredSelection selection) { setEnabled(isEnabled(selection)); } private ICompilationUnit[] getCompilationUnits(IStructuredSelection selection) { HashSet result= new HashSet(); Object[] selected= selection.toArray(); for (int i= 0; i < selected.length; i++) { try { if (selected[i] instanceof IJavaElement) { IJavaElement elem= (IJavaElement) selected[i]; switch (elem.getElementType()) { case IJavaElement.TYPE: if (elem.getParent().getElementType() == IJavaElement.COMPILATION_UNIT) { result.add(elem.getParent()); } break; case IJavaElement.COMPILATION_UNIT: result.add(elem); break; case IJavaElement.IMPORT_CONTAINER: result.add(elem.getParent()); break; case IJavaElement.PACKAGE_FRAGMENT: collectCompilationUnits((IPackageFragment) elem, result); break; case IJavaElement.PACKAGE_FRAGMENT_ROOT: collectCompilationUnits((IPackageFragmentRoot) elem, result); break; case IJavaElement.JAVA_PROJECT: IPackageFragmentRoot[] roots= ((IJavaProject) elem).getPackageFragmentRoots(); for (int k= 0; k < roots.length; k++) { collectCompilationUnits(roots[k], result); } break; } } else if (selected[i] instanceof LogicalPackage) { IPackageFragment[] packageFragments= ((LogicalPackage)selected[i]).getFragments(); for (int k= 0; k < packageFragments.length; k++) collectCompilationUnits(packageFragments[k], result); } } catch (JavaModelException e) { JavaPlugin.log(e); } } return (ICompilationUnit[]) result.toArray(new ICompilationUnit[result.size()]); } private void collectCompilationUnits(IPackageFragment pack, Collection result) throws JavaModelException { result.addAll(Arrays.asList(pack.getCompilationUnits())); } private void collectCompilationUnits(IPackageFragmentRoot root, Collection result) throws JavaModelException { if (root.getKind() == IPackageFragmentRoot.K_SOURCE) { IJavaElement[] children= root.getChildren(); for (int i= 0; i < children.length; i++) { collectCompilationUnits((IPackageFragment) children[i], result); } } } private boolean isEnabled(IStructuredSelection selection) { Object[] selected= selection.toArray(); for (int i= 0; i < selected.length; i++) { try { if (selected[i] instanceof IJavaElement) { IJavaElement elem= (IJavaElement) selected[i]; switch (elem.getElementType()) { case IJavaElement.TYPE: return elem.getParent().getElementType() == IJavaElement.COMPILATION_UNIT; // for browsing perspective case IJavaElement.COMPILATION_UNIT: return true; case IJavaElement.IMPORT_CONTAINER: return true; case IJavaElement.PACKAGE_FRAGMENT: case IJavaElement.PACKAGE_FRAGMENT_ROOT: IPackageFragmentRoot root= (IPackageFragmentRoot) elem.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); return (root.getKind() == IPackageFragmentRoot.K_SOURCE); case IJavaElement.JAVA_PROJECT: return hasSourceFolders((IJavaProject) elem); } } } catch (JavaModelException e) { JavaPlugin.log(e); } } return false; } private boolean hasSourceFolders(IJavaProject project) throws JavaModelException { IPackageFragmentRoot[] roots= project.getPackageFragmentRoots(); for (int i= 0; i < roots.length; i++) { IPackageFragmentRoot root= roots[i]; if (root.getKind() == IPackageFragmentRoot.K_SOURCE) { return true; } } return false; } /* (non-Javadoc) * Method declared on SelectionDispatchAction. */ public void run(ITextSelection selection) { run(getCompilationUnit(fEditor)); } private static ICompilationUnit getCompilationUnit(JavaEditor editor) { IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager(); ICompilationUnit cu= manager.getWorkingCopy(editor.getEditorInput()); return cu; } /* (non-Javadoc) * Method declared on SelectionDispatchAction. */ public void run(IStructuredSelection selection) { ICompilationUnit[] cus= getCompilationUnits(selection); if (cus.length == 1) { run(cus[0]); } else { runOnMultiple(cus); } } /** * Peform organize import on multiple compilation units. No editors are opened. */ public void runOnMultiple(final ICompilationUnit[] cus) { try { String message= ActionMessages.getString("OrganizeImportsAction.multi.status.description"); //$NON-NLS-1$ final MultiStatus status= new MultiStatus(JavaUI.ID_PLUGIN, IStatus.OK, message, null); ProgressMonitorDialog dialog= new ProgressMonitorDialog(getShell()); dialog.run(true, true, new WorkbenchRunnableAdapter(new IWorkspaceRunnable() { public void run(IProgressMonitor monitor) { doRunOnMultiple(cus, status, monitor); } })); if (!status.isOK()) { String title= ActionMessages.getString("OrganizeImportsAction.multi.status.title"); //$NON-NLS-1$ ProblemDialog.open(getShell(), title, null, status); } } catch (InvocationTargetException e) { ExceptionHandler.handle(e, getShell(), ActionMessages.getString("OrganizeImportsAction.error.title"), ActionMessages.getString("OrganizeImportsAction.error.message")); //$NON-NLS-1$ //$NON-NLS-2$ } catch (InterruptedException e) { // cancelled by user } } static final class OrganizeImportError extends Error { } private void doRunOnMultiple(ICompilationUnit[] cus, MultiStatus status, IProgressMonitor monitor) throws OperationCanceledException { if (monitor == null) { monitor= new NullProgressMonitor(); } monitor.setTaskName(ActionMessages.getString("OrganizeImportsAction.multi.op.description")); //$NON-NLS-1$ monitor.beginTask("", cus.length); //$NON-NLS-1$ try { IPreferenceStore store= PreferenceConstants.getPreferenceStore(); String[] prefOrder= JavaPreferencesSettings.getImportOrderPreference(store); int threshold= JavaPreferencesSettings.getImportNumberThreshold(store); boolean ignoreLowerCaseNames= store.getBoolean(PreferenceConstants.ORGIMPORTS_IGNORELOWERCASE); IChooseImportQuery query= new IChooseImportQuery() { public TypeInfo[] chooseImports(TypeInfo[][] openChoices, ISourceRange[] ranges) { throw new OrganizeImportError(); } }; for (int i= 0; i < cus.length; i++) { ICompilationUnit cu= cus[i]; if (testOnBuildPath(cu, status)) { String cuLocation= cu.getPath().makeRelative().toString(); cu= JavaModelUtil.toWorkingCopy(cu); monitor.subTask(cuLocation); try { OrganizeImportsOperation op= new OrganizeImportsOperation(cu, prefOrder, threshold, ignoreLowerCaseNames, !cu.isWorkingCopy(), true, query); runInSync(op, cuLocation, status, monitor); IProblem parseError= op.getParseError(); if (parseError != null) { String message= ActionMessages.getFormattedString("OrganizeImportsAction.multi.error.parse", cuLocation); //$NON-NLS-1$ status.add(new Status(IStatus.INFO, JavaUI.ID_PLUGIN, IStatus.ERROR, message, null)); } } catch (CoreException e) { JavaPlugin.log(e); String message= ActionMessages.getFormattedString("OrganizeImportsAction.multi.error.unexpected", e.getStatus().getMessage()); //$NON-NLS-1$ status.add(new Status(IStatus.ERROR, JavaUI.ID_PLUGIN, IStatus.ERROR, message, null)); } if (monitor.isCanceled()) { throw new OperationCanceledException(); } } } } finally { monitor.done(); } } private boolean testOnBuildPath(ICompilationUnit cu, MultiStatus status) { IJavaProject project= cu.getJavaProject(); if (!project.isOnClasspath(cu)) { String cuLocation= cu.getPath().makeRelative().toString(); String message= ActionMessages.getFormattedString("OrganizeImportsAction.multi.error.notoncp", cuLocation); //$NON-NLS-1$ status.add(new Status(IStatus.INFO, JavaUI.ID_PLUGIN, IStatus.ERROR, message, null)); return false; } return true; } private void runInSync(final OrganizeImportsOperation op, final String cuLocation, final MultiStatus status, final IProgressMonitor monitor) { Runnable runnable= new Runnable() { public void run() { try { op.run(new SubProgressMonitor(monitor, 1)); } catch (ValidateEditException e) { status.add(e.getStatus()); } catch (CoreException e) { JavaPlugin.log(e); String message= ActionMessages.getFormattedString("OrganizeImportsAction.multi.error.unexpected", e.getStatus().getMessage()); //$NON-NLS-1$ status.add(new Status(IStatus.ERROR, JavaUI.ID_PLUGIN, IStatus.ERROR, message, null)); } catch (OrganizeImportError e) { String message= ActionMessages.getFormattedString("OrganizeImportsAction.multi.error.unresolvable", cuLocation); //$NON-NLS-1$ status.add(new Status(IStatus.INFO, JavaUI.ID_PLUGIN, IStatus.ERROR, message, null)); } } }; getShell().getDisplay().syncExec(runnable); } /** * Note: This method is for internal use only. Clients should not call this method. */ public void run(ICompilationUnit cu) { if (!ElementValidator.check(cu, getShell(), ActionMessages.getString("OrganizeImportsAction.error.title"), fEditor != null)) //$NON-NLS-1$ return; if (!ActionUtil.isProcessable(getShell(), cu)) return; try { IPreferenceStore store= PreferenceConstants.getPreferenceStore(); String[] prefOrder= JavaPreferencesSettings.getImportOrderPreference(store); int threshold= JavaPreferencesSettings.getImportNumberThreshold(store); boolean ignoreLowerCaseNames= store.getBoolean(PreferenceConstants.ORGIMPORTS_IGNORELOWERCASE); if (!cu.isWorkingCopy()) { IEditorPart editor= EditorUtility.openInEditor(cu); if (editor instanceof JavaEditor) { fEditor= (JavaEditor) editor; } cu= JavaModelUtil.toWorkingCopy(cu); } OrganizeImportsOperation op= new OrganizeImportsOperation(cu, prefOrder, threshold, ignoreLowerCaseNames, !cu.isWorkingCopy(), true, createChooseImportQuery()); BusyIndicatorRunnableContext context= new BusyIndicatorRunnableContext(); context.run(false, true, new WorkbenchRunnableAdapter(op)); IProblem parseError= op.getParseError(); if (parseError != null) { String message= ActionMessages.getFormattedString("OrganizeImportsAction.single.error.parse", parseError.getMessage()); //$NON-NLS-1$ MessageDialog.openInformation(getShell(), ActionMessages.getString("OrganizeImportsAction.error.title"), message); //$NON-NLS-1$ if (fEditor != null && parseError.getSourceStart() != -1) { fEditor.selectAndReveal(parseError.getSourceStart(), parseError.getSourceEnd() - parseError.getSourceStart() + 1); } } else { if (fEditor != null) { setStatusBarMessage(getOrganizeInfo(op)); } } } catch (CoreException e) { ExceptionHandler.handle(e, getShell(), ActionMessages.getString("OrganizeImportsAction.error.title"), ActionMessages.getString("OrganizeImportsAction.error.message")); //$NON-NLS-1$ //$NON-NLS-2$ } catch (InvocationTargetException e) { ExceptionHandler.handle(e, getShell(), ActionMessages.getString("OrganizeImportsAction.error.title"), ActionMessages.getString("OrganizeImportsAction.error.message")); //$NON-NLS-1$ //$NON-NLS-2$ } catch (InterruptedException e) { } } private String getOrganizeInfo(OrganizeImportsOperation op) { int nImportsAdded= op.getNumberOfImportsAdded(); if (nImportsAdded >= 0) { return ActionMessages.getFormattedString("OrganizeImportsAction.summary_added", String.valueOf(nImportsAdded)); //$NON-NLS-1$ } else { return ActionMessages.getFormattedString("OrganizeImportsAction.summary_removed", String.valueOf(-nImportsAdded)); //$NON-NLS-1$ } } private IChooseImportQuery createChooseImportQuery() { return new IChooseImportQuery() { public TypeInfo[] chooseImports(TypeInfo[][] openChoices, ISourceRange[] ranges) { return doChooseImports(openChoices, ranges); } }; } private TypeInfo[] doChooseImports(TypeInfo[][] openChoices, final ISourceRange[] ranges) { // remember selection ISelection sel= fEditor != null ? fEditor.getSelectionProvider().getSelection() : null; TypeInfo[] result= null; ILabelProvider labelProvider= new TypeInfoLabelProvider(TypeInfoLabelProvider.SHOW_FULLYQUALIFIED); MultiElementListSelectionDialog dialog= new MultiElementListSelectionDialog(getShell(), labelProvider) { protected void handleSelectionChanged() { super.handleSelectionChanged(); // show choices in editor doListSelectionChanged(getCurrentPage(), ranges); } }; dialog.setTitle(ActionMessages.getString("OrganizeImportsAction.selectiondialog.title")); //$NON-NLS-1$ dialog.setMessage(ActionMessages.getString("OrganizeImportsAction.selectiondialog.message")); //$NON-NLS-1$ dialog.setElements(openChoices); if (dialog.open() == Window.OK) { Object[] res= dialog.getResult(); result= new TypeInfo[res.length]; for (int i= 0; i < res.length; i++) { Object[] array= (Object[]) res[i]; if (array.length > 0) result[i]= (TypeInfo) array[0]; } } // restore selection if (sel instanceof ITextSelection) { ITextSelection textSelection= (ITextSelection) sel; fEditor.selectAndReveal(textSelection.getOffset(), textSelection.getLength()); } return result; } private void doListSelectionChanged(int page, ISourceRange[] ranges) { if (page >= 0 && page < ranges.length) { ISourceRange range= ranges[page]; fEditor.selectAndReveal(range.getOffset(), range.getLength()); } } private void setStatusBarMessage(String message) { IEditorActionBarContributor contributor= fEditor.getEditorSite().getActionBarContributor(); if (contributor instanceof EditorActionBarContributor) { IStatusLineManager manager= ((EditorActionBarContributor) contributor).getActionBars().getStatusLineManager(); manager.setMessage(message); } } }
43,487
Bug 43487 Exception on 'Preview' of inline method [refactoring]
20030923 smoke 1. Laod the Junit sources in a project 2. Select SuiteTest.testInheritedTests and do a 'Inline...' Nothing happens, Exception in the log java.lang.NullPointerException at org.eclipse.jdt.internal.ui.refactoring.ChangeElementContentProvider.getChangeElement(ChangeElementContentProvider.java:165) at org.eclipse.jdt.internal.ui.refactoring.ChangeElementContentProvider.getChangeElement(ChangeElementContentProvider.java:171) at org.eclipse.jdt.internal.ui.refactoring.ChangeElementContentProvider.getChangeElement(ChangeElementContentProvider.java:171) at org.eclipse.jdt.internal.ui.refactoring.ChangeElementContentProvider.getChangeElement(ChangeElementContentProvider.java:171) at org.eclipse.jdt.internal.ui.refactoring.ChangeElementContentProvider.getChangeElement(ChangeElementContentProvider.java:171) at org.eclipse.jdt.internal.ui.refactoring.ChangeElementContentProvider.createChildren(ChangeElementContentProvider.java:135) at org.eclipse.jdt.internal.ui.refactoring.ChangeElementContentProvider.getChildren(ChangeElementContentProvider.java:76) at org.eclipse.jdt.internal.ui.refactoring.ChangeElementContentProvider.hasChildren(ChangeElementContentProvider.java:92) at org.eclipse.jface.viewers.AbstractTreeViewer.isExpandable(AbstractTreeViewer.java:1081) at org.eclipse.jface.viewers.AbstractTreeViewer.updatePlus(AbstractTreeViewer.java:1497) at org.eclipse.jface.viewers.AbstractTreeViewer.createTreeItem(AbstractTreeViewer.java:339) at org.eclipse.jface.viewers.AbstractTreeViewer$1.run(AbstractTreeViewer.java:321) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:84) at org.eclipse.jface.viewers.AbstractTreeViewer.createChildren(AbstractTreeViewer.java:307) at org.eclipse.jface.viewers.AbstractTreeViewer$5.run(AbstractTreeViewer.java:753) at org.eclipse.jface.viewers.StructuredViewer.preservingSelection(StructuredViewer.java:796) at org.eclipse.jface.viewers.CheckboxTreeViewer.preservingSelection(CheckboxTreeViewer.java:341) at org.eclipse.jface.viewers.AbstractTreeViewer.inputChanged(AbstractTreeViewer.java:744) at org.eclipse.jdt.internal.ui.refactoring.ChangeElementTreeViewer.inputChanged(ChangeElementTreeViewer.java:50) at org.eclipse.jface.viewers.ContentViewer.setInput(ContentViewer.java:238) at org.eclipse.jface.viewers.StructuredViewer.setInput(StructuredViewer.java:983) at org.eclipse.jdt.internal.ui.refactoring.PreviewWizardPage.setTreeViewerInput(PreviewWizardPage.java:308) at org.eclipse.jdt.internal.ui.refactoring.PreviewWizardPage.createStandardPreviewPage(PreviewWizardPage.java:233) at org.eclipse.jdt.internal.ui.refactoring.PreviewWizardPage.createControl(PreviewWizardPage.java:205) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.previewPressed(RefactoringWizardDialog2.java:431) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.access$3(RefactoringWizardDialog2.java:416) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2$1.widgetSelected(RefactoringWizardDialog2.java:547) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:89) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2187) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1877) at org.eclipse.jface.window.Window.runEventLoop(Window.java:583) at org.eclipse.jface.window.Window.open(Window.java:563) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate(RefactoringStarter.java:56) at org.eclipse.jdt.internal.ui.refactoring.actions.InlineMethodAction.activate(InlineMethodAction.java:128) at org.eclipse.jdt.internal.ui.refactoring.actions.InlineMethodAction.run(InlineMethodAction.java:121) at org.eclipse.jdt.internal.ui.refactoring.actions.InlineMethodAction.run(InlineMethodAction.java:82) at org.eclipse.jdt.ui.actions.InlineAction.tryInlineMethod(InlineAction.java:132) at org.eclipse.jdt.ui.actions.InlineAction.run(InlineAction.java:109) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun(SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run(SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:529) at org.eclipse.jface.action.ActionContributionItem.access$4(ActionContributionItem.java:482) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent(ActionContributionItem.java:454) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2187) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1877) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2037) at org.eclipse.ui.internal.Workbench.run(Workbench.java:2020) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:295) at org.eclipse.core.launcher.Main.run(Main.java:751) at org.eclipse.core.launcher.Main.main(Main.java:587)
resolved fixed
182766f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-02T16:50:31Z
2003-09-23T09:40:00Z
org.eclipse.jdt.ui/ui
43,487
Bug 43487 Exception on 'Preview' of inline method [refactoring]
20030923 smoke 1. Laod the Junit sources in a project 2. Select SuiteTest.testInheritedTests and do a 'Inline...' Nothing happens, Exception in the log java.lang.NullPointerException at org.eclipse.jdt.internal.ui.refactoring.ChangeElementContentProvider.getChangeElement(ChangeElementContentProvider.java:165) at org.eclipse.jdt.internal.ui.refactoring.ChangeElementContentProvider.getChangeElement(ChangeElementContentProvider.java:171) at org.eclipse.jdt.internal.ui.refactoring.ChangeElementContentProvider.getChangeElement(ChangeElementContentProvider.java:171) at org.eclipse.jdt.internal.ui.refactoring.ChangeElementContentProvider.getChangeElement(ChangeElementContentProvider.java:171) at org.eclipse.jdt.internal.ui.refactoring.ChangeElementContentProvider.getChangeElement(ChangeElementContentProvider.java:171) at org.eclipse.jdt.internal.ui.refactoring.ChangeElementContentProvider.createChildren(ChangeElementContentProvider.java:135) at org.eclipse.jdt.internal.ui.refactoring.ChangeElementContentProvider.getChildren(ChangeElementContentProvider.java:76) at org.eclipse.jdt.internal.ui.refactoring.ChangeElementContentProvider.hasChildren(ChangeElementContentProvider.java:92) at org.eclipse.jface.viewers.AbstractTreeViewer.isExpandable(AbstractTreeViewer.java:1081) at org.eclipse.jface.viewers.AbstractTreeViewer.updatePlus(AbstractTreeViewer.java:1497) at org.eclipse.jface.viewers.AbstractTreeViewer.createTreeItem(AbstractTreeViewer.java:339) at org.eclipse.jface.viewers.AbstractTreeViewer$1.run(AbstractTreeViewer.java:321) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:84) at org.eclipse.jface.viewers.AbstractTreeViewer.createChildren(AbstractTreeViewer.java:307) at org.eclipse.jface.viewers.AbstractTreeViewer$5.run(AbstractTreeViewer.java:753) at org.eclipse.jface.viewers.StructuredViewer.preservingSelection(StructuredViewer.java:796) at org.eclipse.jface.viewers.CheckboxTreeViewer.preservingSelection(CheckboxTreeViewer.java:341) at org.eclipse.jface.viewers.AbstractTreeViewer.inputChanged(AbstractTreeViewer.java:744) at org.eclipse.jdt.internal.ui.refactoring.ChangeElementTreeViewer.inputChanged(ChangeElementTreeViewer.java:50) at org.eclipse.jface.viewers.ContentViewer.setInput(ContentViewer.java:238) at org.eclipse.jface.viewers.StructuredViewer.setInput(StructuredViewer.java:983) at org.eclipse.jdt.internal.ui.refactoring.PreviewWizardPage.setTreeViewerInput(PreviewWizardPage.java:308) at org.eclipse.jdt.internal.ui.refactoring.PreviewWizardPage.createStandardPreviewPage(PreviewWizardPage.java:233) at org.eclipse.jdt.internal.ui.refactoring.PreviewWizardPage.createControl(PreviewWizardPage.java:205) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.previewPressed(RefactoringWizardDialog2.java:431) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.access$3(RefactoringWizardDialog2.java:416) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2$1.widgetSelected(RefactoringWizardDialog2.java:547) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:89) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2187) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1877) at org.eclipse.jface.window.Window.runEventLoop(Window.java:583) at org.eclipse.jface.window.Window.open(Window.java:563) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate(RefactoringStarter.java:56) at org.eclipse.jdt.internal.ui.refactoring.actions.InlineMethodAction.activate(InlineMethodAction.java:128) at org.eclipse.jdt.internal.ui.refactoring.actions.InlineMethodAction.run(InlineMethodAction.java:121) at org.eclipse.jdt.internal.ui.refactoring.actions.InlineMethodAction.run(InlineMethodAction.java:82) at org.eclipse.jdt.ui.actions.InlineAction.tryInlineMethod(InlineAction.java:132) at org.eclipse.jdt.ui.actions.InlineAction.run(InlineAction.java:109) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun(SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run(SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:529) at org.eclipse.jface.action.ActionContributionItem.access$4(ActionContributionItem.java:482) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent(ActionContributionItem.java:454) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2187) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1877) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2037) at org.eclipse.ui.internal.Workbench.run(Workbench.java:2020) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:295) at org.eclipse.core.launcher.Main.run(Main.java:751) at org.eclipse.core.launcher.Main.main(Main.java:587)
resolved fixed
182766f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-02T16:50:31Z
2003-09-23T09:40:00Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/ChangeElementContentProvider.java
42,585
Bug 42585 [Refactoring] "self encapsulate field" loses finalness of field
Do "self encapsulate field" on a final field it correctly recognises that a setter is not appropriate but the field loses it's final marker. e.g. public final Object field; -> private Object field;
resolved fixed
0efc6d9
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-02T17:50:08Z
2003-09-05T08:20:00Z
org.eclipse.jdt.ui.tests.refactoring/resources/SefWorkSpace/SefTests/base_in/TestFinal.java
42,585
Bug 42585 [Refactoring] "self encapsulate field" loses finalness of field
Do "self encapsulate field" on a final field it correctly recognises that a setter is not appropriate but the field loses it's final marker. e.g. public final Object field; -> private Object field;
resolved fixed
0efc6d9
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-02T17:50:08Z
2003-09-05T08:20:00Z
org.eclipse.jdt.ui.tests.refactoring/resources/SefWorkSpace/SefTests/base_out/TestFinal.java
42,585
Bug 42585 [Refactoring] "self encapsulate field" loses finalness of field
Do "self encapsulate field" on a final field it correctly recognises that a setter is not appropriate but the field loses it's final marker. e.g. public final Object field; -> private Object field;
resolved fixed
0efc6d9
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-02T17:50:08Z
2003-09-05T08:20:00Z
org.eclipse.jdt.ui.tests.refactoring/test
42,585
Bug 42585 [Refactoring] "self encapsulate field" loses finalness of field
Do "self encapsulate field" on a final field it correctly recognises that a setter is not appropriate but the field loses it's final marker. e.g. public final Object field; -> private Object field;
resolved fixed
0efc6d9
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-02T17:50:08Z
2003-09-05T08:20:00Z
cases/org/eclipse/jdt/ui/tests/refactoring/SefTests.java
42,585
Bug 42585 [Refactoring] "self encapsulate field" loses finalness of field
Do "self encapsulate field" on a final field it correctly recognises that a setter is not appropriate but the field loses it's final marker. e.g. public final Object field; -> private Object field;
resolved fixed
0efc6d9
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-02T17:50:08Z
2003-09-05T08:20:00Z
org.eclipse.jdt.ui/core
42,585
Bug 42585 [Refactoring] "self encapsulate field" loses finalness of field
Do "self encapsulate field" on a final field it correctly recognises that a setter is not appropriate but the field loses it's final marker. e.g. public final Object field; -> private Object field;
resolved fixed
0efc6d9
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-02T17:50:08Z
2003-09-05T08:20:00Z
extension/org/eclipse/jdt/internal/corext/dom/ASTNodes.java
42,585
Bug 42585 [Refactoring] "self encapsulate field" loses finalness of field
Do "self encapsulate field" on a final field it correctly recognises that a setter is not appropriate but the field loses it's final marker. e.g. public final Object field; -> private Object field;
resolved fixed
0efc6d9
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-02T17:50:08Z
2003-09-05T08:20:00Z
org.eclipse.jdt.ui/core
42,585
Bug 42585 [Refactoring] "self encapsulate field" loses finalness of field
Do "self encapsulate field" on a final field it correctly recognises that a setter is not appropriate but the field loses it's final marker. e.g. public final Object field; -> private Object field;
resolved fixed
0efc6d9
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-02T17:50:08Z
2003-09-05T08:20:00Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/sef/SelfEncapsulateFieldRefactoring.java
41,630
Bug 41630 Cannot apply Surround with Try Catch when click error from task view. [refactoring]
null
closed fixed
ab5b758
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-03T11:01:01Z
2003-08-18T01:26:40Z
org.eclipse.jdt.ui.tests.refactoring/resources/SurroundWithWorkSpace/SurroundWithTests/trycatch_in/TestExpressionStatement.java
41,630
Bug 41630 Cannot apply Surround with Try Catch when click error from task view. [refactoring]
null
closed fixed
ab5b758
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-03T11:01:01Z
2003-08-18T01:26:40Z
org.eclipse.jdt.ui.tests.refactoring/resources/SurroundWithWorkSpace/SurroundWithTests/trycatch_out/TestExpressionStatement.java
41,630
Bug 41630 Cannot apply Surround with Try Catch when click error from task view. [refactoring]
null
closed fixed
ab5b758
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-03T11:01:01Z
2003-08-18T01:26:40Z
org.eclipse.jdt.ui.tests.refactoring/test
41,630
Bug 41630 Cannot apply Surround with Try Catch when click error from task view. [refactoring]
null
closed fixed
ab5b758
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-03T11:01:01Z
2003-08-18T01:26:40Z
cases/org/eclipse/jdt/ui/tests/refactoring/SurroundWithTests.java
41,630
Bug 41630 Cannot apply Surround with Try Catch when click error from task view. [refactoring]
null
closed fixed
ab5b758
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-03T11:01:01Z
2003-08-18T01:26:40Z
org.eclipse.jdt.ui/core
41,630
Bug 41630 Cannot apply Surround with Try Catch when click error from task view. [refactoring]
null
closed fixed
ab5b758
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-03T11:01:01Z
2003-08-18T01:26:40Z
extension/org/eclipse/jdt/internal/corext/dom/SelectionAnalyzer.java
41,630
Bug 41630 Cannot apply Surround with Try Catch when click error from task view. [refactoring]
null
closed fixed
ab5b758
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-03T11:01:01Z
2003-08-18T01:26:40Z
org.eclipse.jdt.ui/core
41,630
Bug 41630 Cannot apply Surround with Try Catch when click error from task view. [refactoring]
null
closed fixed
ab5b758
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-03T11:01:01Z
2003-08-18T01:26:40Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/ExtractMethodAnalyzer.java
41,630
Bug 41630 Cannot apply Surround with Try Catch when click error from task view. [refactoring]
null
closed fixed
ab5b758
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-03T11:01:01Z
2003-08-18T01:26:40Z
org.eclipse.jdt.ui/core
41,630
Bug 41630 Cannot apply Surround with Try Catch when click error from task view. [refactoring]
null
closed fixed
ab5b758
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-03T11:01:01Z
2003-08-18T01:26:40Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/surround/SurroundWithTryCatchAnalyzer.java
41,630
Bug 41630 Cannot apply Surround with Try Catch when click error from task view. [refactoring]
null
closed fixed
ab5b758
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-03T11:01:01Z
2003-08-18T01:26:40Z
org.eclipse.jdt.ui/core
41,630
Bug 41630 Cannot apply Surround with Try Catch when click error from task view. [refactoring]
null
closed fixed
ab5b758
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-03T11:01:01Z
2003-08-18T01:26:40Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/surround/SurroundWithTryCatchRefactoring.java
42,753
Bug 42753 Inline refactoring showed bogus error [refactoring]
The are no compiliation errors or warnings in the project. Happens in M3 and M2.
resolved fixed
4e741e4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-03T12:37:02Z
2003-09-09T06:46:40Z
org.eclipse.jdt.ui.tests.refactoring/resources/InlineMethodWorkspace/TestCases/simple_in/TestLabeledStatement.java
42,753
Bug 42753 Inline refactoring showed bogus error [refactoring]
The are no compiliation errors or warnings in the project. Happens in M3 and M2.
resolved fixed
4e741e4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-03T12:37:02Z
2003-09-09T06:46:40Z
org.eclipse.jdt.ui.tests.refactoring/resources/InlineMethodWorkspace/TestCases/simple_out/TestLabeledStatement.java
42,753
Bug 42753 Inline refactoring showed bogus error [refactoring]
The are no compiliation errors or warnings in the project. Happens in M3 and M2.
resolved fixed
4e741e4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-03T12:37:02Z
2003-09-09T06:46:40Z
org.eclipse.jdt.ui.tests.refactoring/test
42,753
Bug 42753 Inline refactoring showed bogus error [refactoring]
The are no compiliation errors or warnings in the project. Happens in M3 and M2.
resolved fixed
4e741e4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-03T12:37:02Z
2003-09-09T06:46:40Z
cases/org/eclipse/jdt/ui/tests/refactoring/InlineMethodTests.java
42,753
Bug 42753 Inline refactoring showed bogus error [refactoring]
The are no compiliation errors or warnings in the project. Happens in M3 and M2.
resolved fixed
4e741e4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-03T12:37:02Z
2003-09-09T06:46:40Z
org.eclipse.jdt.ui/core
42,753
Bug 42753 Inline refactoring showed bogus error [refactoring]
The are no compiliation errors or warnings in the project. Happens in M3 and M2.
resolved fixed
4e741e4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-03T12:37:02Z
2003-09-09T06:46:40Z
extension/org/eclipse/jdt/internal/corext/dom/ASTNodes.java
42,753
Bug 42753 Inline refactoring showed bogus error [refactoring]
The are no compiliation errors or warnings in the project. Happens in M3 and M2.
resolved fixed
4e741e4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-03T12:37:02Z
2003-09-09T06:46:40Z
org.eclipse.jdt.ui/core
42,753
Bug 42753 Inline refactoring showed bogus error [refactoring]
The are no compiliation errors or warnings in the project. Happens in M3 and M2.
resolved fixed
4e741e4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-03T12:37:02Z
2003-09-09T06:46:40Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/SourceAnalyzer.java
38,137
Bug 38137 inline call that is used in a field initializer [refactoring]
Often I have deprecated methods which just delegate to a new method. A nice way to get rid of them is to simply inline those methods. Unfortunately, it's not possible to inline a method call in a field initializer, though I don't think it should be a problem as long as - the method is consisting of only one method call, and - all arguments are declared as final
verified fixed
4d5bc5d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-03T16:14:32Z
2003-05-27T10:06:40Z
org.eclipse.jdt.ui.tests.refactoring/resources/InlineMethodWorkspace/TestCases/invalid/TestFieldInitializer.java
package invalid; public class TestFieldInitializer { private int field= /*]*/foo()/*[*/; public int foo() { return 1; } }
38,137
Bug 38137 inline call that is used in a field initializer [refactoring]
Often I have deprecated methods which just delegate to a new method. A nice way to get rid of them is to simply inline those methods. Unfortunately, it's not possible to inline a method call in a field initializer, though I don't think it should be a problem as long as - the method is consisting of only one method call, and - all arguments are declared as final
verified fixed
4d5bc5d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-03T16:14:32Z
2003-05-27T10:06:40Z
org.eclipse.jdt.ui.tests.refactoring/resources/InlineMethodWorkspace/TestCases/invalid/TestInvalidFieldInitializer1.java
38,137
Bug 38137 inline call that is used in a field initializer [refactoring]
Often I have deprecated methods which just delegate to a new method. A nice way to get rid of them is to simply inline those methods. Unfortunately, it's not possible to inline a method call in a field initializer, though I don't think it should be a problem as long as - the method is consisting of only one method call, and - all arguments are declared as final
verified fixed
4d5bc5d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-03T16:14:32Z
2003-05-27T10:06:40Z
org.eclipse.jdt.ui.tests.refactoring/resources/InlineMethodWorkspace/TestCases/invalid/TestInvalidFieldInitializer2.java
38,137
Bug 38137 inline call that is used in a field initializer [refactoring]
Often I have deprecated methods which just delegate to a new method. A nice way to get rid of them is to simply inline those methods. Unfortunately, it's not possible to inline a method call in a field initializer, though I don't think it should be a problem as long as - the method is consisting of only one method call, and - all arguments are declared as final
verified fixed
4d5bc5d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-03T16:14:32Z
2003-05-27T10:06:40Z
org.eclipse.jdt.ui.tests.refactoring/resources/InlineMethodWorkspace/TestCases/simple_in/TestFieldInitializer1.java
38,137
Bug 38137 inline call that is used in a field initializer [refactoring]
Often I have deprecated methods which just delegate to a new method. A nice way to get rid of them is to simply inline those methods. Unfortunately, it's not possible to inline a method call in a field initializer, though I don't think it should be a problem as long as - the method is consisting of only one method call, and - all arguments are declared as final
verified fixed
4d5bc5d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-03T16:14:32Z
2003-05-27T10:06:40Z
org.eclipse.jdt.ui.tests.refactoring/resources/InlineMethodWorkspace/TestCases/simple_in/TestFieldInitializer2.java
38,137
Bug 38137 inline call that is used in a field initializer [refactoring]
Often I have deprecated methods which just delegate to a new method. A nice way to get rid of them is to simply inline those methods. Unfortunately, it's not possible to inline a method call in a field initializer, though I don't think it should be a problem as long as - the method is consisting of only one method call, and - all arguments are declared as final
verified fixed
4d5bc5d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-03T16:14:32Z
2003-05-27T10:06:40Z
org.eclipse.jdt.ui.tests.refactoring/resources/InlineMethodWorkspace/TestCases/simple_out/TestFieldInitializer1.java
38,137
Bug 38137 inline call that is used in a field initializer [refactoring]
Often I have deprecated methods which just delegate to a new method. A nice way to get rid of them is to simply inline those methods. Unfortunately, it's not possible to inline a method call in a field initializer, though I don't think it should be a problem as long as - the method is consisting of only one method call, and - all arguments are declared as final
verified fixed
4d5bc5d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-03T16:14:32Z
2003-05-27T10:06:40Z
org.eclipse.jdt.ui.tests.refactoring/resources/InlineMethodWorkspace/TestCases/simple_out/TestFieldInitializer2.java
38,137
Bug 38137 inline call that is used in a field initializer [refactoring]
Often I have deprecated methods which just delegate to a new method. A nice way to get rid of them is to simply inline those methods. Unfortunately, it's not possible to inline a method call in a field initializer, though I don't think it should be a problem as long as - the method is consisting of only one method call, and - all arguments are declared as final
verified fixed
4d5bc5d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-03T16:14:32Z
2003-05-27T10:06:40Z
org.eclipse.jdt.ui.tests.refactoring/test
38,137
Bug 38137 inline call that is used in a field initializer [refactoring]
Often I have deprecated methods which just delegate to a new method. A nice way to get rid of them is to simply inline those methods. Unfortunately, it's not possible to inline a method call in a field initializer, though I don't think it should be a problem as long as - the method is consisting of only one method call, and - all arguments are declared as final
verified fixed
4d5bc5d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-03T16:14:32Z
2003-05-27T10:06:40Z
cases/org/eclipse/jdt/ui/tests/refactoring/InlineMethodTests.java
38,137
Bug 38137 inline call that is used in a field initializer [refactoring]
Often I have deprecated methods which just delegate to a new method. A nice way to get rid of them is to simply inline those methods. Unfortunately, it's not possible to inline a method call in a field initializer, though I don't think it should be a problem as long as - the method is consisting of only one method call, and - all arguments are declared as final
verified fixed
4d5bc5d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-03T16:14:32Z
2003-05-27T10:06:40Z
org.eclipse.jdt.ui/core
38,137
Bug 38137 inline call that is used in a field initializer [refactoring]
Often I have deprecated methods which just delegate to a new method. A nice way to get rid of them is to simply inline those methods. Unfortunately, it's not possible to inline a method call in a field initializer, though I don't think it should be a problem as long as - the method is consisting of only one method call, and - all arguments are declared as final
verified fixed
4d5bc5d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-03T16:14:32Z
2003-05-27T10:06:40Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/CallInliner.java
38,137
Bug 38137 inline call that is used in a field initializer [refactoring]
Often I have deprecated methods which just delegate to a new method. A nice way to get rid of them is to simply inline those methods. Unfortunately, it's not possible to inline a method call in a field initializer, though I don't think it should be a problem as long as - the method is consisting of only one method call, and - all arguments are declared as final
verified fixed
4d5bc5d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-03T16:14:32Z
2003-05-27T10:06:40Z
org.eclipse.jdt.ui/core
38,137
Bug 38137 inline call that is used in a field initializer [refactoring]
Often I have deprecated methods which just delegate to a new method. A nice way to get rid of them is to simply inline those methods. Unfortunately, it's not possible to inline a method call in a field initializer, though I don't think it should be a problem as long as - the method is consisting of only one method call, and - all arguments are declared as final
verified fixed
4d5bc5d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-03T16:14:32Z
2003-05-27T10:06:40Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/InlineMethodRefactoring.java
38,137
Bug 38137 inline call that is used in a field initializer [refactoring]
Often I have deprecated methods which just delegate to a new method. A nice way to get rid of them is to simply inline those methods. Unfortunately, it's not possible to inline a method call in a field initializer, though I don't think it should be a problem as long as - the method is consisting of only one method call, and - all arguments are declared as final
verified fixed
4d5bc5d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-03T16:14:32Z
2003-05-27T10:06:40Z
org.eclipse.jdt.ui/core
38,137
Bug 38137 inline call that is used in a field initializer [refactoring]
Often I have deprecated methods which just delegate to a new method. A nice way to get rid of them is to simply inline those methods. Unfortunately, it's not possible to inline a method call in a field initializer, though I don't think it should be a problem as long as - the method is consisting of only one method call, and - all arguments are declared as final
verified fixed
4d5bc5d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-03T16:14:32Z
2003-05-27T10:06:40Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/InvocationAnalyzer.java
38,137
Bug 38137 inline call that is used in a field initializer [refactoring]
Often I have deprecated methods which just delegate to a new method. A nice way to get rid of them is to simply inline those methods. Unfortunately, it's not possible to inline a method call in a field initializer, though I don't think it should be a problem as long as - the method is consisting of only one method call, and - all arguments are declared as final
verified fixed
4d5bc5d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-03T16:14:32Z
2003-05-27T10:06:40Z
org.eclipse.jdt.ui/core
38,137
Bug 38137 inline call that is used in a field initializer [refactoring]
Often I have deprecated methods which just delegate to a new method. A nice way to get rid of them is to simply inline those methods. Unfortunately, it's not possible to inline a method call in a field initializer, though I don't think it should be a problem as long as - the method is consisting of only one method call, and - all arguments are declared as final
verified fixed
4d5bc5d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-03T16:14:32Z
2003-05-27T10:06:40Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/SourceProvider.java
38,137
Bug 38137 inline call that is used in a field initializer [refactoring]
Often I have deprecated methods which just delegate to a new method. A nice way to get rid of them is to simply inline those methods. Unfortunately, it's not possible to inline a method call in a field initializer, though I don't think it should be a problem as long as - the method is consisting of only one method call, and - all arguments are declared as final
verified fixed
4d5bc5d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-03T16:14:32Z
2003-05-27T10:06:40Z
org.eclipse.jdt.ui/core
38,137
Bug 38137 inline call that is used in a field initializer [refactoring]
Often I have deprecated methods which just delegate to a new method. A nice way to get rid of them is to simply inline those methods. Unfortunately, it's not possible to inline a method call in a field initializer, though I don't think it should be a problem as long as - the method is consisting of only one method call, and - all arguments are declared as final
verified fixed
4d5bc5d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-03T16:14:32Z
2003-05-27T10:06:40Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/flow/InputFlowAnalyzer.java
44,062
Bug 44062 javadoc command should correspond to default JDK [javadoc]
The java command should match the selected JDK in preferences. In OSX, I found that the default runtime was 1.4.1 but the javadoc command was using JDK 1.3.1 javadoc.
verified fixed
6ae8ee8
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-06T09:40:54Z
2003-10-02T10:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/JavadocPreferencePage.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * Sebastian Davids <[email protected]> bug 38692 *******************************************************************************/ package org.eclipse.jdt.internal.ui.preferences; import java.io.File; import org.eclipse.core.runtime.IStatus; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Text; import org.eclipse.jface.dialogs.Dialog; 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.jdt.launching.IVMInstall; import org.eclipse.jdt.launching.IVMInstallType; import org.eclipse.jdt.launching.JavaRuntime; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField; public class JavadocPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { private StringButtonDialogField fJavadocSelection; private Composite fComposite; private static final String PREF_JAVADOC_COMMAND= PreferenceConstants.JAVADOC_COMMAND; private class JDocDialogFieldAdapter implements IDialogFieldListener, IStringButtonAdapter { /* * @see IDialogFieldListener#dialogFieldChanged(DialogField) */ public void dialogFieldChanged(DialogField field) { doValidation(); } /* * @see IStringButtonAdapter#changeControlPressed(DialogField) */ public void changeControlPressed(DialogField field) { handleFileBrowseButtonPressed(fJavadocSelection.getTextControl(fComposite), null, PreferencesMessages.getString("JavadocPreferencePage.browsedialog.title")); //$NON-NLS-1$ } } /** * Returns the configured Javadoc command or the empty string. */ public static String getJavaDocCommand() { IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); String cmd= store.getString(PREF_JAVADOC_COMMAND); if (cmd.length() == 0 && store.getDefaultString(PREF_JAVADOC_COMMAND).length() == 0) { initJavadocCommandDefault(store); cmd= store.getString(PREF_JAVADOC_COMMAND); } return cmd; } public JavadocPreferencePage() { setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore()); //setDescription("Javadoc command"); //$NON-NLS-1$ } /* * @see PreferencePage#createControl(Composite) */ public void createControl(Composite parent) { super.createControl(parent); WorkbenchHelp.setHelp(getControl(), IJavaHelpContextIds.JAVADOC_PREFERENCE_PAGE); } /* * @see PreferencePage#createContents(Composite) */ protected Control createContents(Composite parent) { initializeDialogUnits(parent); GridLayout layout= new GridLayout(); layout.marginHeight= 0; layout.marginWidth= 0; layout.numColumns= 3; fComposite= new Composite(parent, SWT.NONE); fComposite.setLayout(layout); DialogField javaDocCommentLabel= new DialogField(); javaDocCommentLabel.setLabelText(PreferencesMessages.getString("JavadocPreferencePage.description")); //$NON-NLS-1$ javaDocCommentLabel.doFillIntoGrid(fComposite, 3); LayoutUtil.setWidthHint(javaDocCommentLabel.getLabelControl(null), convertWidthInCharsToPixels(80)); JDocDialogFieldAdapter adapter= new JDocDialogFieldAdapter(); fJavadocSelection= new StringButtonDialogField(adapter); fJavadocSelection.setDialogFieldListener(adapter); fJavadocSelection.setLabelText(PreferencesMessages.getString("JavadocPreferencePage.command.label")); //$NON-NLS-1$ fJavadocSelection.setButtonLabel(PreferencesMessages.getString("JavadocPreferencePage.command.button")); //$NON-NLS-1$ fJavadocSelection.doFillIntoGrid(fComposite, 3); LayoutUtil.setHorizontalGrabbing(fJavadocSelection.getTextControl(null)); LayoutUtil.setWidthHint(fJavadocSelection.getTextControl(null), convertWidthInCharsToPixels(10)); initFields(); Dialog.applyDialogFont(fComposite); return fComposite; } /* * @see IWorkbenchPreferencePage#init(IWorkbench) */ public void init(IWorkbench workbench) { } private static void initJavadocCommandDefault(IPreferenceStore store) { File file= findJavaDocCommand(); if (file != null) { store.setDefault(PREF_JAVADOC_COMMAND, file.getPath()); } } private static File findJavaDocCommand() { IVMInstallType[] jreTypes= JavaRuntime.getVMInstallTypes(); for (int i= 0; i < jreTypes.length; i++) { IVMInstallType jreType= jreTypes[i]; IVMInstall[] installs= jreType.getVMInstalls(); for (int k= 0; k < installs.length; k++) { File installLocation= installs[k].getInstallLocation(); if (installLocation != null) { File javaDocCommand= new File(installLocation, "bin/javadoc"); //$NON-NLS-1$ if (javaDocCommand.isFile()) { return javaDocCommand; } javaDocCommand= new File(installLocation, "bin/javadoc.exe"); //$NON-NLS-1$ if (javaDocCommand.isFile()) { return javaDocCommand; } } } } return null; } private void initFields() { fJavadocSelection.setTextWithoutUpdate(getJavaDocCommand()); } /* (non-Javadoc) * @see org.eclipse.jface.preference.IPreferencePage#performOk() */ public boolean performOk() { getPreferenceStore().setValue(PREF_JAVADOC_COMMAND, fJavadocSelection.getText()); JavaPlugin.getDefault().savePluginPreferences(); return super.performOk(); } /* (non-Javadoc) * @see org.eclipse.jface.preference.PreferencePage#performDefaults() */ protected void performDefaults() { IPreferenceStore store= getPreferenceStore(); initJavadocCommandDefault(store); fJavadocSelection.setText(store.getDefaultString(PREF_JAVADOC_COMMAND)); super.performDefaults(); } private void doValidation() { StatusInfo status= new StatusInfo(); String text= fJavadocSelection.getText(); if (text.length() > 0) { File file= new File(text); if (!file.isFile()) { status.setError(PreferencesMessages.getString("JavadocPreferencePage.error.notexists")); //$NON-NLS-1$ } } else { //bug 38692 status.setInfo(PreferencesMessages.getString("JavadocPreferencePage.info.notset")); //$NON-NLS-1$ } updateStatus(status); } protected void updateStatus(IStatus status) { setValid(!status.matches(IStatus.ERROR)); StatusUtil.applyToStatusLine(this, status); } protected void handleFileBrowseButtonPressed(Text text, String[] extensions, String title) { FileDialog dialog= new FileDialog(text.getShell()); dialog.setText(title); dialog.setFilterExtensions(extensions); String dirName= text.getText(); if (!dirName.equals("")) { //$NON-NLS-1$ File path= new File(dirName); if (path.exists()) dialog.setFilterPath(dirName); } String selectedDirectory= dialog.open(); if (selectedDirectory != null) text.setText(selectedDirectory); } }
44,166
Bug 44166 npe in organize imports [code manipulation]
3.0M3 on linux gtk i found this in the log java.lang.NullPointerException at org.eclipse.jdt.ui.actions.OrganizeImportsAction.doListSelectionChanged(OrganizeImportsAction.java:492) at org.eclipse.jdt.ui.actions.OrganizeImportsAction.access$2(OrganizeImportsAction.java:489) at org.eclipse.jdt.ui.actions.OrganizeImportsAction$5.handleSelectionChanged(OrganizeImportsAction.java:466) at org.eclipse.ui.dialogs.AbstractElementListSelectionDialog.handleWidgetSelected(AbstractElementListSelectionDialog.java:384) at org.eclipse.ui.dialogs.AbstractElementListSelectionDialog.access$0(AbstractElementListSelectionDialog.java:374) at org.eclipse.ui.dialogs.AbstractElementListSelectionDialog$1.widgetSelected(AbstractElementListSelectionDialog.java:364) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:89) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:953) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1872) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1652) at org.eclipse.jface.window.Window.runEventLoop(Window.java:583) at org.eclipse.jface.window.Window.open(Window.java:563) at org.eclipse.ui.dialogs.AbstractElementListSelectionDialog.open(AbstractElementListSelectionDialog.java:430) at org.eclipse.jdt.internal.ui.dialogs.MultiElementListSelectionDialog.open(MultiElementListSelectionDialog.java:107) at org.eclipse.jdt.ui.actions.OrganizeImportsAction.doChooseImports(OrganizeImportsAction.java:472) at org.eclipse.jdt.ui.actions.OrganizeImportsAction.access$1(OrganizeImportsAction.java:456) at org.eclipse.jdt.ui.actions.OrganizeImportsAction$4.chooseImports(OrganizeImportsAction.java:451) at org.eclipse.jdt.internal.corext.codemanipulation.OrganizeImportsOperation.run(OrganizeImportsOperation.java:514) at org.eclipse.jdt.internal.core.BatchOperation.executeOperation(BatchOperation.java:34) at org.eclipse.jdt.internal.core.JavaModelOperation.execute(JavaModelOperation.java:365) at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:704) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1571) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1588) at org.eclipse.jdt.core.JavaCore.run(JavaCore.java:2914) at org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter.run(WorkbenchRunnableAdapter.java:42) at org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext$BusyRunnable.internalRun(BusyIndicatorRunnableContext.java:113) at org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext$BusyRunnable.run(BusyIndicatorRunnableContext.java:80) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:84) at org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext.run(BusyIndicatorRunnableContext.java:126) at org.eclipse.jdt.ui.actions.OrganizeImportsAction.run(OrganizeImportsAction.java:418) at org.eclipse.jdt.ui.actions.OrganizeImportsAction.run(OrganizeImportsAction.java:270) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun(SelectionDispatchAction.java:194) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run(SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:529) at org.eclipse.jface.action.ActionContributionItem.access$4(ActionContributionItem.java:482) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent(ActionContributionItem.java:454) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:953)
resolved fixed
bd51be5
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-06T12:32:17Z
2003-10-03T22:26:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/OrganizeImportsAction.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.Arrays; import java.util.Collection; import java.util.HashSet; import org.eclipse.core.resources.IWorkspaceRunnable; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.MultiStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IStatusLineManager; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.window.Window; import org.eclipse.ui.IEditorActionBarContributor; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IObjectActionDelegate; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchSite; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.part.EditorActionBarContributor; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.compiler.IProblem; import org.eclipse.jdt.ui.IWorkingCopyManager; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.internal.corext.ValidateEditException; import org.eclipse.jdt.internal.corext.codemanipulation.OrganizeImportsOperation; import org.eclipse.jdt.internal.corext.codemanipulation.OrganizeImportsOperation.IChooseImportQuery; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.corext.util.TypeInfo; 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.WorkbenchRunnableAdapter; import org.eclipse.jdt.internal.ui.browsing.LogicalPackage; import org.eclipse.jdt.internal.ui.dialogs.MultiElementListSelectionDialog; import org.eclipse.jdt.internal.ui.dialogs.ProblemDialog; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor; 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.util.TypeInfoLabelProvider; /** * Organizes the imports of a compilation unit. * <p> * The action is applicable to selections containing elements of * type <code>ICompilationUnit</code> or <code>IPackage * </code>. * * <p> * This class may be instantiated; it is not intended to be subclassed. * </p> * * @since 2.0 */ public class OrganizeImportsAction extends SelectionDispatchAction { private JavaEditor fEditor; /* (non-Javadoc) * Class implements IObjectActionDelegate */ public static class ObjectDelegate implements IObjectActionDelegate { private OrganizeImportsAction fAction; public void setActivePart(IAction action, IWorkbenchPart targetPart) { fAction= new OrganizeImportsAction(targetPart.getSite()); } public void run(IAction action) { fAction.run(); } public void selectionChanged(IAction action, ISelection selection) { if (fAction == null) action.setEnabled(false); } } /** * Creates a new <code>OrganizeImportsAction</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 OrganizeImportsAction(IWorkbenchSite site) { super(site); setText(ActionMessages.getString("OrganizeImportsAction.label")); //$NON-NLS-1$ setToolTipText(ActionMessages.getString("OrganizeImportsAction.tooltip")); //$NON-NLS-1$ setDescription(ActionMessages.getString("OrganizeImportsAction.description")); //$NON-NLS-1$ WorkbenchHelp.setHelp(this, IJavaHelpContextIds.ORGANIZE_IMPORTS_ACTION); } /** * Note: This constructor is for internal use only. Clients should not call this constructor. */ public OrganizeImportsAction(JavaEditor editor) { this(editor.getEditorSite()); fEditor= editor; setEnabled(getCompilationUnit(fEditor) != null); } /* (non-Javadoc) * Method declared on SelectionDispatchAction. */ public void selectionChanged(ITextSelection selection) { // do nothing } /* (non-Javadoc) * Method declared on SelectionDispatchAction. */ public void selectionChanged(IStructuredSelection selection) { setEnabled(isEnabled(selection)); } private ICompilationUnit[] getCompilationUnits(IStructuredSelection selection) { HashSet result= new HashSet(); Object[] selected= selection.toArray(); for (int i= 0; i < selected.length; i++) { try { if (selected[i] instanceof IJavaElement) { IJavaElement elem= (IJavaElement) selected[i]; if (elem.exists()) { switch (elem.getElementType()) { case IJavaElement.TYPE: if (elem.getParent().getElementType() == IJavaElement.COMPILATION_UNIT) { result.add(elem.getParent()); } break; case IJavaElement.COMPILATION_UNIT: result.add(elem); break; case IJavaElement.IMPORT_CONTAINER: result.add(elem.getParent()); break; case IJavaElement.PACKAGE_FRAGMENT: collectCompilationUnits((IPackageFragment) elem, result); break; case IJavaElement.PACKAGE_FRAGMENT_ROOT: collectCompilationUnits((IPackageFragmentRoot) elem, result); break; case IJavaElement.JAVA_PROJECT: IPackageFragmentRoot[] roots= ((IJavaProject) elem).getPackageFragmentRoots(); for (int k= 0; k < roots.length; k++) { collectCompilationUnits(roots[k], result); } break; } } } else if (selected[i] instanceof LogicalPackage) { IPackageFragment[] packageFragments= ((LogicalPackage)selected[i]).getFragments(); for (int k= 0; k < packageFragments.length; k++) { IPackageFragment pack= packageFragments[k]; if (pack.exists()) { collectCompilationUnits(pack, result); } } } } catch (JavaModelException e) { JavaPlugin.log(e); } } return (ICompilationUnit[]) result.toArray(new ICompilationUnit[result.size()]); } private void collectCompilationUnits(IPackageFragment pack, Collection result) throws JavaModelException { result.addAll(Arrays.asList(pack.getCompilationUnits())); } private void collectCompilationUnits(IPackageFragmentRoot root, Collection result) throws JavaModelException { if (root.getKind() == IPackageFragmentRoot.K_SOURCE) { IJavaElement[] children= root.getChildren(); for (int i= 0; i < children.length; i++) { collectCompilationUnits((IPackageFragment) children[i], result); } } } private boolean isEnabled(IStructuredSelection selection) { Object[] selected= selection.toArray(); for (int i= 0; i < selected.length; i++) { try { if (selected[i] instanceof IJavaElement) { IJavaElement elem= (IJavaElement) selected[i]; if (elem.exists()) { switch (elem.getElementType()) { case IJavaElement.TYPE: return elem.getParent().getElementType() == IJavaElement.COMPILATION_UNIT; // for browsing perspective case IJavaElement.COMPILATION_UNIT: return true; case IJavaElement.IMPORT_CONTAINER: return true; case IJavaElement.PACKAGE_FRAGMENT: case IJavaElement.PACKAGE_FRAGMENT_ROOT: IPackageFragmentRoot root= (IPackageFragmentRoot) elem.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); return (root.getKind() == IPackageFragmentRoot.K_SOURCE); case IJavaElement.JAVA_PROJECT: return hasSourceFolders((IJavaProject) elem); } } } else if (selected[i] instanceof LogicalPackage) { return true; } } catch (JavaModelException e) { JavaPlugin.log(e); } } return false; } private boolean hasSourceFolders(IJavaProject project) throws JavaModelException { IPackageFragmentRoot[] roots= project.getPackageFragmentRoots(); for (int i= 0; i < roots.length; i++) { IPackageFragmentRoot root= roots[i]; if (root.getKind() == IPackageFragmentRoot.K_SOURCE) { return true; } } return false; } /* (non-Javadoc) * Method declared on SelectionDispatchAction. */ public void run(ITextSelection selection) { run(getCompilationUnit(fEditor)); } private static ICompilationUnit getCompilationUnit(JavaEditor editor) { IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager(); ICompilationUnit cu= manager.getWorkingCopy(editor.getEditorInput()); return cu; } /* (non-Javadoc) * Method declared on SelectionDispatchAction. */ public void run(IStructuredSelection selection) { ICompilationUnit[] cus= getCompilationUnits(selection); if (cus.length == 1) { run(cus[0]); } else { runOnMultiple(cus); } } /** * Peform organize import on multiple compilation units. No editors are opened. */ public void runOnMultiple(final ICompilationUnit[] cus) { try { String message= ActionMessages.getString("OrganizeImportsAction.multi.status.description"); //$NON-NLS-1$ final MultiStatus status= new MultiStatus(JavaUI.ID_PLUGIN, IStatus.OK, message, null); ProgressMonitorDialog dialog= new ProgressMonitorDialog(getShell()); dialog.run(true, true, new WorkbenchRunnableAdapter(new IWorkspaceRunnable() { public void run(IProgressMonitor monitor) { doRunOnMultiple(cus, status, monitor); } })); if (!status.isOK()) { String title= ActionMessages.getString("OrganizeImportsAction.multi.status.title"); //$NON-NLS-1$ ProblemDialog.open(getShell(), title, null, status); } } catch (InvocationTargetException e) { ExceptionHandler.handle(e, getShell(), ActionMessages.getString("OrganizeImportsAction.error.title"), ActionMessages.getString("OrganizeImportsAction.error.message")); //$NON-NLS-1$ //$NON-NLS-2$ } catch (InterruptedException e) { // cancelled by user } } static final class OrganizeImportError extends Error { } private void doRunOnMultiple(ICompilationUnit[] cus, MultiStatus status, IProgressMonitor monitor) throws OperationCanceledException { if (monitor == null) { monitor= new NullProgressMonitor(); } monitor.setTaskName(ActionMessages.getString("OrganizeImportsAction.multi.op.description")); //$NON-NLS-1$ monitor.beginTask("", cus.length); //$NON-NLS-1$ try { IPreferenceStore store= PreferenceConstants.getPreferenceStore(); String[] prefOrder= JavaPreferencesSettings.getImportOrderPreference(store); int threshold= JavaPreferencesSettings.getImportNumberThreshold(store); boolean ignoreLowerCaseNames= store.getBoolean(PreferenceConstants.ORGIMPORTS_IGNORELOWERCASE); IChooseImportQuery query= new IChooseImportQuery() { public TypeInfo[] chooseImports(TypeInfo[][] openChoices, ISourceRange[] ranges) { throw new OrganizeImportError(); } }; for (int i= 0; i < cus.length; i++) { ICompilationUnit cu= cus[i]; if (testOnBuildPath(cu, status)) { String cuLocation= cu.getPath().makeRelative().toString(); cu= JavaModelUtil.toWorkingCopy(cu); monitor.subTask(cuLocation); try { OrganizeImportsOperation op= new OrganizeImportsOperation(cu, prefOrder, threshold, ignoreLowerCaseNames, !cu.isWorkingCopy(), true, query); runInSync(op, cuLocation, status, monitor); IProblem parseError= op.getParseError(); if (parseError != null) { String message= ActionMessages.getFormattedString("OrganizeImportsAction.multi.error.parse", cuLocation); //$NON-NLS-1$ status.add(new Status(IStatus.INFO, JavaUI.ID_PLUGIN, IStatus.ERROR, message, null)); } } catch (CoreException e) { JavaPlugin.log(e); String message= ActionMessages.getFormattedString("OrganizeImportsAction.multi.error.unexpected", e.getStatus().getMessage()); //$NON-NLS-1$ status.add(new Status(IStatus.ERROR, JavaUI.ID_PLUGIN, IStatus.ERROR, message, null)); } if (monitor.isCanceled()) { throw new OperationCanceledException(); } } } } finally { monitor.done(); } } private boolean testOnBuildPath(ICompilationUnit cu, MultiStatus status) { IJavaProject project= cu.getJavaProject(); if (!project.isOnClasspath(cu)) { String cuLocation= cu.getPath().makeRelative().toString(); String message= ActionMessages.getFormattedString("OrganizeImportsAction.multi.error.notoncp", cuLocation); //$NON-NLS-1$ status.add(new Status(IStatus.INFO, JavaUI.ID_PLUGIN, IStatus.ERROR, message, null)); return false; } return true; } private void runInSync(final OrganizeImportsOperation op, final String cuLocation, final MultiStatus status, final IProgressMonitor monitor) { Runnable runnable= new Runnable() { public void run() { try { op.run(new SubProgressMonitor(monitor, 1)); } catch (ValidateEditException e) { status.add(e.getStatus()); } catch (CoreException e) { JavaPlugin.log(e); String message= ActionMessages.getFormattedString("OrganizeImportsAction.multi.error.unexpected", e.getStatus().getMessage()); //$NON-NLS-1$ status.add(new Status(IStatus.ERROR, JavaUI.ID_PLUGIN, IStatus.ERROR, message, null)); } catch (OrganizeImportError e) { String message= ActionMessages.getFormattedString("OrganizeImportsAction.multi.error.unresolvable", cuLocation); //$NON-NLS-1$ status.add(new Status(IStatus.INFO, JavaUI.ID_PLUGIN, IStatus.ERROR, message, null)); } } }; getShell().getDisplay().syncExec(runnable); } /** * Note: This method is for internal use only. Clients should not call this method. */ public void run(ICompilationUnit cu) { if (!ElementValidator.check(cu, getShell(), ActionMessages.getString("OrganizeImportsAction.error.title"), fEditor != null)) //$NON-NLS-1$ return; if (!ActionUtil.isProcessable(getShell(), cu)) return; try { IPreferenceStore store= PreferenceConstants.getPreferenceStore(); String[] prefOrder= JavaPreferencesSettings.getImportOrderPreference(store); int threshold= JavaPreferencesSettings.getImportNumberThreshold(store); boolean ignoreLowerCaseNames= store.getBoolean(PreferenceConstants.ORGIMPORTS_IGNORELOWERCASE); if (!cu.isWorkingCopy()) { IEditorPart editor= EditorUtility.openInEditor(cu); if (editor instanceof JavaEditor) { fEditor= (JavaEditor) editor; } cu= JavaModelUtil.toWorkingCopy(cu); } OrganizeImportsOperation op= new OrganizeImportsOperation(cu, prefOrder, threshold, ignoreLowerCaseNames, !cu.isWorkingCopy(), true, createChooseImportQuery()); BusyIndicatorRunnableContext context= new BusyIndicatorRunnableContext(); context.run(false, true, new WorkbenchRunnableAdapter(op)); IProblem parseError= op.getParseError(); if (parseError != null) { String message= ActionMessages.getFormattedString("OrganizeImportsAction.single.error.parse", parseError.getMessage()); //$NON-NLS-1$ MessageDialog.openInformation(getShell(), ActionMessages.getString("OrganizeImportsAction.error.title"), message); //$NON-NLS-1$ if (fEditor != null && parseError.getSourceStart() != -1) { fEditor.selectAndReveal(parseError.getSourceStart(), parseError.getSourceEnd() - parseError.getSourceStart() + 1); } } else { if (fEditor != null) { setStatusBarMessage(getOrganizeInfo(op)); } } } catch (CoreException e) { ExceptionHandler.handle(e, getShell(), ActionMessages.getString("OrganizeImportsAction.error.title"), ActionMessages.getString("OrganizeImportsAction.error.message")); //$NON-NLS-1$ //$NON-NLS-2$ } catch (InvocationTargetException e) { ExceptionHandler.handle(e, getShell(), ActionMessages.getString("OrganizeImportsAction.error.title"), ActionMessages.getString("OrganizeImportsAction.error.message")); //$NON-NLS-1$ //$NON-NLS-2$ } catch (InterruptedException e) { } } private String getOrganizeInfo(OrganizeImportsOperation op) { int nImportsAdded= op.getNumberOfImportsAdded(); if (nImportsAdded >= 0) { return ActionMessages.getFormattedString("OrganizeImportsAction.summary_added", String.valueOf(nImportsAdded)); //$NON-NLS-1$ } else { return ActionMessages.getFormattedString("OrganizeImportsAction.summary_removed", String.valueOf(-nImportsAdded)); //$NON-NLS-1$ } } private IChooseImportQuery createChooseImportQuery() { return new IChooseImportQuery() { public TypeInfo[] chooseImports(TypeInfo[][] openChoices, ISourceRange[] ranges) { return doChooseImports(openChoices, ranges); } }; } private TypeInfo[] doChooseImports(TypeInfo[][] openChoices, final ISourceRange[] ranges) { // remember selection ISelection sel= fEditor != null ? fEditor.getSelectionProvider().getSelection() : null; TypeInfo[] result= null; ILabelProvider labelProvider= new TypeInfoLabelProvider(TypeInfoLabelProvider.SHOW_FULLYQUALIFIED); MultiElementListSelectionDialog dialog= new MultiElementListSelectionDialog(getShell(), labelProvider) { protected void handleSelectionChanged() { super.handleSelectionChanged(); // show choices in editor doListSelectionChanged(getCurrentPage(), ranges); } }; dialog.setTitle(ActionMessages.getString("OrganizeImportsAction.selectiondialog.title")); //$NON-NLS-1$ dialog.setMessage(ActionMessages.getString("OrganizeImportsAction.selectiondialog.message")); //$NON-NLS-1$ dialog.setElements(openChoices); if (dialog.open() == Window.OK) { Object[] res= dialog.getResult(); result= new TypeInfo[res.length]; for (int i= 0; i < res.length; i++) { Object[] array= (Object[]) res[i]; if (array.length > 0) result[i]= (TypeInfo) array[0]; } } // restore selection if (sel instanceof ITextSelection) { ITextSelection textSelection= (ITextSelection) sel; fEditor.selectAndReveal(textSelection.getOffset(), textSelection.getLength()); } return result; } private void doListSelectionChanged(int page, ISourceRange[] ranges) { if (page >= 0 && page < ranges.length) { ISourceRange range= ranges[page]; fEditor.selectAndReveal(range.getOffset(), range.getLength()); } } private void setStatusBarMessage(String message) { IEditorActionBarContributor contributor= fEditor.getEditorSite().getActionBarContributor(); if (contributor instanceof EditorActionBarContributor) { IStatusLineManager manager= ((EditorActionBarContributor) contributor).getActionBars().getStatusLineManager(); manager.setMessage(message); } } }
18,316
Bug 18316 Status line update when selecting task in task list
The following code snippet is executes by the CompilationUnitEditor when pressing the Next/Previous Problem buttons in the toolbar and also when using the keyboard shortcuts Ctrl+E/P. In the first case, the task list selection is updated and the status line is changed. In the second case, the status line is cleared. (The method setStatusLineErrorMessage calls setErrorMessage of the status line manager.) 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(errorPosition.getOffset(), errorPosition.getLength()); setStatusLineErrorMessage(nextError.getMessage());
verified fixed
64aa612
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-06T15:37:22Z
2002-05-30T14:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/JavaEditor.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.javaeditor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; 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.IStatus; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Preferences; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.BidiSegmentEvent; import org.eclipse.swt.custom.BidiSegmentListener; import org.eclipse.swt.custom.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.Shell; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.GroupMarker; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IStatusLineManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferenceConverter; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.IPostSelectionProvider; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.DefaultInformationControl; import org.eclipse.jface.text.DocumentEvent; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocumentListener; import org.eclipse.jface.text.IInformationControl; import org.eclipse.jface.text.IInformationControlCreator; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextHover; import org.eclipse.jface.text.ITextInputListener; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.ITextViewerExtension2; import org.eclipse.jface.text.ITextViewerExtension3; import org.eclipse.jface.text.ITextViewerExtension4; import org.eclipse.jface.text.ITypedRegion; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.Region; import org.eclipse.jface.text.TextSelection; import org.eclipse.jface.text.TextUtilities; import org.eclipse.jface.text.information.IInformationProvider; import org.eclipse.jface.text.information.IInformationProviderExtension2; import org.eclipse.jface.text.information.InformationPresenter; import org.eclipse.jface.text.source.Annotation; import org.eclipse.jface.text.source.IAnnotationAccess; import org.eclipse.jface.text.source.IAnnotationModel; import org.eclipse.jface.text.source.IOverviewRuler; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.jface.text.source.IVerticalRuler; import org.eclipse.jface.text.source.LineChangeHover; import org.eclipse.jface.text.source.SourceViewerConfiguration; import org.eclipse.ui.IEditorActionBarContributor; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IPageLayout; import org.eclipse.ui.IPartService; import org.eclipse.ui.IViewPart; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.actions.ActionContext; import org.eclipse.ui.actions.ActionGroup; import org.eclipse.ui.editors.text.DefaultEncodingSupport; import org.eclipse.ui.editors.text.IEncodingSupport; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.part.EditorActionBarContributor; import org.eclipse.ui.part.IShowInTargetList; import org.eclipse.ui.texteditor.AddTaskAction; import org.eclipse.ui.texteditor.AnnotationPreference; import org.eclipse.ui.texteditor.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.jdt.core.IClassFile; import org.eclipse.jdt.core.ICodeAssist; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IImportContainer; import org.eclipse.jdt.core.IImportDeclaration; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IPackageDeclaration; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.ISourceReference; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.IContextMenuConstants; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.actions.IJavaEditorActionDefinitionIds; import org.eclipse.jdt.ui.actions.JavaSearchActionGroup; import org.eclipse.jdt.ui.actions.OpenEditorActionGroup; import org.eclipse.jdt.ui.actions.OpenViewActionGroup; import org.eclipse.jdt.ui.actions.ShowActionGroup; import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration; import org.eclipse.jdt.ui.text.JavaTextTools; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup; import org.eclipse.jdt.internal.ui.actions.SelectionConverter; import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.GoToNextPreviousMemberAction; import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.SelectionHistory; import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectEnclosingAction; import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectHistoryAction; import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectNextAction; import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectPreviousAction; import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectionAction; import org.eclipse.jdt.internal.ui.text.HTMLTextPresenter; import org.eclipse.jdt.internal.ui.text.IJavaPartitions; import org.eclipse.jdt.internal.ui.text.JavaChangeHover; import org.eclipse.jdt.internal.ui.text.JavaPairMatcher; import org.eclipse.jdt.internal.ui.util.JavaUIHelp; import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider; /** * Java specific text editor. */ public abstract class JavaEditor extends ExtendedTextEditor implements IViewPartInputProvider { /** * Internal implementation class for a change listener. * @since 3.0 */ protected abstract class AbstractSelectionChangedListener implements ISelectionChangedListener { /** * Installs this selection changed listener with the given selection provider. If * the selection provider is a post selection provider, post selection changed * events are the preferred choice, otherwise normal selection changed events * are requested. * * @param selectionProvider */ public void install(ISelectionProvider selectionProvider) { if (selectionProvider == null) return; if (selectionProvider instanceof IPostSelectionProvider) { IPostSelectionProvider provider= (IPostSelectionProvider) selectionProvider; provider.addPostSelectionChangedListener(this); } else { selectionProvider.addSelectionChangedListener(this); } } /** * Removes this selection changed listener from the given selection provider. * * @param selectionProvider */ public void uninstall(ISelectionProvider selectionProvider) { if (selectionProvider == null) return; if (selectionProvider instanceof IPostSelectionProvider) { IPostSelectionProvider provider= (IPostSelectionProvider) selectionProvider; provider.removePostSelectionChangedListener(this); } else { selectionProvider.removeSelectionChangedListener(this); } } } /** * Updates the Java outline page selection and this editor's range indicator. * * @since 3.0 */ private class EditorSelectionChangedListener extends AbstractSelectionChangedListener { /* * @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent) */ public void selectionChanged(SelectionChangedEvent event) { selectionChanged(); } public void selectionChanged() { ISourceReference element= computeHighlightRangeSourceReference(); synchronizeOutlinePage(element); setSelection(element, false); } } /** * Updates the selection in the editor's widget with the selection of the outline page. */ class OutlineSelectionChangedListener extends AbstractSelectionChangedListener { public void selectionChanged(SelectionChangedEvent event) { doSelectionChanged(event); } } /* * Link mode. */ class MouseClickListener implements KeyListener, MouseListener, MouseMoveListener, FocusListener, PaintListener, IPropertyChangeListener, IDocumentListener, ITextInputListener { /** The session is active. */ private boolean fActive; /** The currently active style range. */ private IRegion fActiveRegion; /** The currently active style range as position. */ private Position fRememberedPosition; /** The hand cursor. */ private Cursor fCursor; /** The link color. */ private Color fColor; /** The key modifier mask. */ private int fKeyModifierMask; public void deactivate() { deactivate(false); } public void deactivate(boolean redrawAll) { if (!fActive) return; repairRepresentation(redrawAll); fActive= false; } public void install() { ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer == null) return; StyledText text= sourceViewer.getTextWidget(); if (text == null || text.isDisposed()) return; updateColor(sourceViewer); sourceViewer.addTextInputListener(this); IDocument document= sourceViewer.getDocument(); if (document != null) document.addDocumentListener(this); text.addKeyListener(this); text.addMouseListener(this); text.addMouseMoveListener(this); text.addFocusListener(this); text.addPaintListener(this); updateKeyModifierMask(); IPreferenceStore preferenceStore= getPreferenceStore(); preferenceStore.addPropertyChangeListener(this); } private void updateKeyModifierMask() { String modifiers= getPreferenceStore().getString(BROWSER_LIKE_LINKS_KEY_MODIFIER); fKeyModifierMask= computeStateMask(modifiers); if (fKeyModifierMask == -1) { // Fallback to stored state mask fKeyModifierMask= getPreferenceStore().getInt(BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK); } } private int computeStateMask(String modifiers) { if (modifiers == null) return -1; if (modifiers.length() == 0) return SWT.NONE; int stateMask= 0; StringTokenizer modifierTokenizer= new StringTokenizer(modifiers, ",;.:+-* "); //$NON-NLS-1$ while (modifierTokenizer.hasMoreTokens()) { int modifier= EditorUtility.findLocalizedModifier(modifierTokenizer.nextToken()); if (modifier == 0 || (stateMask & modifier) == modifier) return -1; stateMask= stateMask | modifier; } return stateMask; } public void uninstall() { if (fColor != null) { fColor.dispose(); fColor= null; } if (fCursor != null) { fCursor.dispose(); fCursor= null; } ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer == null) return; sourceViewer.removeTextInputListener(this); IDocument document= sourceViewer.getDocument(); if (document != null) document.removeDocumentListener(this); IPreferenceStore preferenceStore= getPreferenceStore(); if (preferenceStore != null) preferenceStore.removePropertyChangeListener(this); StyledText text= sourceViewer.getTextWidget(); if (text == null || text.isDisposed()) return; text.removeKeyListener(this); text.removeMouseListener(this); text.removeMouseMoveListener(this); text.removeFocusListener(this); text.removePaintListener(this); } /* * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent) */ public void propertyChange(PropertyChangeEvent event) { if (event.getProperty().equals(JavaEditor.LINK_COLOR)) { ISourceViewer viewer= getSourceViewer(); if (viewer != null) updateColor(viewer); } else if (event.getProperty().equals(BROWSER_LIKE_LINKS_KEY_MODIFIER)) { updateKeyModifierMask(); } } private void updateColor(ISourceViewer viewer) { if (fColor != null) fColor.dispose(); StyledText text= viewer.getTextWidget(); if (text == null || text.isDisposed()) return; Display display= text.getDisplay(); fColor= createColor(getPreferenceStore(), JavaEditor.LINK_COLOR, display); } /** * Creates a color from the information stored in the given preference store. * Returns <code>null</code> if there is no such information available. */ private Color createColor(IPreferenceStore store, String key, Display display) { RGB rgb= null; if (store.contains(key)) { if (store.isDefault(key)) rgb= PreferenceConverter.getDefaultColor(store, key); else rgb= PreferenceConverter.getColor(store, key); if (rgb != null) return new Color(display, rgb); } return null; } private void repairRepresentation() { repairRepresentation(false); } private void repairRepresentation(boolean redrawAll) { if (fActiveRegion == null) return; int offset= fActiveRegion.getOffset(); int length= fActiveRegion.getLength(); fActiveRegion= null; ISourceViewer viewer= getSourceViewer(); if (viewer != null) { resetCursor(viewer); // 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); } } } // 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) { if (!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(); } }); } } } else { fActiveRegion= null; fRememberedPosition= null; 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; } return super.getType(annotation); } /* * @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); getTextWidget().showSelection(); fireSelectionChanged(); 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) { getTextWidget().setCaretOffset(modelOffset2WidgetOffset(getSourceViewer(), 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); } } } /** * 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); while (position >= 0 && Character.isUpperCase(character)) character= document.getChar(--position); setCaretPosition(position + 1); getTextWidget().showSelection(); fireSelectionChanged(); 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) { getTextWidget().setCaretOffset(modelOffset2WidgetOffset(getSourceViewer(), 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); } } } /** * Quick format action to format the enclosing java element. * <p> * The quick format action works as follows: * <ul> * <li>If there is no selection and the caret is positioned on a Java element, * only this element is formatted. If the element has some accompanying comment, * then the comment is formatted as well.</li> * <li>If the selection spans one or more partitions of the document, then all * partitions covered by the selection are entirely formatted.</li> * <p> * Partitions at the end of the selection are not completed, except for comments. * * @since 3.0 */ protected class QuickFormatAction extends Action { /* * @see org.eclipse.jface.action.IAction#run() */ public void run() { final JavaSourceViewer viewer= (JavaSourceViewer) getSourceViewer(); if (viewer.isEditable()) { final Point selection= viewer.rememberSelection(); try { viewer.setRedraw(false); final String type= TextUtilities.getContentType(viewer.getDocument(), IJavaPartitions.JAVA_PARTITIONING, selection.x); if (type.equals(IDocument.DEFAULT_CONTENT_TYPE) && selection.y == 0) { try { final IJavaElement element= getElementAt(selection.x, true); if (element != null && element.exists()) { final int kind= element.getElementType(); if (kind == IJavaElement.TYPE || kind == IJavaElement.METHOD || kind == IJavaElement.INITIALIZER) { final ISourceReference reference= (ISourceReference)element; final ISourceRange range= reference.getSourceRange(); if (range != null) { viewer.setSelectedRange(range.getOffset(), range.getLength()); viewer.doOperation(ISourceViewer.FORMAT); } } } } catch (JavaModelException exception) { // Should not happen } } else { viewer.setSelectedRange(selection.x, 1); viewer.doOperation(ISourceViewer.FORMAT); } } catch (BadLocationException exception) { // Can not happen } finally { viewer.setRedraw(true); viewer.restoreSelection(); } } } } /** 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); /** This editor's encoding support */ private DefaultEncodingSupport fEncodingSupport; /** 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 (IEncodingSupport.class.equals(required)) return fEncodingSupport; if (required == IShowInTargetList.class) { return new IShowInTargetList() { public String[] getShowInTargetIds() { return new String[] { JavaUI.ID_PACKAGES, IPageLayout.ID_OUTLINE, IPageLayout.ID_RES_NAV }; } }; } return super.getAdapter(required); } protected void setSelection(ISourceReference reference, boolean moveCursor) { ISelection selection= getSelectionProvider().getSelection(); if (selection instanceof TextSelection) { TextSelection textSelection= (TextSelection) selection; // 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 StatusTextEditor#getStatusHeader(IStatus) */ protected String getStatusHeader(IStatus status) { if (fEncodingSupport != null) { String message= fEncodingSupport.getStatusHeader(status); if (message != null) return message; } return super.getStatusHeader(status); } /* * @see StatusTextEditor#getStatusBanner(IStatus) */ protected String getStatusBanner(IStatus status) { if (fEncodingSupport != null) { String message= fEncodingSupport.getStatusBanner(status); if (message != null) return message; } return super.getStatusBanner(status); } /* * @see StatusTextEditor#getStatusMessage(IStatus) */ protected String getStatusMessage(IStatus status) { if (fEncodingSupport != null) { String message= fEncodingSupport.getStatusMessage(status); if (message != null) return message; } return super.getStatusMessage(status); } /* * @see AbstractTextEditor#doSetInput */ protected void doSetInput(IEditorInput input) throws CoreException { super.doSetInput(input); if (fEncodingSupport != null) fEncodingSupport.reset(); setOutlinePageInput(fOutlinePage, input); } /* * @see IWorkbenchPart#dispose() */ public void dispose() { if (isBrowserLikeLinks()) disableBrowserLikeLinks(); if (fEncodingSupport != null) { fEncodingSupport.dispose(); fEncodingSupport= null; } if (fPropertyChangeListener != null) { Preferences preferences= JavaCore.getPlugin().getPluginPreferences(); preferences.removePropertyChangeListener(fPropertyChangeListener); fPropertyChangeListener= null; } if (fBracketMatcher != null) { fBracketMatcher.dispose(); fBracketMatcher= null; } if (fSelectionHistory != null) { fSelectionHistory.dispose(); fSelectionHistory= null; } if (fEditorSelectionChangedListener != null) { fEditorSelectionChangedListener.uninstall(getSelectionProvider()); fEditorSelectionChangedListener= null; } super.dispose(); } protected void createActions() { super.createActions(); ResourceAction resAction= new AddTaskAction(JavaEditorMessages.getResourceBundle(), "AddTask.", this); //$NON-NLS-1$ resAction.setHelpContextId(IAbstractTextEditorHelpContextIds.ADD_TASK_ACTION); resAction.setActionDefinitionId(ITextEditorActionDefinitionIds.ADD_TASK); setAction(ITextEditorActionConstants.ADD_TASK, resAction); ActionGroup oeg, ovg, jsg, sg; fActionGroups= new CompositeActionGroup(new ActionGroup[] { oeg= new OpenEditorActionGroup(this), sg= new ShowActionGroup(this), ovg= new OpenViewActionGroup(this), jsg= new JavaSearchActionGroup(this) }); fContextMenuGroup= new CompositeActionGroup(new ActionGroup[] {oeg, ovg, sg, jsg}); resAction= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc.", this, ISourceViewer.INFORMATION, true); //$NON-NLS-1$ resAction= new InformationDispatchAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc.", (TextOperationAction) resAction); //$NON-NLS-1$ resAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_JAVADOC); setAction("ShowJavaDoc", resAction); //$NON-NLS-1$ WorkbenchHelp.setHelp(resAction, IJavaHelpContextIds.SHOW_JAVADOC_ACTION); Action action= new GotoMatchingBracketAction(this); action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_MATCHING_BRACKET); setAction(GotoMatchingBracketAction.GOTO_MATCHING_BRACKET, action); action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"ShowOutline.", this, JavaSourceViewer.SHOW_OUTLINE, true); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_OUTLINE); setAction(IJavaEditorActionDefinitionIds.SHOW_OUTLINE, action); WorkbenchHelp.setHelp(action, IJavaHelpContextIds.SHOW_OUTLINE_ACTION); action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"OpenStructure.", this, JavaSourceViewer.OPEN_STRUCTURE, true); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_STRUCTURE); setAction(IJavaEditorActionDefinitionIds.OPEN_STRUCTURE, action); WorkbenchHelp.setHelp(action, IJavaHelpContextIds.OPEN_STRUCTURE_ACTION); action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"OpenHierarchy.", this, JavaSourceViewer.SHOW_HIERARCHY, true); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_HIERARCHY); setAction(IJavaEditorActionDefinitionIds.OPEN_HIERARCHY, action); WorkbenchHelp.setHelp(action, IJavaHelpContextIds.OPEN_HIERARCHY_ACTION); fEncodingSupport= new DefaultEncodingSupport(); fEncodingSupport.initialize(this); fSelectionHistory= new SelectionHistory(this); action= new StructureSelectEnclosingAction(this, fSelectionHistory); action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_ENCLOSING); setAction(StructureSelectionAction.ENCLOSING, action); action= new StructureSelectNextAction(this, fSelectionHistory); action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_NEXT); setAction(StructureSelectionAction.NEXT, action); action= new StructureSelectPreviousAction(this, fSelectionHistory); action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_PREVIOUS); setAction(StructureSelectionAction.PREVIOUS, action); StructureSelectHistoryAction historyAction= new StructureSelectHistoryAction(this, fSelectionHistory); historyAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_LAST); setAction(StructureSelectionAction.HISTORY, historyAction); fSelectionHistory.setHistoryAction(historyAction); action= GoToNextPreviousMemberAction.newGoToNextMemberAction(this); action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_NEXT_MEMBER); setAction(GoToNextPreviousMemberAction.NEXT_MEMBER, action); action= GoToNextPreviousMemberAction.newGoToPreviousMemberAction(this); action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_PREVIOUS_MEMBER); setAction(GoToNextPreviousMemberAction.PREVIOUS_MEMBER, action); action= new QuickFormatAction(); action.setActionDefinitionId(IJavaEditorActionDefinitionIds.QUICK_FORMAT); setAction(IJavaEditorActionDefinitionIds.QUICK_FORMAT, 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; } /* * @see org.eclipse.ui.texteditor.AbstractTextEditor#updatePropertyDependentActions() */ protected void updatePropertyDependentActions() { super.updatePropertyDependentActions(); if (fEncodingSupport != null) fEncodingSupport.reset(); } /* * Update the hovering behavior depending on the preferences. */ private void updateHoverBehavior() { SourceViewerConfiguration configuration= getSourceViewerConfiguration(); String[] types= configuration.getConfiguredContentTypes(getSourceViewer()); for (int i= 0; i < types.length; i++) { String t= types[i]; ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer instanceof ITextViewerExtension2) { // Remove existing hovers ((ITextViewerExtension2)sourceViewer).removeTextHovers(t); int[] stateMasks= configuration.getConfiguredTextHoverStateMasks(getSourceViewer(), t); if (stateMasks != null) { for (int j= 0; j < stateMasks.length; j++) { int stateMask= stateMasks[j]; ITextHover textHover= configuration.getTextHover(sourceViewer, t, stateMask); ((ITextViewerExtension2)sourceViewer).setTextHover(textHover, t, stateMask); } } else { ITextHover textHover= configuration.getTextHover(sourceViewer, t); ((ITextViewerExtension2)sourceViewer).setTextHover(textHover, t, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK); } } else sourceViewer.setTextHover(configuration.getTextHover(sourceViewer, t), t); } } /* * @see org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput() */ public Object getViewPartInput() { return getEditorInput().getAdapter(IJavaElement.class); } /* * @see org.eclipse.ui.texteditor.AbstractTextEditor#doSetSelection(ISelection) */ protected void doSetSelection(ISelection selection) { super.doSetSelection(selection); synchronizeOutlinePageSelection(); } /* * @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite) */ public void createPartControl(Composite parent) { super.createPartControl(parent); 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); Annotation 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 if (nextAnnotation instanceof IJavaAnnotation) { Iterator e= ((IJavaAnnotation)nextAnnotation).getOverlaidIterator(); if (e != null) { while (e.hasNext()) { Object o= e.next(); if (o instanceof MarkerAnnotation) { marker= ((MarkerAnnotation) o).getMarker(); break; } } } } if (marker != null) { try { boolean isProblem= marker.isSubtypeOf(IMarker.PROBLEM); IWorkbenchPage page= getSite().getPage(); IViewPart view= view= page.findView(isProblem ? IPageLayout.ID_PROBLEM_VIEW: IPageLayout.ID_TASK_LIST); //$NON-NLS-1$ //$NON-NLS-2$ Method method= view.getClass().getMethod("setSelection", new Class[] { IStructuredSelection.class, boolean.class}); //$NON-NLS-1$ method.invoke(view, new Object[] {new StructuredSelection(marker), Boolean.TRUE }); } catch (CoreException x) { } catch (NoSuchMethodException x) { } catch (IllegalAccessException x) { } catch (InvocationTargetException x) { } // ignore, don't update any of the lists, just set statusline } selectAndReveal(annotationPosition.getOffset(), annotationPosition.getLength()); if (nextAnnotation instanceof IJavaAnnotation && ((IJavaAnnotation)nextAnnotation).isProblem()) setStatusLineErrorMessage(((IJavaAnnotation)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 Annotation getNextAnnotation(int offset, int length, boolean forward, Position annotationPosition) { Annotation nextAnnotation= null; Position nextAnnotationPosition= null; Annotation containingAnnotation= null; Position containingAnnotationPosition= null; boolean currentAnnotation= false; IDocument document= getDocumentProvider().getDocument(getEditorInput()); int endOfDocument= document.getLength(); int distance= 0; IAnnotationAccess access= getAnnotationAccess(); IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput()); Iterator e= new JavaAnnotationIterator(model, true, true); while (e.hasNext()) { Annotation a= (Annotation) e.next(); Object type; if (a instanceof IJavaAnnotation) type= ((IJavaAnnotation)a).getAnnotationType(); else type= access.getType(a); 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(type)) { 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 instanceof IJavaAnnotation) && ((IJavaAnnotation)a).hasOverlay() || !isNavigationTarget) continue; Position p= model.getPosition(a); if (p == null) continue; 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); } }
43,999
Bug 43999 Filter to hide anonymous inner classes in Outline View
A new feature was added in 3.0 to show all the inner classes. However in some cases (for example when you are implementing a large number of event listeners) this makes the Outline view very difficult to use because it becomes very cluttered. Also, the word "Anonymous" is quite long and comes at the front so that typically the useful information (the class name) is scrolled out of view. Could the class name be used instead (e.g. ControlListener$1)?
resolved fixed
7cb2764
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-06T15:41:50Z
2003-10-01T14:53:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/IJavaHelpContextIds.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * Sebastian Davids <[email protected]> bug 38692 *******************************************************************************/ package org.eclipse.jdt.internal.ui; import org.eclipse.jdt.ui.JavaUI; /** * Help context ids for the Java UI. * <p> * This interface contains constants only; it is not intended to be implemented * or extended. * </p> * */ public interface IJavaHelpContextIds { public static final String PREFIX= JavaUI.ID_PLUGIN + '.'; // Actions public static final String GETTERSETTER_ACTION= PREFIX + "getter_setter_action_context"; //$NON-NLS-1$ public static final String ADD_METHODSTUB_ACTION= PREFIX + "add_methodstub_action_context"; //$NON-NLS-1$ public static final String ADD_UNIMPLEMENTED_METHODS_ACTION= PREFIX + "add_unimplemented_methods_action_context"; //$NON-NLS-1$ public static final String ADD_UNIMPLEMENTED_CONSTRUCTORS_ACTION= PREFIX + "add_unimplemented_constructors_action_context"; //$NON-NLS-1$ public static final String CREATE_NEW_CONSTRUCTOR_ACTION= PREFIX + "create_new_constructor_action_context"; //$NON-NLS-1$ public static final String SHOW_IN_PACKAGEVIEW_ACTION= PREFIX + "show_in_packageview_action_context"; //$NON-NLS-1$ public static final String SHOW_IN_HIERARCHYVIEW_ACTION= PREFIX + "show_in_hierarchyview_action_context"; //$NON-NLS-1$ public static final String FOCUS_ON_SELECTION_ACTION= PREFIX + "focus_on_selection_action"; //$NON-NLS-1$ public static final String FOCUS_ON_TYPE_ACTION= PREFIX + "focus_on_type_action"; //$NON-NLS-1$ public static final String TYPEHIERARCHY_HISTORY_ACTION= PREFIX + "typehierarchy_history_action"; //$NON-NLS-1$ public static final String FILTER_PUBLIC_ACTION= PREFIX + "filter_public_action"; //$NON-NLS-1$ public static final String FILTER_FIELDS_ACTION= PREFIX + "filter_fields_action"; //$NON-NLS-1$ public static final String FILTER_STATIC_ACTION= PREFIX + "filter_static_action"; //$NON-NLS-1$ public static final String SHOW_INHERITED_ACTION= PREFIX + "show_inherited_action"; //$NON-NLS-1$ public static final String SHOW_SUPERTYPES= PREFIX + "show_supertypes_action"; //$NON-NLS-1$ public static final String SHOW_SUBTYPES= PREFIX + "show_subtypes_action"; //$NON-NLS-1$ public static final String SHOW_HIERARCHY= PREFIX + "show_hierarchy_action"; //$NON-NLS-1$ public static final String ENABLE_METHODFILTER_ACTION= PREFIX + "enable_methodfilter_action"; //$NON-NLS-1$ public static final String ADD_IMPORT_ON_SELECTION_ACTION= PREFIX + "add_imports_on_selection_action_context"; //$NON-NLS-1$ public static final String ORGANIZE_IMPORTS_ACTION= PREFIX + "organize_imports_action_context"; //$NON-NLS-1$ public static final String ADD_TO_CLASSPATH_ACTION= PREFIX + "addjtoclasspath_action_context"; //$NON-NLS-1$ public static final String REMOVE_FROM_CLASSPATH_ACTION= PREFIX + "removefromclasspath_action_context"; //$NON-NLS-1$ public static final String TOGGLE_PRESENTATION_ACTION= PREFIX + "toggle_presentation_action_context"; //$NON-NLS-1$ public static final String TOGGLE_TEXTHOVER_ACTION= PREFIX + "toggle_texthover_action_context"; //$NON-NLS-1$ public static final String OPEN_CLASS_WIZARD_ACTION= PREFIX + "open_class_wizard_action"; //$NON-NLS-1$ public static final String OPEN_INTERFACE_WIZARD_ACTION= PREFIX + "open_interface_wizard_action"; //$NON-NLS-1$ public static final String SORT_MEMBERS_ACTION= PREFIX + "sort_members_action"; //$NON-NLS-1$ public static final String OPEN_PACKAGE_WIZARD_ACTION= PREFIX + "open_package_wizard_action"; //$NON-NLS-1$ public static final String OPEN_PROJECT_WIZARD_ACTION= PREFIX + "open_project_wizard_action"; //$NON-NLS-1$ public static final String OPEN_SNIPPET_WIZARD_ACTION= PREFIX + "open_snippet_wizard_action"; //$NON-NLS-1$ public static final String EDIT_WORKING_SET_ACTION= PREFIX + "edit_working_set_action"; //$NON-NLS-1$ public static final String CLEAR_WORKING_SET_ACTION= PREFIX + "clear_working_set_action"; //$NON-NLS-1$ public static final String GOTO_MARKER_ACTION= PREFIX + "goto_marker_action"; //$NON-NLS-1$ public static final String GOTO_PACKAGE_ACTION= PREFIX + "goto_package_action"; //$NON-NLS-1$ public static final String GOTO_TYPE_ACTION= PREFIX + "goto_type_action"; //$NON-NLS-1$ public static final String GOTO_MATCHING_BRACKET_ACTION= PREFIX + "goto_matching_bracket_action"; //$NON-NLS-1$ public static final String GOTO_NEXT_MEMBER_ACTION= PREFIX + "goto_next_member_action"; //$NON-NLS-1$ public static final String GOTO_PREVIOUS_MEMBER_ACTION= PREFIX + "goto_previous_member_action"; //$NON-NLS-1$ public static final String HISTORY_ACTION= PREFIX + "history_action"; //$NON-NLS-1$ public static final String HISTORY_LIST_ACTION= PREFIX + "history_list_action"; //$NON-NLS-1$ public static final String LEXICAL_SORTING_OUTLINE_ACTION= PREFIX + "lexical_sorting_outline_action"; //$NON-NLS-1$ public static final String LEXICAL_SORTING_BROWSING_ACTION= PREFIX + "lexical_sorting_browsing_action"; //$NON-NLS-1$ public static final String OPEN_JAVA_PERSPECTIVE_ACTION= PREFIX + "open_java_perspective_action"; //$NON-NLS-1$ public static final String ADD_DELEGATE_METHODS_ACTION= PREFIX + "add_delegate_methods_action"; //$NON-NLS-1$ public static final String OPEN_JAVA_BROWSING_PERSPECTIVE_ACTION= PREFIX + "open_java_browsing_perspective_action"; //$NON-NLS-1$ public static final String OPEN_PROJECT_ACTION= PREFIX + "open_project_action"; //$NON-NLS-1$ public static final String OPEN_TYPE_ACTION= PREFIX + "open_type_action"; //$NON-NLS-1$ public static final String OPEN_TYPE_IN_HIERARCHY_ACTION= PREFIX + "open_type_in_hierarchy_action"; //$NON-NLS-1$ public static final String ADD_JAVADOC_STUB_ACTION= PREFIX + "add_javadoc_stub_action"; //$NON-NLS-1$ public static final String ADD_TASK_ACTION= PREFIX + "add_task_action"; //$NON-NLS-1$ public static final String EXTERNALIZE_STRINGS_ACTION= PREFIX + "externalize_strings_action"; //$NON-NLS-1$ public static final String EXTRACT_METHOD_ACTION= PREFIX + "extract_method_action"; //$NON-NLS-1$ public static final String EXTRACT_TEMP_ACTION= PREFIX + "extract_temp_action"; //$NON-NLS-1$ public static final String PROMOTE_TEMP_TO_FIELD_ACTION= PREFIX + "promote_temp_to_field_action"; //$NON-NLS-1$ public static final String CONVERT_ANONYMOUS_TO_NESTED_ACTION= PREFIX + "convert_anonymous_to_nested_action"; //$NON-NLS-1$ public static final String EXTRACT_CONSTANT_ACTION= PREFIX + "extract_constant_action"; //$NON-NLS-1$ public static final String INTRODUCE_PARAMETER_ACTION= PREFIX + "introduce_parameter_action"; //$NON-NLS-1$ public static final String EXTRACT_INTERFACE_ACTION= PREFIX + "extract_interface_action"; //$NON-NLS-1$ public static final String MOVE_INNER_TO_TOP_ACTION= PREFIX + "move_inner_to_top_level_action"; //$NON-NLS-1$ public static final String USE_SUPERTYPE_ACTION= PREFIX + "use_supertype_action"; //$NON-NLS-1$ public static final String FIND_DECLARATIONS_IN_WORKSPACE_ACTION= PREFIX + "find_declarations_in_workspace_action"; //$NON-NLS-1$ public static final String FIND_DECLARATIONS_IN_PROJECT_ACTION= PREFIX + "find_declarations_in_project_action"; //$NON-NLS-1$ public static final String FIND_DECLARATIONS_IN_HIERARCHY_ACTION= PREFIX + "find_declarations_in_hierarchy_action"; //$NON-NLS-1$ public static final String FIND_DECLARATIONS_IN_WORKING_SET_ACTION= PREFIX + "find_declarations_in_working_set_action"; //$NON-NLS-1$ public static final String FIND_IMPLEMENTORS_IN_WORKSPACE_ACTION= PREFIX + "find_implementors_in_workspace_action"; //$NON-NLS-1$ public static final String FIND_IMPLEMENTORS_IN_PROJECT_ACTION= PREFIX + "find_implementors_in_project_action"; //$NON-NLS-1$ public static final String FIND_IMPLEMENTORS_IN_WORKING_SET_ACTION= PREFIX + "find_implementors_in_working_set_action"; //$NON-NLS-1$ public static final String FIND_REFERENCES_IN_WORKSPACE_ACTION= PREFIX + "find_references_in_workspace_action"; //$NON-NLS-1$ public static final String FIND_REFERENCES_IN_PROJECT_ACTION= PREFIX + "find_references_in_project_action"; //$NON-NLS-1$ public static final String FIND_REFERENCES_IN_HIERARCHY_ACTION= PREFIX + "find_references_in_hierarchy_action"; //$NON-NLS-1$ public static final String FIND_REFERENCES_IN_WORKING_SET_ACTION= PREFIX + "find_references_in_working_set_action"; //$NON-NLS-1$ public static final String FIND_READ_REFERENCES_IN_WORKSPACE_ACTION= PREFIX + "find_read_references_in_workspace_action"; //$NON-NLS-1$ public static final String FIND_READ_REFERENCES_IN_PROJECT_ACTION= PREFIX + "find_read_references_in_project_action"; //$NON-NLS-1$ public static final String FIND_READ_REFERENCES_IN_HIERARCHY_ACTION= PREFIX + "find_read_references_in_hierarchy_action"; //$NON-NLS-1$ public static final String FIND_READ_REFERENCES_IN_WORKING_SET_ACTION= PREFIX + "find_read_references_in_working_set_action"; //$NON-NLS-1$ public static final String FIND_WRITE_REFERENCES_IN_HIERARCHY_ACTION= PREFIX + "find_write_references_in_hierarchy_action"; //$NON-NLS-1$ public static final String FIND_WRITE_REFERENCES_IN_PROJECT_ACTION= PREFIX + "find_write_references_in_project_action"; //$NON-NLS-1$ public static final String FIND_WRITE_REFERENCES_IN_WORKING_SET_ACTION= PREFIX + "find_write_references_in_working_set_action"; //$NON-NLS-1$ public static final String FIND_WRITE_REFERENCES_IN_WORKSPACE_ACTION= PREFIX + "find_write_references_in_workspace_action"; //$NON-NLS-1$ public static final String FIND_OCCURRENCES_IN_FILE_ACTION= PREFIX + "find_occurrences_in_file_action"; //$NON-NLS-1$ public static final String WORKING_SET_FIND_ACTION= PREFIX + "working_set_find_action"; //$NON-NLS-1$ public static final String FIND_STRINGS_TO_EXTERNALIZE_ACTION= PREFIX + "find_strings_to_externalize_action"; //$NON-NLS-1$ public static final String INLINE_ACTION= PREFIX + "inline_action"; //$NON-NLS-1$ public static final String MODIFY_PARAMETERS_ACTION= PREFIX + "modify_parameters_action"; //$NON-NLS-1$ public static final String MOVE_ACTION= PREFIX + "move_action"; //$NON-NLS-1$ public static final String OPEN_ACTION= PREFIX + "open_action"; //$NON-NLS-1$ public static final String OPEN_EXTERNAL_JAVADOC_ACTION= PREFIX + "open_external_javadoc_action"; //$NON-NLS-1$ public static final String OPEN_INPUT_ACTION= PREFIX + "open_input_action"; //$NON-NLS-1$ public static final String OPEN_SUPER_IMPLEMENTATION_ACTION= PREFIX + "open_super_implementation_action"; //$NON-NLS-1$ public static final String PULL_UP_ACTION= PREFIX + "pull_up_action"; //$NON-NLS-1$ public static final String PUSH_DOWN_ACTION= PREFIX + "push_down_action"; //$NON-NLS-1$ public static final String REFRESH_ACTION= PREFIX + "refresh_action"; //$NON-NLS-1$ public static final String RENAME_ACTION= PREFIX + "rename_action"; //$NON-NLS-1$ public static final String SELF_ENCAPSULATE_ACTION= PREFIX + "self_encapsulate_action"; //$NON-NLS-1$ public static final String SHOW_IN_NAVIGATOR_VIEW_ACTION= PREFIX + "show_in_navigator_action"; //$NON-NLS-1$ public static final String SURROUND_WITH_TRY_CATCH_ACTION= PREFIX + "surround_with_try_catch_action"; //$NON-NLS-1$ public static final String OPEN_RESOURCE_ACTION= PREFIX + "open_resource_action"; //$NON-NLS-1$ public static final String SELECT_WORKING_SET_ACTION= PREFIX + "select_working_set_action"; //$NON-NLS-1$ public static final String STRUCTURED_SELECTION_HISTORY_ACTION= PREFIX + "structured_selection_history_action"; //$NON-NLS-1$ public static final String STRUCTURED_SELECT_ENCLOSING_ACTION= PREFIX + "structured_select_enclosing_action"; //$NON-NLS-1$ public static final String STRUCTURED_SELECT_NEXT_ACTION= PREFIX + "structured_select_next_action"; //$NON-NLS-1$ public static final String STRUCTURED_SELECT_PREVIOUS_ACTION= PREFIX + "structured_select_previous_action"; //$NON-NLS-1$ public static final String TOGGLE_ORIENTATION_ACTION= PREFIX + "toggle_orientations_action"; //$NON-NLS-1$ public static final String CUT_ACTION= PREFIX + "cut_action"; //$NON-NLS-1$ public static final String COPY_ACTION= PREFIX + "copy_action"; //$NON-NLS-1$ public static final String PASTE_ACTION= PREFIX + "paste_action"; //$NON-NLS-1$ public static final String DELETE_ACTION= PREFIX + "delete_action"; //$NON-NLS-1$ public static final String SELECT_ALL_ACTION= PREFIX + "select_all_action"; //$NON-NLS-1$ public static final String OPEN_TYPE_HIERARCHY_ACTION= PREFIX + "open_type_hierarchy_action"; //$NON-NLS-1$ public static final String COLLAPSE_ALL_ACTION= PREFIX + "open_type_hierarchy_action"; //$NON-NLS-1$ public static final String GOTO_RESOURCE_ACTION= PREFIX + "goto_resource_action"; //$NON-NLS-1$ public static final String LINK_EDITOR_ACTION= PREFIX + "link_editor_action"; //$NON-NLS-1$ public static final String GO_INTO_TOP_LEVEL_TYPE_ACTION= PREFIX + "go_into_top_level_type_action"; //$NON-NLS-1$ public static final String COMPARE_WITH_HISTORY_ACTION= PREFIX + "compare_with_history_action"; //$NON-NLS-1$ public static final String REPLACE_WITH_PREVIOUS_FROM_HISTORY_ACTION= PREFIX + "replace_with_previous_from_history_action"; //$NON-NLS-1$ public static final String REPLACE_WITH_HISTORY_ACTION= PREFIX + "replace_with_history_action"; //$NON-NLS-1$ public static final String ADD_FROM_HISTORY_ACTION= PREFIX + "add_from_history_action"; //$NON-NLS-1$ public static final String LAYOUT_FLAT_ACTION= PREFIX + "layout_flat_action"; //$NON-NLS-1$ public static final String LAYOUT_HIERARCHICAL_ACTION= PREFIX + "layout_hierarchical_action"; //$NON-NLS-1$ public static final String NEXT_CHANGE_ACTION= PREFIX + "next_change_action"; //$NON-NLS-1$ public static final String PREVIOUS_CHANGE_ACTION= PREFIX + "previous_change_action"; //$NON-NLS-1$ public static final String NEXT_PROBLEM_ACTION= PREFIX + "next_problem_action"; //$NON-NLS-1$ public static final String PREVIOUS_PROBLEM_ACTION= PREFIX + "previous_problem_action"; //$NON-NLS-1$ public static final String JAVA_SELECT_MARKER_RULER_ACTION= PREFIX + "java_select_marker_ruler_action"; //$NON-NLS-1$ public static final String GOTO_NEXT_ERROR_ACTION= PREFIX + "goto_next_error_action"; //$NON-NLS-1$ public static final String GOTO_PREVIOUS_ERROR_ACTION= PREFIX + "goto_previous_error_action"; //$NON-NLS-1$ public static final String SHOW_QUALIFIED_NAMES_ACTION= PREFIX + "show_qualified_names_action"; //$NON-NLS-1$ public static final String SORT_BY_DEFINING_TYPE_ACTION= PREFIX + "sort_by_defining_type_action"; //$NON-NLS-1$ public static final String FORMAT_ACTION= PREFIX + "format_action"; //$NON-NLS-1$ public static final String COMMENT_ACTION= PREFIX + "comment_action"; //$NON-NLS-1$ public static final String UNCOMMENT_ACTION= PREFIX + "uncomment_action"; //$NON-NLS-1$ public static final String ADD_BLOCK_COMMENT_ACTION= PREFIX + "add_block_comment_action"; //$NON-NLS-1$ public static final String REMOVE_BLOCK_COMMENT_ACTION= PREFIX + "remove_block_comment_action"; //$NON-NLS-1$ public static final String QUICK_FIX_ACTION= PREFIX + "quick_fix_action"; //$NON-NLS-1$ public static final String CONTENT_ASSIST_ACTION= PREFIX + "content_assist_action"; //$NON-NLS-1$ public static final String PARAMETER_HINTS_ACTION= PREFIX + "parameter_hints_action"; //$NON-NLS-1$ public static final String SHOW_JAVADOC_ACTION= PREFIX + "show_javadoc_action"; //$NON-NLS-1$ public static final String SHOW_OUTLINE_ACTION= PREFIX + "show_outline_action"; //$NON-NLS-1$ public static final String OPEN_STRUCTURE_ACTION= PREFIX + "open_structure_action"; //$NON-NLS-1$ public static final String OPEN_HIERARCHY_ACTION= PREFIX + "open_hierarchy_action"; //$NON-NLS-1$ public static final String TOGGLE_SMART_TYPING_ACTION= PREFIX + "toggle_smart_typing_action"; //$NON-NLS-1$ public static final String INDENT_ACTION= PREFIX + "indent_action"; //$NON-NLS-1$ // Dialogs public static final String MAINTYPE_SELECTION_DIALOG= PREFIX + "maintype_selection_dialog_context"; //$NON-NLS-1$ public static final String OPEN_TYPE_DIALOG= PREFIX + "open_type_dialog_context"; //$NON-NLS-1$ public static final String SOURCE_ATTACHMENT_DIALOG= PREFIX + "source_attachment_dialog_context"; //$NON-NLS-1$ public static final String LIBRARIES_WORKBOOK_PAGE_ADVANCED_DIALOG= PREFIX + "advanced_dialog_context"; //$NON-NLS-1$ public static final String CONFIRM_SAVE_MODIFIED_RESOURCES_DIALOG= PREFIX + "confirm_save_modified_resources_dialog_context"; //$NON-NLS-1$ public static final String NEW_VARIABLE_ENTRY_DIALOG= PREFIX + "new_variable_dialog_context"; //$NON-NLS-1$ public static final String NONNLS_DIALOG= PREFIX + "nonnls_dialog_context"; //$NON-NLS-1$ public static final String MULTI_MAIN_TYPE_SELECTION_DIALOG= PREFIX + "multi_main_type_selection_dialog_context"; //$NON-NLS-1$ public static final String MULTI_TYPE_SELECTION_DIALOG= PREFIX + "multi_type_selection_dialog_context"; //$NON-NLS-1$ public static final String SUPER_INTERFACE_SELECTION_DIALOG= PREFIX + "super_interface_selection_dialog_context"; //$NON-NLS-1$ public static final String OVERRIDE_TREE_SELECTION_DIALOG= PREFIX + "override_tree_selection_dialog_context"; //$NON-NLS-1$ public static final String MOVE_DESTINATION_DIALOG= PREFIX + "move_destination_dialog_context"; //$NON-NLS-1$ public static final String CHOOSE_VARIABLE_DIALOG= PREFIX + "choose_variable_dialog_context"; //$NON-NLS-1$ public static final String EDIT_TEMPLATE_DIALOG= PREFIX + "edit_template_dialog_context"; //$NON-NLS-1$ public static final String HISTORY_LIST_DIALOG= PREFIX + "history_list_dialog_context"; //$NON-NLS-1$ public static final String IMPORT_ORGANIZE_INPUT_DIALOG= PREFIX + "import_organize_input_dialog_context"; //$NON-NLS-1$ public static final String TODO_TASK_INPUT_DIALOG= PREFIX + "todo_task_input_dialog_context"; //$NON-NLS-1$ public static final String JAVADOC_PROPERTY_DIALOG= PREFIX + "javadoc_property_dialog_context"; //$NON-NLS-1$ public static final String NEW_CONTAINER_DIALOG= PREFIX + "new_container_dialog_context"; //$NON-NLS-1$ public static final String EXCLUSION_PATTERN_DIALOG= PREFIX + "exclusion_pattern_dialog_context"; //$NON-NLS-1$ public static final String OUTPUT_LOCATION_DIALOG= PREFIX + "output_location_dialog_context"; //$NON-NLS-1$ public static final String VARIABLE_CREATION_DIALOG= PREFIX + "variable_creation_dialog_context"; //$NON-NLS-1$ public static final String JAVA_SEARCH_PAGE= PREFIX + "java_search_page_context"; //$NON-NLS-1$ public static final String NLS_SEARCH_PAGE= PREFIX + "nls_search_page_context"; //$NON-NLS-1$ public static final String JAVA_EDITOR= PREFIX + "java_editor_context"; //$NON-NLS-1$ public static final String GOTO_RESOURCE_DIALOG= PREFIX + "goto_resource_dialog"; //$NON-NLS-1$ public static final String COMPARE_DIALOG= PREFIX + "compare_dialog_context"; //$NON-NLS-1$ public static final String ADD_ELEMENT_FROM_HISTORY_DIALOG= PREFIX + "add_element_from_history_dialog_context"; //$NON-NLS-1$ public static final String COMPARE_ELEMENT_WITH_HISTORY_DIALOG= PREFIX + "compare_element_with_history_dialog_context"; //$NON-NLS-1$ public static final String REPLACE_ELEMENT_WITH_HISTORY_DIALOG= PREFIX + "replace_element_with_history_dialog_context"; //$NON-NLS-1$ // view parts public static final String TYPE_HIERARCHY_VIEW= PREFIX + "type_hierarchy_view_context"; //$NON-NLS-1$ public static final String PACKAGES_VIEW= PREFIX + "package_view_context"; //$NON-NLS-1$ public static final String PROJECTS_VIEW= PREFIX + "projects_view_context"; //$NON-NLS-1$ public static final String PACKAGES_BROWSING_VIEW= PREFIX + "packages_browsing_view_context"; //$NON-NLS-1$ public static final String TYPES_VIEW= PREFIX + "types_view_context"; //$NON-NLS-1$ public static final String MEMBERS_VIEW= PREFIX + "members_view_context"; //$NON-NLS-1$ // Preference/Property pages public static final String APPEARANCE_PREFERENCE_PAGE= PREFIX + "appearance_preference_page_context"; //$NON-NLS-1$ public static final String SORT_ORDER_PREFERENCE_PAGE= PREFIX + "sort_order_preference_page_context"; //$NON-NLS-1$ public static final String BUILD_PATH_PROPERTY_PAGE= PREFIX + "build_path_property_page_context"; //$NON-NLS-1$ public static final String CP_VARIABLES_PREFERENCE_PAGE= PREFIX + "cp_variables_preference_page_context"; //$NON-NLS-1$ public static final String CODEFORMATTER_PREFERENCE_PAGE= PREFIX + "codeformatter_preference_page_context"; //$NON-NLS-1$ public static final String SOURCE_ATTACHMENT_PROPERTY_PAGE= PREFIX + "source_attachment_property_page_context"; //$NON-NLS-1$ public static final String COMPILER_PROPERTY_PAGE= PREFIX + "compiler_property_page_context"; //$NON-NLS-1$ public static final String TODOTASK_PROPERTY_PAGE= PREFIX + "tasktags_property_page_context"; //$NON-NLS-1$ public static final String CODE_MANIPULATION_PREFERENCE_PAGE= PREFIX + "code_manipulation_preference_context"; //$NON-NLS-1$ public static final String ORGANIZE_IMPORTS_PREFERENCE_PAGE= PREFIX + "organizeimports_preference_page_context"; //$NON-NLS-1$ public static final String JAVA_BASE_PREFERENCE_PAGE= PREFIX + "java_base_preference_page_context"; //$NON-NLS-1$ public static final String REFACTORING_PREFERENCE_PAGE= PREFIX + "refactoring_preference_page_context"; //$NON-NLS-1$ public static final String JAVA_EDITOR_PREFERENCE_PAGE= PREFIX + "java_editor_preference_page_context"; //$NON-NLS-1$ public static final String COMPILER_PREFERENCE_PAGE= PREFIX + "compiler_preference_page_context"; //$NON-NLS-1$ public static final String TODOTASK_PREFERENCE_PAGE= PREFIX + "tasktags_preference_page_context"; //$NON-NLS-1$ public static final String TEMPLATE_PREFERENCE_PAGE= PREFIX + "template_preference_page_context"; //$NON-NLS-1$ public static final String JAVADOC_PREFERENCE_PAGE= PREFIX + "javadoc_preference_page_context"; //$NON-NLS-1$ public static final String NEW_JAVA_PROJECT_PREFERENCE_PAGE= PREFIX + "new_java_project_preference_page_context"; //$NON-NLS-1$ public static final String JAVADOC_CONFIGURATION_PROPERTY_PAGE= PREFIX + "new_java_project_preference_page_context"; //$NON-NLS-1$ public static final String JAVA_ELEMENT_INFO_PAGE= PREFIX + "java_element_info_page_context"; //$NON-NLS-1$ // Wizard pages public static final String NEW_JAVAPROJECT_WIZARD_PAGE= PREFIX + "new_javaproject_wizard_page_context"; //$NON-NLS-1$ public static final String NEW_SNIPPET_WIZARD_PAGE= PREFIX + "new_snippet_wizard_page_context"; //$NON-NLS-1$ public static final String NEW_PACKAGE_WIZARD_PAGE= PREFIX + "new_package_wizard_page_context"; //$NON-NLS-1$ public static final String NEW_CLASS_WIZARD_PAGE= PREFIX + "new_class_wizard_page_context"; //$NON-NLS-1$ public static final String NEW_INTERFACE_WIZARD_PAGE= PREFIX + "new_interface_wizard_page_context"; //$NON-NLS-1$ public static final String NEW_PACKAGEROOT_WIZARD_PAGE= PREFIX + "new_packageroot_wizard_page_context"; //$NON-NLS-1$ public static final String JARPACKAGER_WIZARD_PAGE= PREFIX + "jar_packager_wizard_page_context"; //$NON-NLS-1$ public static final String JARMANIFEST_WIZARD_PAGE= PREFIX + "jar_manifest_wizard_page_context"; //$NON-NLS-1$ public static final String JAROPTIONS_WIZARD_PAGE= PREFIX + "jar_options_wizard_page_context"; //$NON-NLS-1$ public static final String JAVA_WORKING_SET_PAGE= PREFIX + "java_working_set_page_context"; //$NON-NLS-1$ public static final String CLASSPATH_CONTAINER_DEFAULT_PAGE= PREFIX + "classpath_container_default_page_context"; //$NON-NLS-1$ public static final String JAVADOC_STANDARD_PAGE= PREFIX + "javadoc_standard_page_context"; //$NON-NLS-1$ public static final String JAVADOC_SPECIFICS_PAGE= PREFIX + "javadoc_specifics_page_context"; //$NON-NLS-1$ public static final String JAVADOC_TREE_PAGE= PREFIX + "javadoc_tree_page_context"; //$NON-NLS-1$ public static final String JAVADOC_COMMAND_PAGE= PREFIX + "javadoc_command_page_context"; //$NON-NLS-1$ // Same help for all refactoring error pages. Indidivual help can // be provided per a single refactoring status. public static final String REFACTORING_ERROR_WIZARD_PAGE= PREFIX + "refactoring_error_wizard_page_context"; //$NON-NLS-1$ // same help for all refactoring preview pages public static final String REFACTORING_PREVIEW_WIZARD_PAGE= PREFIX + "refactoring_preview_wizard_page_context"; //$NON-NLS-1$ public static final String RENAME_PARAMS_WIZARD_PAGE= PREFIX + "rename_params_wizard_page"; //$NON-NLS-1$ public static final String EXTERNALIZE_WIZARD_KEYVALUE_PAGE= PREFIX + "externalize_wizard_keyvalue_page_context"; //$NON-NLS-1$ public static final String EXTERNALIZE_WIZARD_PROPERTIES_FILE_PAGE= PREFIX + "externalize_wizard_properties_file_page_context"; //$NON-NLS-1$ public static final String EXTRACT_INTERFACE_WIZARD_PAGE= PREFIX + "extract_interface_temp_page_context"; //$NON-NLS-1$ public static final String EXTRACT_METHOD_WIZARD_PAGE= PREFIX + "extract_method_wizard_page_context"; //$NON-NLS-1$ public static final String EXTRACT_TEMP_WIZARD_PAGE= PREFIX + "extract_temp_page_context"; //$NON-NLS-1$ public static final String EXTRACT_CONSTANT_WIZARD_PAGE= PREFIX + "extract_constant_page_context"; //$NON-NLS-1$ public static final String INTRODUCE_PARAMETER_WIZARD_PAGE= PREFIX + "introduce_parameter_page_context"; //$NON-NLS-1$ public static final String PROMOTE_TEMP_TO_FIELD_WIZARD_PAGE= PREFIX + "promote_temp_to_field_page_context"; //$NON-NLS-1$ public static final String CONVERT_ANONYMOUS_TO_NESTED_WIZARD_PAGE= PREFIX + "convert_anonymous_to_nested_page_context"; //$NON-NLS-1$ public static final String MODIFY_PARAMETERS_WIZARD_PAGE= PREFIX + "modify_parameters_wizard_page_context"; //$NON-NLS-1$ public static final String MOVE_MEMBERS_WIZARD_PAGE= PREFIX + "move_members_wizard_page_context"; //$NON-NLS-1$ public static final String MOVE_INNER_TO_TOP_WIZARD_PAGE= PREFIX + "move_inner_to_top_wizard_page_context"; //$NON-NLS-1$ public static final String PULL_UP_WIZARD_PAGE= PREFIX + "pull_up_wizard_page_context"; //$NON-NLS-1$ public static final String PUSH_DOWN_WIZARD_PAGE= PREFIX + "push_down_wizard_page_context"; //$NON-NLS-1$ public static final String RENAME_PACKAGE_WIZARD_PAGE= PREFIX + "rename_package_wizard_page_context"; //$NON-NLS-1$ public static final String RENAME_TEMP_WIZARD_PAGE= PREFIX + "rename_local_variable_wizard_page_context"; //$NON-NLS-1$ public static final String RENAME_CU_WIZARD_PAGE= PREFIX + "rename_cu_wizard_page_context"; //$NON-NLS-1$ public static final String RENAME_METHOD_WIZARD_PAGE= PREFIX + "rename_method_wizard_page_context"; //$NON-NLS-1$ public static final String RENAME_TYPE_WIZARD_PAGE= PREFIX + "rename_type_wizard_page_context"; //$NON-NLS-1$ public static final String RENAME_FIELD_WIZARD_PAGE= PREFIX + "rename_field_wizard_page_context"; //$NON-NLS-1$ public static final String RENAME_RESOURCE_WIZARD_PAGE= PREFIX + "rename_resource_wizard_page_context"; //$NON-NLS-1$ public static final String RENAME_JAVA_PROJECT_WIZARD_PAGE= PREFIX + "rename_java_project_wizard_page_context"; //$NON-NLS-1$ public static final String RENAME_SOURCE_FOLDER_WIZARD_PAGE= PREFIX + "rename_source_folder_wizard_page_context"; //$NON-NLS-1$ public static final String SEF_WIZARD_PAGE= PREFIX + "self_encapsulate_field_wizard_page_context"; //$NON-NLS-1$ public static final String USE_SUPERTYPE_WIZARD_PAGE= PREFIX + "use_supertype_wizard_page_context"; //$NON-NLS-1$ public static final String INLINE_METHOD_WIZARD_PAGE= PREFIX + "inline_method_wizard_page_context"; //$NON-NLS-1$ public static final String INLINE_CONSTANT_WIZARD_PAGE= PREFIX + "inline_constant_wizard_page_context"; //$NON-NLS-1$ // reused ui-blocks public static final String BUILD_PATH_BLOCK= PREFIX + "build_paths_context"; //$NON-NLS-1$ public static final String SOURCE_ATTACHMENT_BLOCK= PREFIX + "source_attachment_context"; //$NON-NLS-1$ // Custom Filters public static final String CUSTOM_FILTERS_DIALOG= PREFIX + "open_custom_filters_dialog_context"; //$NON-NLS-1$ // Call Hierarchy public static final String CALL_HIERARCHY_VIEW= PREFIX + "call_hierarchy_view_context"; //$NON-NLS-1$ public static final String CALL_HIERARCHY_FILTERS_DIALOG= PREFIX + "call_hierarchy_filters_dialog_context"; //$NON-NLS-1$ public static final String CALL_HIERARCHY_FOCUS_ON_SELECTION_ACTION= PREFIX + "call_hierarchy_focus_on_selection_action_context"; //$NON-NLS-1$ public static final String CALL_HIERARCHY_HISTORY_ACTION= PREFIX + "call_hierarchy_history_action_context"; //$NON-NLS-1$ public static final String CALL_HIERARCHY_HISTORY_DROP_DOWN_ACTION= PREFIX + "call_hierarchy_history_drop_down_action_context"; //$NON-NLS-1$ public static final String CALL_HIERARCHY_REFRESH_ACTION= PREFIX + "call_hierarchy_refresh_action_context"; //$NON-NLS-1$ public static final String CALL_HIERARCHY_SEARCH_SCOPE_ACTION= PREFIX + "call_hierarchy_search_scope_action_context"; //$NON-NLS-1$ public static final String CALL_HIERARCHY_TOGGLE_CALL_MODE_ACTION= PREFIX + "call_hierarchy_toggle_call_mode_action_context"; //$NON-NLS-1$ public static final String CALL_HIERARCHY_TOGGLE_JAVA_LABEL_FORMAT_ACTION= PREFIX + "call_hierarchy_toggle_java_label_format_action_context"; //$NON-NLS-1$ public static final String CALL_HIERARCHY_TOGGLE_ORIENTATION_ACTION= PREFIX + "call_hierarchy_toggle_call_mode_action_context"; //$NON-NLS-1$ public static final String CALL_HIERARCHY_COPY_ACTION= PREFIX + "call_hierarchy_copy_action_context"; //$NON-NLS-1$ public static final String CALL_HIERARCHY_TOGGLE_IMPLEMENTORS_ACTION= PREFIX + "call_hierarchy_toggle_implementors_action_context"; //$NON-NLS-1$ public static final String CALL_HIERARCHY_OPEN_ACTION= PREFIX + "call_hierarchy_open_action_context"; //$NON-NLS-1$ }
43,999
Bug 43999 Filter to hide anonymous inner classes in Outline View
A new feature was added in 3.0 to show all the inner classes. However in some cases (for example when you are implementing a large number of event listeners) this makes the Outline view very difficult to use because it becomes very cluttered. Also, the word "Anonymous" is quite long and comes at the front so that typically the useful information (the class name) is scrolled out of view. Could the class name be used instead (e.g. ControlListener$1)?
resolved fixed
7cb2764
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-06T15:41:50Z
2003-10-01T14:53:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/viewsupport/MemberFilter.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.viewsupport; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.jdt.core.Flags; import org.eclipse.jdt.core.IField; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; /** * Filter for the methods viewer. * Changing a filter property does not trigger a refiltering of the viewer */ public class MemberFilter extends ViewerFilter { public static final int FILTER_NONPUBLIC= 1; public static final int FILTER_STATIC= 2; public static final int FILTER_FIELDS= 4; private int fFilterProperties; /** * Modifies filter and add a property to filter for */ public final void addFilter(int filter) { fFilterProperties |= filter; } /** * Modifies filter and remove a property to filter for */ public final void removeFilter(int filter) { fFilterProperties &= (-1 ^ filter); } /** * Tests if a property is filtered */ public final boolean hasFilter(int filter) { return (fFilterProperties & filter) != 0; } /* * @see ViewerFilter@isFilterProperty */ public boolean isFilterProperty(Object element, Object property) { return false; } /* * @see ViewerFilter@select */ public boolean select(Viewer viewer, Object parentElement, Object element) { try { if (hasFilter(FILTER_FIELDS) && element instanceof IField) { return false; } if (element instanceof IMember) { IMember member= (IMember)element; if (member.getElementName().startsWith("<")) { // filter out <clinit> //$NON-NLS-1$ return false; } int flags= member.getFlags(); if (hasFilter(FILTER_STATIC) && (Flags.isStatic(flags) || isFieldInInterface(member)) && member.getElementType() != IJavaElement.TYPE) { return false; } if (hasFilter(FILTER_NONPUBLIC) && !Flags.isPublic(flags) && !isMemberInInterface(member) && !isTopLevelType(member)) { return false; } } } catch (JavaModelException e) { // ignore } return true; } private boolean isMemberInInterface(IMember member) throws JavaModelException { IType parent= member.getDeclaringType(); return parent != null && parent.isInterface(); } private boolean isFieldInInterface(IMember member) throws JavaModelException { return (member.getElementType() == IJavaElement.FIELD) && member.getDeclaringType().isInterface(); } private boolean isTopLevelType(IMember member) throws JavaModelException { IType parent= member.getDeclaringType(); return parent == null; } }
43,999
Bug 43999 Filter to hide anonymous inner classes in Outline View
A new feature was added in 3.0 to show all the inner classes. However in some cases (for example when you are implementing a large number of event listeners) this makes the Outline view very difficult to use because it becomes very cluttered. Also, the word "Anonymous" is quite long and comes at the front so that typically the useful information (the class name) is scrolled out of view. Could the class name be used instead (e.g. ControlListener$1)?
resolved fixed
7cb2764
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-06T15:41:50Z
2003-10-01T14:53:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/MemberFilterActionGroup.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 org.eclipse.swt.custom.BusyIndicator; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.util.Assert; import org.eclipse.jface.viewers.StructuredViewer; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IMemento; import org.eclipse.ui.actions.ActionGroup; 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.ActionMessages; import org.eclipse.jdt.internal.ui.viewsupport.MemberFilter; import org.eclipse.jdt.internal.ui.viewsupport.MemberFilterAction; /** * Action Group that contributes filter buttons for a view parts showing * methods and fields. Contributed filters are: hide fields, hide static * members and hide non-public members. * <p> * The action group installs a filter on a structured viewer. The filter is connected * to the actions installed in the view part's toolbar menu and is updated when the * state of the buttons changes. * * <p> * This class may be instantiated; it is not intended to be subclassed. * </p> * * @since 2.0 */ public class MemberFilterActionGroup extends ActionGroup { public static final int FILTER_NONPUBLIC= MemberFilter.FILTER_NONPUBLIC; public static final int FILTER_STATIC= MemberFilter.FILTER_STATIC; public static final int FILTER_FIELDS= MemberFilter.FILTER_FIELDS; private static final String TAG_HIDEFIELDS= "hidefields"; //$NON-NLS-1$ private static final String TAG_HIDESTATIC= "hidestatic"; //$NON-NLS-1$ private static final String TAG_HIDENONPUBLIC= "hidenonpublic"; //$NON-NLS-1$ private MemberFilterAction[] fFilterActions; private MemberFilter fFilter; private StructuredViewer fViewer; private String fViewerId; private boolean fInViewMenu; /** * Creates a new <code>MemberFilterActionGroup</code>. * * @param viewer the viewer to be filtered * @param viewerId a unique id of the viewer. Used as a key to to store * the last used filter settings in the preference store */ public MemberFilterActionGroup(StructuredViewer viewer, String viewerId) { this(viewer, viewerId, false); } /** * Creates a new <code>MemberFilterActionGroup</code>. * * @param viewer the viewer to be filtered * @param viewerId a unique id of the viewer. Used as a key to to store * the last used filter settings in the preference store * @param inViewMenu if <code>true</code> the actions are added to the view * menu. If <code>false</code> they are added to the toobar. * * @since 2.1 */ public MemberFilterActionGroup(StructuredViewer viewer, String viewerId, boolean inViewMenu) { fViewer= viewer; fViewerId= viewerId; fInViewMenu= inViewMenu; // get initial values IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); boolean doHideFields= store.getBoolean(getPreferenceKey(FILTER_FIELDS)); boolean doHideStatic= store.getBoolean(getPreferenceKey(FILTER_STATIC)); boolean doHidePublic= store.getBoolean(getPreferenceKey(FILTER_NONPUBLIC)); fFilter= new MemberFilter(); if (doHideFields) fFilter.addFilter(FILTER_FIELDS); if (doHideStatic) fFilter.addFilter(FILTER_STATIC); if (doHidePublic) fFilter.addFilter(FILTER_NONPUBLIC); // fields String title= ActionMessages.getString("MemberFilterActionGroup.hide_fields.label"); //$NON-NLS-1$ String helpContext= IJavaHelpContextIds.FILTER_FIELDS_ACTION; MemberFilterAction hideFields= new MemberFilterAction(this, title, FILTER_FIELDS, helpContext, doHideFields); hideFields.setDescription(ActionMessages.getString("MemberFilterActionGroup.hide_fields.description")); //$NON-NLS-1$ hideFields.setToolTipText(ActionMessages.getString("MemberFilterActionGroup.hide_fields.tooltip")); //$NON-NLS-1$ JavaPluginImages.setLocalImageDescriptors(hideFields, "fields_co.gif"); //$NON-NLS-1$ // static title= ActionMessages.getString("MemberFilterActionGroup.hide_static.label"); //$NON-NLS-1$ helpContext= IJavaHelpContextIds.FILTER_STATIC_ACTION; MemberFilterAction hideStatic= new MemberFilterAction(this, title, FILTER_STATIC, helpContext, doHideStatic); hideStatic.setDescription(ActionMessages.getString("MemberFilterActionGroup.hide_static.description")); //$NON-NLS-1$ hideStatic.setToolTipText(ActionMessages.getString("MemberFilterActionGroup.hide_static.tooltip")); //$NON-NLS-1$ JavaPluginImages.setLocalImageDescriptors(hideStatic, "static_co.gif"); //$NON-NLS-1$ // non-public title= ActionMessages.getString("MemberFilterActionGroup.hide_nonpublic.label"); //$NON-NLS-1$ helpContext= IJavaHelpContextIds.FILTER_PUBLIC_ACTION; MemberFilterAction hideNonPublic= new MemberFilterAction(this, title, FILTER_NONPUBLIC, helpContext, doHidePublic); hideNonPublic.setDescription(ActionMessages.getString("MemberFilterActionGroup.hide_nonpublic.description")); //$NON-NLS-1$ hideNonPublic.setToolTipText(ActionMessages.getString("MemberFilterActionGroup.hide_nonpublic.tooltip")); //$NON-NLS-1$ JavaPluginImages.setLocalImageDescriptors(hideNonPublic, "public_co.gif"); //$NON-NLS-1$ // order corresponds to order in toolbar fFilterActions= new MemberFilterAction[] { hideFields, hideStatic, hideNonPublic }; fViewer.addFilter(fFilter); } private String getPreferenceKey(int filterProperty) { return "MemberFilterActionGroup." + fViewerId + '.' + String.valueOf(filterProperty); //$NON-NLS-1$ } /** * Sets the member filters. * * @param filterProperty the filter to be manipulated. Valid values are <code>FILTER_FIELDS</code>, * <code>FILTER_PUBLIC</code>, and <code>FILTER_PRIVATE</code> as defined by this action * group * @param set if <code>true</code> the given filter is installed. If <code>false</code> the * given filter is removed * . */ public void setMemberFilter(int filterProperty, boolean set) { setMemberFilters(new int[] {filterProperty}, new boolean[] {set}, true); } private void setMemberFilters(int[] propertyKeys, boolean[] propertyValues, boolean refresh) { if (propertyKeys.length == 0) return; Assert.isTrue(propertyKeys.length == propertyValues.length); for (int i= 0; i < propertyKeys.length; i++) { int filterProperty= propertyKeys[i]; boolean set= propertyValues[i]; if (set) { fFilter.addFilter(filterProperty); } else { fFilter.removeFilter(filterProperty); } IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); for (int j= 0; j < fFilterActions.length; j++) { int currProperty= fFilterActions[j].getFilterProperty(); if (currProperty == filterProperty) { fFilterActions[j].setChecked(set); } store.setValue(getPreferenceKey(currProperty), hasMemberFilter(currProperty)); } } if (refresh) { fViewer.getControl().setRedraw(false); BusyIndicator.showWhile(fViewer.getControl().getDisplay(), new Runnable() { public void run() { fViewer.refresh(); } }); fViewer.getControl().setRedraw(true); } } /** * Returns <code>true</code> if the given filter is installed. * * @param filterProperty the filter to be tested. Valid values are <code>FILTER_FIELDS</code>, * <code>FILTER_PUBLIC</code>, and <code>FILTER_PRIVATE</code> as defined by this action * group */ public boolean hasMemberFilter(int filterProperty) { return fFilter.hasFilter(filterProperty); } /** * Saves the state of the filter actions in a memento. * * @param memento the memento to which the state is saved */ public void saveState(IMemento memento) { memento.putString(TAG_HIDEFIELDS, String.valueOf(hasMemberFilter(FILTER_FIELDS))); memento.putString(TAG_HIDESTATIC, String.valueOf(hasMemberFilter(FILTER_STATIC))); memento.putString(TAG_HIDENONPUBLIC, String.valueOf(hasMemberFilter(FILTER_NONPUBLIC))); } /** * Restores the state of the filter actions from a memento. * <p> * Note: This method does not refresh the viewer. * </p> * @param memento the memento from which the state is restored */ public void restoreState(IMemento memento) { setMemberFilters( new int[] {FILTER_FIELDS, FILTER_STATIC, FILTER_NONPUBLIC}, new boolean[] { Boolean.valueOf(memento.getString(TAG_HIDEFIELDS)).booleanValue(), Boolean.valueOf(memento.getString(TAG_HIDESTATIC)).booleanValue(), Boolean.valueOf(memento.getString(TAG_HIDENONPUBLIC)).booleanValue() }, false); } /* (non-Javadoc) * @see ActionGroup#fillActionBars(IActionBars) */ public void fillActionBars(IActionBars actionBars) { contributeToToolBar(actionBars.getToolBarManager()); } /** * Adds the filter actions to the given tool bar * * @param tbm the tool bar to which the actions are added */ public void contributeToToolBar(IToolBarManager tbm) { if (fInViewMenu) return; tbm.add(fFilterActions[0]); // fields tbm.add(fFilterActions[1]); // static tbm.add(fFilterActions[2]); // public } /** * Adds the filter actions to the given menu manager. * * @param menu the menu manager to which the actions are added * @since 2.1 */ public void contributeToViewMenu(IMenuManager menu) { if (!fInViewMenu) return; final String filters= "filters"; //$NON-NLS-1$ if (menu.find(filters) != null) { menu.prependToGroup(filters, fFilterActions[0]); // fields menu.prependToGroup(filters, fFilterActions[1]); // static menu.prependToGroup(filters, fFilterActions[2]); // public } else { menu.add(fFilterActions[0]); // fields menu.add(fFilterActions[1]); // static menu.add(fFilterActions[2]); // public } } /* (non-Javadoc) * @see ActionGroup#dispose() */ public void dispose() { super.dispose(); } }
42,215
Bug 42215 enclosing_package template variable doesn't seem to work [code manipulation]
I'm trying to use the template variable "enclosing_package" as the value behind a package statement within a template, as follows: package ${enclosing_package}; However, the variable never gets replaced with anything, and I end up having to type out the package name.
resolved fixed
87e78c8
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-06T16:14:19Z
2003-08-28T14:13:20Z
org.eclipse.jdt.ui/core
42,215
Bug 42215 enclosing_package template variable doesn't seem to work [code manipulation]
I'm trying to use the template variable "enclosing_package" as the value behind a package statement within a template, as follows: package ${enclosing_package}; However, the variable never gets replaced with anything, and I end up having to type out the package name.
resolved fixed
87e78c8
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-06T16:14:19Z
2003-08-28T14:13:20Z
extension/org/eclipse/jdt/internal/corext/template/java/CompilationUnitContext.java
39,272
Bug 39272 Java Model Exception when creating a project from scratch
I launched Eclipse 2.1 from a brand new Workspace and from there, created a Java project (called "Works") by pointing Eclipse to the root of my project. The process fails after a short while (whether I press Next or Finish after the first page of the wizard) with a dialog telling me to look at the log. I included the top of the log below (it's about 8k, I can post it in its entirety if there's interest). The error is Java Model Exception: Java Model Status [Works does not exist.] I get the same problem with Eclipse 3.0 M1: I can't create a new project.
resolved fixed
6cbe482
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-06T17:09:01Z
2003-06-24T15:53:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/BuildPathsBlock.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.wizards.buildpaths; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IProjectDescription; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.SubProgressMonitor; 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.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TabFolder; import org.eclipse.swt.widgets.TabItem; import org.eclipse.swt.widgets.Widget; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.jface.window.Window; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.dialogs.ISelectionStatusValidator; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.model.WorkbenchContentProvider; import org.eclipse.ui.model.WorkbenchLabelProvider; import org.eclipse.ui.views.navigator.ResourceSorter; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaModelStatus; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaConventions; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.PreferenceConstants; 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.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.util.CoreUtility; import org.eclipse.jdt.internal.ui.util.PixelConverter; import org.eclipse.jdt.internal.ui.util.TabFolderLayout; import org.eclipse.jdt.internal.ui.viewsupport.ImageDisposer; import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener; import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages; import org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator; import org.eclipse.jdt.internal.ui.wizards.TypedViewerFilter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.CheckedListDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField; public class BuildPathsBlock { public static interface IRemoveOldBinariesQuery { /** * Do the callback. Returns <code>true</code> if .class files should be removed from the * old output location. */ boolean doQuery(IPath oldOutputLocation) throws InterruptedException; } private IWorkspaceRoot fWorkspaceRoot; private CheckedListDialogField fClassPathList; private StringButtonDialogField fBuildPathDialogField; private StatusInfo fClassPathStatus; private StatusInfo fOutputFolderStatus; private StatusInfo fBuildPathStatus; private IJavaProject fCurrJProject; private IPath fOutputLocationPath; private IStatusChangeListener fContext; private Control fSWTWidget; private int fPageIndex; private SourceContainerWorkbookPage fSourceContainerPage; private ProjectsWorkbookPage fProjectsPage; private LibrariesWorkbookPage fLibrariesPage; private BuildPathBasePage fCurrPage; public BuildPathsBlock(IStatusChangeListener context, int pageToShow) { fWorkspaceRoot= JavaPlugin.getWorkspace().getRoot(); fContext= context; fPageIndex= pageToShow; fSourceContainerPage= null; fLibrariesPage= null; fProjectsPage= null; fCurrPage= null; BuildPathAdapter adapter= new BuildPathAdapter(); String[] buttonLabels= new String[] { /* 0 */ NewWizardMessages.getString("BuildPathsBlock.classpath.up.button"), //$NON-NLS-1$ /* 1 */ NewWizardMessages.getString("BuildPathsBlock.classpath.down.button"), //$NON-NLS-1$ /* 2 */ null, /* 3 */ NewWizardMessages.getString("BuildPathsBlock.classpath.checkall.button"), //$NON-NLS-1$ /* 4 */ NewWizardMessages.getString("BuildPathsBlock.classpath.uncheckall.button") //$NON-NLS-1$ }; fClassPathList= new CheckedListDialogField(null, buttonLabels, new CPListLabelProvider()); fClassPathList.setDialogFieldListener(adapter); fClassPathList.setLabelText(NewWizardMessages.getString("BuildPathsBlock.classpath.label")); //$NON-NLS-1$ fClassPathList.setUpButtonIndex(0); fClassPathList.setDownButtonIndex(1); fClassPathList.setCheckAllButtonIndex(3); fClassPathList.setUncheckAllButtonIndex(4); fBuildPathDialogField= new StringButtonDialogField(adapter); fBuildPathDialogField.setButtonLabel(NewWizardMessages.getString("BuildPathsBlock.buildpath.button")); //$NON-NLS-1$ fBuildPathDialogField.setDialogFieldListener(adapter); fBuildPathDialogField.setLabelText(NewWizardMessages.getString("BuildPathsBlock.buildpath.label")); //$NON-NLS-1$ fBuildPathStatus= new StatusInfo(); fClassPathStatus= new StatusInfo(); fOutputFolderStatus= new StatusInfo(); fCurrJProject= null; } // -------- UI creation --------- public Control createControl(Composite parent) { fSWTWidget= parent; PixelConverter converter= new PixelConverter(parent); Composite composite= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(); layout.marginWidth= 0; layout.numColumns= 1; composite.setLayout(layout); TabFolder folder= new TabFolder(composite, SWT.NONE); folder.setLayout(new TabFolderLayout()); folder.setLayoutData(new GridData(GridData.FILL_BOTH)); ImageRegistry imageRegistry= JavaPlugin.getDefault().getImageRegistry(); TabItem item; fSourceContainerPage= new SourceContainerWorkbookPage(fWorkspaceRoot, fClassPathList, fBuildPathDialogField); item= new TabItem(folder, SWT.NONE); item.setText(NewWizardMessages.getString("BuildPathsBlock.tab.source")); //$NON-NLS-1$ item.setImage(imageRegistry.get(JavaPluginImages.IMG_OBJS_PACKFRAG_ROOT)); item.setData(fSourceContainerPage); item.setControl(fSourceContainerPage.getControl(folder)); IWorkbench workbench= JavaPlugin.getDefault().getWorkbench(); Image projectImage= workbench.getSharedImages().getImage(ISharedImages.IMG_OBJ_PROJECT); fProjectsPage= new ProjectsWorkbookPage(fClassPathList); item= new TabItem(folder, SWT.NONE); item.setText(NewWizardMessages.getString("BuildPathsBlock.tab.projects")); //$NON-NLS-1$ item.setImage(projectImage); item.setData(fProjectsPage); item.setControl(fProjectsPage.getControl(folder)); fLibrariesPage= new LibrariesWorkbookPage(fWorkspaceRoot, fClassPathList); item= new TabItem(folder, SWT.NONE); item.setText(NewWizardMessages.getString("BuildPathsBlock.tab.libraries")); //$NON-NLS-1$ item.setImage(imageRegistry.get(JavaPluginImages.IMG_OBJS_LIBRARY)); item.setData(fLibrariesPage); item.setControl(fLibrariesPage.getControl(folder)); // a non shared image Image cpoImage= JavaPluginImages.DESC_TOOL_CLASSPATH_ORDER.createImage(); composite.addDisposeListener(new ImageDisposer(cpoImage)); ClasspathOrderingWorkbookPage ordpage= new ClasspathOrderingWorkbookPage(fClassPathList); item= new TabItem(folder, SWT.NONE); item.setText(NewWizardMessages.getString("BuildPathsBlock.tab.order")); //$NON-NLS-1$ item.setImage(cpoImage); item.setData(ordpage); item.setControl(ordpage.getControl(folder)); if (fCurrJProject != null) { fSourceContainerPage.init(fCurrJProject); fLibrariesPage.init(fCurrJProject); fProjectsPage.init(fCurrJProject); } Composite editorcomp= new Composite(composite, SWT.NONE); DialogField[] editors= new DialogField[] { fBuildPathDialogField }; LayoutUtil.doDefaultLayout(editorcomp, editors, true, 0, 0); int maxFieldWidth= converter.convertWidthInCharsToPixels(40); LayoutUtil.setWidthHint(fBuildPathDialogField.getTextControl(null), maxFieldWidth); LayoutUtil.setHorizontalGrabbing(fBuildPathDialogField.getTextControl(null)); editorcomp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); folder.setSelection(fPageIndex); fCurrPage= (BuildPathBasePage) folder.getItem(fPageIndex).getData(); folder.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { tabChanged(e.item); } }); WorkbenchHelp.setHelp(composite, IJavaHelpContextIds.BUILD_PATH_BLOCK); Dialog.applyDialogFont(composite); return composite; } private Shell getShell() { if (fSWTWidget != null) { return fSWTWidget.getShell(); } return JavaPlugin.getActiveWorkbenchShell(); } /** * Initializes the classpath for the given project. Multiple calls to init are allowed, * but all existing settings will be cleared and replace by the given or default paths. * @param project The java project to configure. Does not have to exist. * @param outputLocation The output location to be set in the page. If <code>null</code> * is passed, jdt default settings are used, or - if the project is an existing Java project- the * output location of the existing project * @param classpathEntries The classpath entries to be set in the page. If <code>null</code> * is passed, jdt default settings are used, or - if the project is an existing Java project - the * classpath entries of the existing project */ public void init(IJavaProject jproject, IPath outputLocation, IClasspathEntry[] classpathEntries) { fCurrJProject= jproject; boolean projectExists= false; List newClassPath= null; try { IProject project= fCurrJProject.getProject(); projectExists= (project.exists() && project.getFile(".classpath").exists()); //$NON-NLS-1$ if (projectExists) { if (outputLocation == null) { outputLocation= fCurrJProject.getOutputLocation(); } if (classpathEntries == null) { classpathEntries= fCurrJProject.getRawClasspath(); } } if (outputLocation == null) { outputLocation= getDefaultBuildPath(jproject); } if (classpathEntries != null) { newClassPath= getExistingEntries(classpathEntries); } } catch (CoreException e) { JavaPlugin.log(e); } if (newClassPath == null) { newClassPath= getDefaultClassPath(jproject); } List exportedEntries = new ArrayList(); for (int i= 0; i < newClassPath.size(); i++) { CPListElement curr= (CPListElement) newClassPath.get(i); if (curr.isExported() || curr.getEntryKind() == IClasspathEntry.CPE_SOURCE) { exportedEntries.add(curr); } } // inits the dialog field fBuildPathDialogField.setText(outputLocation.makeRelative().toString()); fBuildPathDialogField.enableButton(projectExists); fClassPathList.setElements(newClassPath); fClassPathList.setCheckedElements(exportedEntries); if (fSourceContainerPage != null) { fSourceContainerPage.init(fCurrJProject); fProjectsPage.init(fCurrJProject); fLibrariesPage.init(fCurrJProject); } doStatusLineUpdate(); } private ArrayList getExistingEntries(IClasspathEntry[] classpathEntries) { ArrayList newClassPath= new ArrayList(); for (int i= 0; i < classpathEntries.length; i++) { IClasspathEntry curr= classpathEntries[i]; newClassPath.add(CPListElement.createFromExisting(curr, fCurrJProject)); } return newClassPath; } // -------- public api -------- /** * Returns the Java project. Can return <code>null<code> if the page has not * been initialized. */ public IJavaProject getJavaProject() { return fCurrJProject; } /** * Returns the current output location. Note that the path returned must not be valid. */ public IPath getOutputLocation() { return new Path(fBuildPathDialogField.getText()).makeAbsolute(); } /** * Returns the current class path (raw). Note that the entries returned must not be valid. */ public IClasspathEntry[] getRawClassPath() { List elements= fClassPathList.getElements(); int nElements= elements.size(); IClasspathEntry[] entries= new IClasspathEntry[elements.size()]; for (int i= 0; i < nElements; i++) { CPListElement currElement= (CPListElement) elements.get(i); entries[i]= currElement.getClasspathEntry(); } return entries; } public int getPageIndex() { return fPageIndex; } // -------- evaluate default settings -------- private List getDefaultClassPath(IJavaProject jproj) { List list= new ArrayList(); IResource srcFolder; IPreferenceStore store= PreferenceConstants.getPreferenceStore(); String sourceFolderName= store.getString(PreferenceConstants.SRCBIN_SRCNAME); if (store.getBoolean(PreferenceConstants.SRCBIN_FOLDERS_IN_NEWPROJ) && sourceFolderName.length() > 0) { srcFolder= jproj.getProject().getFolder(sourceFolderName); } else { srcFolder= jproj.getProject(); } list.add(new CPListElement(jproj, IClasspathEntry.CPE_SOURCE, srcFolder.getFullPath(), srcFolder)); IClasspathEntry[] jreEntries= PreferenceConstants.getDefaultJRELibrary(); list.addAll(getExistingEntries(jreEntries)); return list; } private IPath getDefaultBuildPath(IJavaProject jproj) { IPreferenceStore store= PreferenceConstants.getPreferenceStore(); if (store.getBoolean(PreferenceConstants.SRCBIN_FOLDERS_IN_NEWPROJ)) { String outputLocationName= store.getString(PreferenceConstants.SRCBIN_BINNAME); return jproj.getProject().getFullPath().append(outputLocationName); } else { return jproj.getProject().getFullPath(); } } private class BuildPathAdapter implements IStringButtonAdapter, IDialogFieldListener { // -------- IStringButtonAdapter -------- public void changeControlPressed(DialogField field) { buildPathChangeControlPressed(field); } // ---------- IDialogFieldListener -------- public void dialogFieldChanged(DialogField field) { buildPathDialogFieldChanged(field); } } private void buildPathChangeControlPressed(DialogField field) { if (field == fBuildPathDialogField) { IContainer container= chooseContainer(); if (container != null) { fBuildPathDialogField.setText(container.getFullPath().toString()); } } } private void buildPathDialogFieldChanged(DialogField field) { if (field == fClassPathList) { updateClassPathStatus(); } else if (field == fBuildPathDialogField) { updateOutputLocationStatus(); } doStatusLineUpdate(); } // -------- verification ------------------------------- private void doStatusLineUpdate() { IStatus res= findMostSevereStatus(); fContext.statusChanged(res); } private IStatus findMostSevereStatus() { return StatusUtil.getMostSevere(new IStatus[] { fClassPathStatus, fOutputFolderStatus, fBuildPathStatus }); } /** * Validates the build path. */ public void updateClassPathStatus() { fClassPathStatus.setOK(); List elements= fClassPathList.getElements(); CPListElement entryMissing= null; int nEntriesMissing= 0; IClasspathEntry[] entries= new IClasspathEntry[elements.size()]; for (int i= elements.size()-1 ; i >= 0 ; i--) { CPListElement currElement= (CPListElement)elements.get(i); boolean isChecked= fClassPathList.isChecked(currElement); if (currElement.getEntryKind() == IClasspathEntry.CPE_SOURCE) { if (!isChecked) { fClassPathList.setCheckedWithoutUpdate(currElement, true); } } else { currElement.setExported(isChecked); } entries[i]= currElement.getClasspathEntry(); if (currElement.isMissing()) { nEntriesMissing++; if (entryMissing == null) { entryMissing= currElement; } } } if (nEntriesMissing > 0) { if (nEntriesMissing == 1) { fClassPathStatus.setWarning(NewWizardMessages.getFormattedString("BuildPathsBlock.warning.EntryMissing", entryMissing.getPath().toString())); //$NON-NLS-1$ } else { fClassPathStatus.setWarning(NewWizardMessages.getFormattedString("BuildPathsBlock.warning.EntriesMissing", String.valueOf(nEntriesMissing))); //$NON-NLS-1$ } } /* if (fCurrJProject.hasClasspathCycle(entries)) { fClassPathStatus.setWarning(NewWizardMessages.getString("BuildPathsBlock.warning.CycleInClassPath")); //$NON-NLS-1$ } */ updateBuildPathStatus(); } /** * Validates output location & build path. */ private void updateOutputLocationStatus() { fOutputLocationPath= null; String text= fBuildPathDialogField.getText(); if ("".equals(text)) { //$NON-NLS-1$ fOutputFolderStatus.setError(NewWizardMessages.getString("BuildPathsBlock.error.EnterBuildPath")); //$NON-NLS-1$ return; } IPath path= getOutputLocation(); fOutputLocationPath= path; IResource res= fWorkspaceRoot.findMember(path); if (res != null) { // if exists, must be a folder or project if (res.getType() == IResource.FILE) { fOutputFolderStatus.setError(NewWizardMessages.getString("BuildPathsBlock.error.InvalidBuildPath")); //$NON-NLS-1$ return; } } fOutputFolderStatus.setOK(); updateBuildPathStatus(); } private void updateBuildPathStatus() { List elements= fClassPathList.getElements(); IClasspathEntry[] entries= new IClasspathEntry[elements.size()]; for (int i= elements.size()-1 ; i >= 0 ; i--) { CPListElement currElement= (CPListElement)elements.get(i); entries[i]= currElement.getClasspathEntry(); } IJavaModelStatus status= JavaConventions.validateClasspath(fCurrJProject, entries, fOutputLocationPath); if (!status.isOK()) { fBuildPathStatus.setError(status.getMessage()); return; } fBuildPathStatus.setOK(); } // -------- creation ------------------------------- public static void createProject(IProject project, IPath locationPath, IProgressMonitor monitor) throws CoreException { if (monitor == null) { monitor= new NullProgressMonitor(); } monitor.beginTask(NewWizardMessages.getString("BuildPathsBlock.operationdesc_project"), 10); //$NON-NLS-1$ // create the project try { if (!project.exists()) { IProjectDescription desc= project.getWorkspace().newProjectDescription(project.getName()); if (Platform.getLocation().equals(locationPath)) { locationPath= null; } desc.setLocation(locationPath); project.create(desc, monitor); monitor= null; } if (!project.isOpen()) { project.open(monitor); monitor= null; } } finally { if (monitor != null) { monitor.done(); } } } public static void addJavaNature(IProject project, IProgressMonitor monitor) throws CoreException { if (!project.hasNature(JavaCore.NATURE_ID)) { IProjectDescription description = project.getDescription(); String[] prevNatures= description.getNatureIds(); String[] newNatures= new String[prevNatures.length + 1]; System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length); newNatures[prevNatures.length]= JavaCore.NATURE_ID; description.setNatureIds(newNatures); project.setDescription(description, monitor); } else { monitor.worked(1); } } public void configureJavaProject(IProgressMonitor monitor) throws CoreException, InterruptedException { if (monitor == null) { monitor= new NullProgressMonitor(); } monitor.setTaskName(NewWizardMessages.getString("BuildPathsBlock.operationdesc_java")); //$NON-NLS-1$ monitor.beginTask("", 10); //$NON-NLS-1$ try { Shell shell= null; if (fSWTWidget != null && !fSWTWidget.getShell().isDisposed()) { shell= fSWTWidget.getShell(); } internalConfigureJavaProject(fClassPathList.getElements(), getOutputLocation(), shell, monitor); } finally { monitor.done(); } } /** * Creates the Java project and sets the configured build path and output location. * If the project already exists only build paths are updated. */ private void internalConfigureJavaProject(List classPathEntries, IPath outputLocation, Shell shell, IProgressMonitor monitor) throws CoreException, InterruptedException { // 10 monitor steps to go IRemoveOldBinariesQuery reorgQuery= null; if (shell != null) { reorgQuery= getRemoveOldBinariesQuery(shell); } // remove old .class files if (reorgQuery != null) { IPath oldOutputLocation= fCurrJProject.getOutputLocation(); if (!outputLocation.equals(oldOutputLocation)) { IResource res= fWorkspaceRoot.findMember(oldOutputLocation); if (res instanceof IContainer && hasClassfiles(res)) { if (reorgQuery.doQuery(oldOutputLocation)) { removeOldClassfiles(res); } } } } // create and set the output path first if (!fWorkspaceRoot.exists(outputLocation)) { IFolder folder= fWorkspaceRoot.getFolder(outputLocation); CoreUtility.createFolder(folder, true, true, null); folder.setDerived(true); } monitor.worked(2); int nEntries= classPathEntries.size(); IClasspathEntry[] classpath= new IClasspathEntry[nEntries]; // create and set the class path for (int i= 0; i < nEntries; i++) { CPListElement entry= ((CPListElement)classPathEntries.get(i)); IResource res= entry.getResource(); if ((res instanceof IFolder) && !res.exists()) { CoreUtility.createFolder((IFolder)res, true, true, null); } if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) { IPath folderOutput= (IPath) entry.getAttribute(CPListElement.OUTPUT); if (folderOutput != null && folderOutput.segmentCount() > 1) { IFolder folder= fWorkspaceRoot.getFolder(folderOutput); CoreUtility.createFolder(folder, true, true, null); } } classpath[i]= entry.getClasspathEntry(); // set javadoc location configureJavaDoc(entry); } monitor.worked(1); fCurrJProject.setRawClasspath(classpath, outputLocation, new SubProgressMonitor(monitor, 7)); } private void configureJavaDoc(CPListElement entry) { if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) { URL javadocLocation= (URL) entry.getAttribute(CPListElement.JAVADOC); IPath path= entry.getPath(); if (entry.getEntryKind() == IClasspathEntry.CPE_VARIABLE) { path= JavaCore.getResolvedVariablePath(path); } if (path != null) { JavaUI.setLibraryJavadocLocation(path, javadocLocation); } } else if (entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) { Object[] children= entry.getChildren(false); for (int i= 0; i < children.length; i++) { CPListElement curr= (CPListElement) children[i]; configureJavaDoc(curr); } } } public static boolean hasClassfiles(IResource resource) throws CoreException { if (resource.isDerived()) { //$NON-NLS-1$ return true; } if (resource instanceof IContainer) { IResource[] members= ((IContainer) resource).members(); for (int i= 0; i < members.length; i++) { if (hasClassfiles(members[i])) { return true; } } } return false; } public static void removeOldClassfiles(IResource resource) throws CoreException { if (resource.isDerived()) { resource.delete(false, null); } else if (resource instanceof IContainer) { IResource[] members= ((IContainer) resource).members(); for (int i= 0; i < members.length; i++) { removeOldClassfiles(members[i]); } } } public static IRemoveOldBinariesQuery getRemoveOldBinariesQuery(final Shell shell) { return new IRemoveOldBinariesQuery() { public boolean doQuery(final IPath oldOutputLocation) throws InterruptedException { final int[] res= new int[] { 1 }; shell.getDisplay().syncExec(new Runnable() { public void run() { String title= NewWizardMessages.getString("BuildPathsBlock.RemoveBinariesDialog.title"); //$NON-NLS-1$ String message= NewWizardMessages.getFormattedString("BuildPathsBlock.RemoveBinariesDialog.description", oldOutputLocation.toString()); //$NON-NLS-1$ MessageDialog dialog= new MessageDialog(shell, title, null, message, MessageDialog.QUESTION, new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL }, 2); res[0]= dialog.open(); } }); if (res[0] == 0) { return true; } else if (res[0] == 1) { return false; } throw new InterruptedException(); } }; } // ---------- util method ------------ private IContainer chooseContainer() { Class[] acceptedClasses= new Class[] { IProject.class, IFolder.class }; ISelectionStatusValidator validator= new TypedElementSelectionValidator(acceptedClasses, false); IProject[] allProjects= fWorkspaceRoot.getProjects(); ArrayList rejectedElements= new ArrayList(allProjects.length); IProject currProject= fCurrJProject.getProject(); for (int i= 0; i < allProjects.length; i++) { if (!allProjects[i].equals(currProject)) { rejectedElements.add(allProjects[i]); } } ViewerFilter filter= new TypedViewerFilter(acceptedClasses, rejectedElements.toArray()); ILabelProvider lp= new WorkbenchLabelProvider(); ITreeContentProvider cp= new WorkbenchContentProvider(); IResource initSelection= null; if (fOutputLocationPath != null) { initSelection= fWorkspaceRoot.findMember(fOutputLocationPath); } FolderSelectionDialog dialog= new FolderSelectionDialog(getShell(), lp, cp); dialog.setTitle(NewWizardMessages.getString("BuildPathsBlock.ChooseOutputFolderDialog.title")); //$NON-NLS-1$ dialog.setValidator(validator); dialog.setMessage(NewWizardMessages.getString("BuildPathsBlock.ChooseOutputFolderDialog.description")); //$NON-NLS-1$ dialog.addFilter(filter); dialog.setInput(fWorkspaceRoot); dialog.setInitialSelection(initSelection); dialog.setSorter(new ResourceSorter(ResourceSorter.NAME)); if (dialog.open() == Window.OK) { return (IContainer)dialog.getFirstResult(); } return null; } // -------- tab switching ---------- private void tabChanged(Widget widget) { if (widget instanceof TabItem) { TabItem tabItem= (TabItem) widget; BuildPathBasePage newPage= (BuildPathBasePage) tabItem.getData(); if (fCurrPage != null) { List selection= fCurrPage.getSelection(); if (!selection.isEmpty()) { newPage.setSelection(selection); } } fCurrPage= newPage; fPageIndex= tabItem.getParent().getSelectionIndex(); } } }
38,497
Bug 38497 Missleading quickfix proposal name [quickfix]
I20030604: Define the following method: void m(int i, float r) {} Call it using m(2.3, 1); Onw of the proposed quick fixes is "Cast argument 1 to 'int'" which is confusing. We should rephrase the proposal.
resolved fixed
23097b8
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-06T18:09:57Z
2003-06-05T10:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/UnresolvedElementsSubProcessor.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 * Renaud Waldura &lt;[email protected]&gt; - New class/interface with wizard *******************************************************************************/ package org.eclipse.jdt.internal.ui.text.correction; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.eclipse.text.edits.ReplaceEdit; import org.eclipse.text.edits.TextEdit; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.resources.IFile; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.ArrayType; import org.eclipse.jdt.core.dom.Assignment; import org.eclipse.jdt.core.dom.BodyDeclaration; import org.eclipse.jdt.core.dom.ClassInstanceCreation; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.ConstructorInvocation; import org.eclipse.jdt.core.dom.Expression; import org.eclipse.jdt.core.dom.FieldAccess; import org.eclipse.jdt.core.dom.IBinding; import org.eclipse.jdt.core.dom.IMethodBinding; import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.IVariableBinding; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.MethodInvocation; import org.eclipse.jdt.core.dom.Modifier; import org.eclipse.jdt.core.dom.Name; import org.eclipse.jdt.core.dom.QualifiedName; import org.eclipse.jdt.core.dom.SimpleName; import org.eclipse.jdt.core.dom.SimpleType; import org.eclipse.jdt.core.dom.SuperConstructorInvocation; import org.eclipse.jdt.core.dom.SuperFieldAccess; import org.eclipse.jdt.core.dom.SuperMethodInvocation; import org.eclipse.jdt.core.dom.ThisExpression; import org.eclipse.jdt.core.dom.Type; import org.eclipse.jdt.core.dom.TypeDeclaration; import org.eclipse.jdt.core.dom.VariableDeclarationFragment; import org.eclipse.swt.graphics.Image; import org.eclipse.ui.ISharedImages; import org.eclipse.jdt.internal.corext.codemanipulation.ImportRewrite; import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory; import org.eclipse.jdt.internal.corext.dom.ASTRewrite; import org.eclipse.jdt.internal.corext.dom.Bindings; import org.eclipse.jdt.internal.corext.dom.ScopeAnalyzer; import org.eclipse.jdt.internal.corext.dom.TypeRules; import org.eclipse.jdt.internal.corext.textmanipulation.TextBuffer; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.corext.util.WorkingCopyUtil; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.ChangeDescription; import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.EditDescription; import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.InsertDescription; import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.RemoveDescription; import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.SwapDescription; import org.eclipse.jdt.ui.text.java.IInvocationContext; import org.eclipse.jdt.ui.text.java.IProblemLocation; public class UnresolvedElementsSubProcessor { public static void getVariableProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); CompilationUnit astRoot= context.getASTRoot(); ASTNode selectedNode= problem.getCoveredNode(astRoot); if (selectedNode == null) { return; } // type that defines the variable ITypeBinding binding= null; ITypeBinding declaringTypeBinding= Bindings.getBindingOfParentType(selectedNode); if (declaringTypeBinding == null) { return; } // possible type kind of the node boolean suggestVariablePropasals= true; int typeKind= 0; Name node= null; switch (selectedNode.getNodeType()) { case ASTNode.SIMPLE_NAME: node= (SimpleName) selectedNode; ASTNode parent= node.getParent(); if (parent instanceof MethodInvocation && node.equals(((MethodInvocation)parent).getExpression())) { typeKind= SimilarElementsRequestor.CLASSES; } else if (parent instanceof SimpleType) { suggestVariablePropasals= false; typeKind= SimilarElementsRequestor.REF_TYPES; } break; case ASTNode.QUALIFIED_NAME: QualifiedName qualifierName= (QualifiedName) selectedNode; ITypeBinding qualifierBinding= qualifierName.getQualifier().resolveTypeBinding(); if (qualifierBinding != null) { node= qualifierName.getName(); binding= qualifierBinding; } else { node= qualifierName.getQualifier(); typeKind= SimilarElementsRequestor.REF_TYPES; suggestVariablePropasals= node.isSimpleName(); } if (selectedNode.getParent() instanceof SimpleType) { typeKind= SimilarElementsRequestor.REF_TYPES; suggestVariablePropasals= false; } break; case ASTNode.FIELD_ACCESS: FieldAccess access= (FieldAccess) selectedNode; Expression expression= access.getExpression(); if (expression != null) { binding= expression.resolveTypeBinding(); if (binding != null) { node= access.getName(); } } break; case ASTNode.SUPER_FIELD_ACCESS: binding= declaringTypeBinding.getSuperclass(); node= ((SuperFieldAccess) selectedNode).getName(); break; default: } if (node == null) { return; } // add type proposals if (typeKind != 0) { int relevance= Character.isUpperCase(ASTResolving.getSimpleName(node).charAt(0)) ? 3 : 0; addSimilarTypeProposals(typeKind, cu, node, relevance + 1, proposals); addNewTypeProposals(cu, node, SimilarElementsRequestor.REF_TYPES, relevance, proposals); } if (!suggestVariablePropasals) { return; } SimpleName simpleName= node.isSimpleName() ? (SimpleName) node : ((QualifiedName) node).getName(); addSimilarVariableProposals(cu, astRoot, simpleName, proposals); // new variables ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, binding); ITypeBinding senderBinding= binding != null ? binding : declaringTypeBinding; if (senderBinding.isFromSource() && targetCU != null && JavaModelUtil.isEditable(targetCU)) { String label; Image image; if (binding == null) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createfield.description", simpleName.getIdentifier()); //$NON-NLS-1$ image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PRIVATE); } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createfield.other.description", new Object[] { simpleName.getIdentifier(), binding.getName() } ); //$NON-NLS-1$ image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PUBLIC); } proposals.add(new NewVariableCompletionProposal(label, targetCU, NewVariableCompletionProposal.FIELD, simpleName, senderBinding, 6, image)); if (binding == null && senderBinding.isAnonymous()) { ASTNode anonymDecl= astRoot.findDeclaringNode(senderBinding); if (anonymDecl != null) { senderBinding= Bindings.getBindingOfParentType(anonymDecl.getParent()); if (!senderBinding.isAnonymous()) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createfield.other.description", new Object[] { simpleName.getIdentifier(), senderBinding.getName() } ); //$NON-NLS-1$ image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PUBLIC); proposals.add(new NewVariableCompletionProposal(label, targetCU, NewVariableCompletionProposal.FIELD, simpleName, senderBinding, 6, image)); } } } } if (binding == null) { BodyDeclaration bodyDeclaration= ASTResolving.findParentBodyDeclaration(node); int type= bodyDeclaration.getNodeType(); if (type == ASTNode.METHOD_DECLARATION) { String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createparameter.description", simpleName.getIdentifier()); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL); proposals.add(new NewVariableCompletionProposal(label, cu, NewVariableCompletionProposal.PARAM, simpleName, null, 5, image)); } if (type == ASTNode.METHOD_DECLARATION || type == ASTNode.INITIALIZER) { String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createlocal.description", simpleName.getIdentifier()); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL); proposals.add(new NewVariableCompletionProposal(label, cu, NewVariableCompletionProposal.LOCAL, simpleName, null, 7, image)); } if (node.getParent().getNodeType() == ASTNode.ASSIGNMENT) { Assignment assignment= (Assignment) node.getParent(); if (assignment.getLeftHandSide() == node && assignment.getParent().getNodeType() == ASTNode.EXPRESSION_STATEMENT) { ASTNode statement= assignment.getParent(); ASTRewrite rewrite= new ASTRewrite(statement.getParent()); rewrite.markAsRemoved(statement); String label= CorrectionMessages.getString("UnresolvedElementsSubProcessor.removestatement.description"); //$NON-NLS-1$ Image image= JavaPlugin.getDefault().getWorkbench().getSharedImages().getImage(ISharedImages.IMG_TOOL_DELETE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 4, image); proposal.ensureNoModifications(); proposals.add(proposal); } } } } private static void addSimilarVariableProposals(ICompilationUnit cu, CompilationUnit astRoot, SimpleName node, Collection proposals) { IBinding[] varsInScope= (new ScopeAnalyzer(astRoot)).getDeclarationsInScope(node, ScopeAnalyzer.VARIABLES); if (varsInScope.length > 0) { // avoid corrections like int i= i; String assignedName= null; ASTNode parent= node.getParent(); if (parent.getNodeType() == ASTNode.VARIABLE_DECLARATION_FRAGMENT) { assignedName= ((VariableDeclarationFragment) parent).getName().getIdentifier(); } ITypeBinding guessedType= ASTResolving.guessBindingForReference(node); if (astRoot.getAST().resolveWellKnownType("java.lang.Object") == guessedType) { //$NON-NLS-1$ guessedType= null; // too many suggestions } String identifier= node.getIdentifier(); for (int i= 0; i < varsInScope.length; i++) { IVariableBinding curr= (IVariableBinding) varsInScope[i]; String currName= curr.getName(); if (!currName.equals(assignedName)) { int relevance= 0; if (NameMatcher.isSimilarName(currName, identifier)) { relevance += 3; // variable with a similar name than the unresolved variable } if (guessedType != null && TypeRules.canAssign(guessedType, curr.getType())) { relevance += 2; // unresolved variable can be assign to this variable } if (relevance > 0) { String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changevariable.description", currName); //$NON-NLS-1$ proposals.add(new ReplaceCorrectionProposal(label, cu, node.getStartPosition(), node.getLength(), currName, relevance)); } } } } } public static void getTypeProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); if (selectedNode == null) { return; } int kind= SimilarElementsRequestor.ALL_TYPES; ASTNode parent= selectedNode.getParent(); while (parent.getLength() == selectedNode.getLength()) { // get parent of type or variablefragment parent= parent.getParent(); } switch (parent.getNodeType()) { case ASTNode.TYPE_DECLARATION: TypeDeclaration typeDeclaration=(TypeDeclaration) parent; if (typeDeclaration.superInterfaces().contains(selectedNode)) { kind= SimilarElementsRequestor.INTERFACES; } else if (selectedNode.equals(typeDeclaration.getSuperclass())) { kind= SimilarElementsRequestor.CLASSES; } break; case ASTNode.METHOD_DECLARATION: MethodDeclaration methodDeclaration= (MethodDeclaration) parent; if (methodDeclaration.thrownExceptions().contains(selectedNode)) { kind= SimilarElementsRequestor.CLASSES; } else if (selectedNode.equals(methodDeclaration.getReturnType())) { kind= SimilarElementsRequestor.REF_TYPES | SimilarElementsRequestor.VOIDTYPE; } break; case ASTNode.INSTANCEOF_EXPRESSION: kind= SimilarElementsRequestor.REF_TYPES; break; case ASTNode.THROW_STATEMENT: kind= SimilarElementsRequestor.REF_TYPES; break; case ASTNode.CLASS_INSTANCE_CREATION: if (((ClassInstanceCreation) parent).getAnonymousClassDeclaration() == null) { kind= SimilarElementsRequestor.CLASSES; } else { kind= SimilarElementsRequestor.REF_TYPES; } break; case ASTNode.SINGLE_VARIABLE_DECLARATION: int superParent= parent.getParent().getNodeType(); if (superParent == ASTNode.CATCH_CLAUSE) { kind= SimilarElementsRequestor.CLASSES; } break; default: } Name node= null; if (selectedNode instanceof SimpleType) { node= ((SimpleType) selectedNode).getName(); } else if (selectedNode instanceof ArrayType) { Type elementType= ((ArrayType) selectedNode).getElementType(); if (elementType.isSimpleType()) { node= ((SimpleType) elementType).getName(); } } else if (selectedNode instanceof Name) { node= (Name) selectedNode; } else { return; } // change to simlar type proposals addSimilarTypeProposals(kind, cu, node, 3, proposals); // add type addNewTypeProposals(cu, node, kind, 0, proposals); } private static void addSimilarTypeProposals(int kind, ICompilationUnit cu, Name node, int relevance, Collection proposals) throws CoreException { SimilarElement[] elements= SimilarElementsRequestor.findSimilarElement(cu, node, kind); // try to resolve type in context -> highest severity String resolvedTypeName= null; ITypeBinding binding= ASTResolving.guessBindingForTypeReference(node); if (binding != null) { if (binding.isArray()) { binding= binding.getElementType(); } resolvedTypeName= binding.getQualifiedName(); proposals.add(createTypeRefChangeProposal(cu, resolvedTypeName, node, relevance + 2)); } // add all similar elements for (int i= 0; i < elements.length; i++) { SimilarElement elem= elements[i]; if ((elem.getKind() & SimilarElementsRequestor.ALL_TYPES) != 0) { String fullName= elem.getName(); if (!fullName.equals(resolvedTypeName)) { proposals.add(createTypeRefChangeProposal(cu, fullName, node, relevance)); } } } } private static CUCorrectionProposal createTypeRefChangeProposal(ICompilationUnit cu, String fullName, Name node, int relevance) throws CoreException { TextBuffer buffer= null; try { buffer= TextBuffer.acquire((IFile)WorkingCopyUtil.getOriginal(cu).getResource()); CUCorrectionProposal proposal= new CUCorrectionProposal("", cu, 0); //$NON-NLS-1$ ImportRewrite importRewrite= new ImportRewrite(cu, JavaPreferencesSettings.getCodeGenerationSettings()); String simpleName= importRewrite.addImport(fullName); TextEdit root= proposal.getRootTextEdit(); if (!importRewrite.isEmpty()) { root.addChild(importRewrite.createEdit(buffer)); //$NON-NLS-1$ } String packName= Signature.getQualifier(fullName); String[] arg= { simpleName, packName }; if (node.isSimpleName() && simpleName.equals(((SimpleName) node).getIdentifier())) { // import only proposal.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_IMPDECL)); proposal.setDisplayName(CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.importtype.description", arg)); //$NON-NLS-1$ proposal.setRelevance(relevance + 20); } else { root.addChild(new ReplaceEdit(node.getStartPosition(), node.getLength(), simpleName)); //$NON-NLS-1$ if (packName.length() == 0) { proposal.setDisplayName(CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changetype.nopack.description", simpleName)); //$NON-NLS-1$ } else { proposal.setDisplayName(CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changetype.description", arg)); //$NON-NLS-1$ } proposal.setRelevance(relevance); } return proposal; } finally { if (buffer != null) TextBuffer.release(buffer); } } private static void addNewTypeProposals(ICompilationUnit cu, Name refNode, int kind, int relevance, Collection proposals) throws JavaModelException { Name node= refNode; do { String typeName= ASTResolving.getSimpleName(node); Name qualifier= null; // only propose to create types for qualifiers when the name starts with upper case boolean isPossibleName= Character.isUpperCase(typeName.charAt(0)) || (node == refNode); if (isPossibleName) { IPackageFragment enclosingPackage= null; IType enclosingType= null; if (node.isSimpleName()) { enclosingPackage= (IPackageFragment) cu.getParent(); // don't sugest member type, user can select it in wizard } else { Name qualifierName= ((QualifiedName) node).getQualifier(); // 24347 // IBinding binding= qualifierName.resolveBinding(); // if (binding instanceof ITypeBinding) { // enclosingType= Binding2JavaModel.find((ITypeBinding) binding, cu.getJavaProject()); IJavaElement[] res= cu.codeSelect(qualifierName.getStartPosition(), qualifierName.getLength()); if (res!= null && res.length > 0 && res[0] instanceof IType) { enclosingType= (IType) res[0]; } else { qualifier= qualifierName; enclosingPackage= JavaModelUtil.getPackageFragmentRoot(cu).getPackageFragment(ASTResolving.getFullName(qualifierName)); } } // new top level type if (enclosingPackage != null && !enclosingPackage.getCompilationUnit(typeName + ".java").exists()) { //$NON-NLS-1$ if ((kind & SimilarElementsRequestor.CLASSES) != 0) { proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, true, enclosingPackage, relevance)); } if ((kind & SimilarElementsRequestor.INTERFACES) != 0) { proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, false, enclosingPackage, relevance)); } } // new member type if (enclosingType != null && !enclosingType.isReadOnly() && !enclosingType.getType(typeName).exists()) { if ((kind & SimilarElementsRequestor.CLASSES) != 0) { proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, true, enclosingType, relevance)); } if ((kind & SimilarElementsRequestor.INTERFACES) != 0) { proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, false, enclosingType, relevance)); } } } node= qualifier; } while (node != null); } public static void getMethodProposals(IInvocationContext context, IProblemLocation problem, boolean needsNewName, Collection proposals) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); CompilationUnit astRoot= context.getASTRoot(); ASTNode selectedNode= problem.getCoveringNode(astRoot); if (!(selectedNode instanceof SimpleName)) { return; } SimpleName nameNode= (SimpleName) selectedNode; List arguments; Expression sender; boolean isSuperInvocation; ASTNode invocationNode= nameNode.getParent(); if (invocationNode instanceof MethodInvocation) { MethodInvocation methodImpl= (MethodInvocation) invocationNode; arguments= methodImpl.arguments(); sender= methodImpl.getExpression(); isSuperInvocation= false; } else if (invocationNode instanceof SuperMethodInvocation) { SuperMethodInvocation methodImpl= (SuperMethodInvocation) invocationNode; arguments= methodImpl.arguments(); sender= methodImpl.getQualifier(); isSuperInvocation= true; } else { return; } String methodName= nameNode.getIdentifier(); int nArguments= arguments.size(); // corrections IBinding[] bindings= (new ScopeAnalyzer(astRoot)).getDeclarationsInScope(nameNode, ScopeAnalyzer.METHODS); ArrayList parameterMismatchs= new ArrayList(); for (int i= 0; i < bindings.length; i++) { IMethodBinding binding= (IMethodBinding) bindings[i]; String curr= binding.getName(); if (curr.equals(methodName) && needsNewName) { parameterMismatchs.add(binding); } else if (binding.getParameterTypes().length == nArguments && NameMatcher.isSimilarName(methodName, curr)) { String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changemethod.description", curr); //$NON-NLS-1$ proposals.add(new ReplaceCorrectionProposal(label, context.getCompilationUnit(), problem.getOffset(), problem.getLength(), curr, 6)); } } addParameterMissmatchProposals(context, problem, parameterMismatchs, arguments, proposals); // new method ITypeBinding binding= null; if (sender != null) { binding= sender.resolveTypeBinding(); } else { binding= Bindings.getBindingOfParentType(invocationNode); if (isSuperInvocation && binding != null) { binding= binding.getSuperclass(); } } if (binding != null && binding.isFromSource()) { ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, binding); if (targetCU != null) { String label; Image image; String sig= getMethodSignature(methodName, arguments); if (cu.equals(targetCU)) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createmethod.description", sig); //$NON-NLS-1$ image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PRIVATE); } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createmethod.other.description", new Object[] { sig, targetCU.getElementName() } ); //$NON-NLS-1$ image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC); } proposals.add(new NewMethodCompletionProposal(label, targetCU, invocationNode, arguments, binding, 5, image)); if (binding.isAnonymous() && cu.equals(targetCU) && sender == null && Bindings.findMethodInHierarchy(binding, methodName, null) == null) { // no covering method ASTNode anonymDecl= astRoot.findDeclaringNode(binding); if (anonymDecl != null) { binding= Bindings.getBindingOfParentType(anonymDecl.getParent()); if (!binding.isAnonymous()) { String[] args= new String[] { sig, binding.getName() }; label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createmethod.other.description", args); //$NON-NLS-1$ image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PROTECTED); proposals.add(new NewMethodCompletionProposal(label, targetCU, invocationNode, arguments, binding, 5, image)); } } } } } } private static void addParameterMissmatchProposals(IInvocationContext context, IProblemLocation problem, List similarElements, List arguments, Collection proposals) throws CoreException { int nSimilarElements= similarElements.size(); ITypeBinding[] argTypes= getArgumentTypes(arguments); if (argTypes == null || nSimilarElements == 0) { return; } for (int i= 0; i < nSimilarElements; i++) { IMethodBinding elem = (IMethodBinding) similarElements.get(i); int diff= elem.getParameterTypes().length - argTypes.length; if (diff == 0) { int nProposals= proposals.size(); doEqualNumberOfParameters(context, problem, arguments, argTypes, elem, proposals); if (nProposals != proposals.size()) { return; // only suggest for one method (avoid duplicated proposals) } } else if (diff > 0) { doMoreParameters(context, problem, arguments, argTypes, elem, proposals); } else { doMoreArguments(context, problem, arguments, argTypes, elem, proposals); } } } private static void doMoreParameters(IInvocationContext context, IProblemLocation problem, List arguments, ITypeBinding[] argTypes, IMethodBinding methodBinding, Collection proposals) throws CoreException { ITypeBinding[] paramTypes= methodBinding.getParameterTypes(); int k= 0, nSkipped= 0; int diff= paramTypes.length - argTypes.length; int[] indexSkipped= new int[diff]; for (int i= 0; i < paramTypes.length; i++) { if (k < argTypes.length && TypeRules.canAssign(argTypes[k], paramTypes[i])) { k++; // match } else { if (nSkipped >= diff) { return; // too different } indexSkipped[nSkipped++]= i; } } ITypeBinding declaringType= methodBinding.getDeclaringClass(); ICompilationUnit cu= context.getCompilationUnit(); CompilationUnit astRoot= context.getASTRoot(); ASTNode nameNode= problem.getCoveringNode(astRoot); if (nameNode == null) { return; } // add arguments { String[] arg= new String[] { getMethodSignature(methodBinding, false) }; String label; if (diff == 1) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addargument.description", arg); //$NON-NLS-1$ } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addarguments.description", arg); //$NON-NLS-1$ } AddArgumentCorrectionProposal proposal= new AddArgumentCorrectionProposal(label, context.getCompilationUnit(), nameNode, arguments, indexSkipped, paramTypes, 8); proposal.setImage(JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD)); proposal.ensureNoModifications(); proposals.add(proposal); } // remove parameters if (!declaringType.isFromSource()) { return; } ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringType); if (targetCU != null) { ChangeDescription[] changeDesc= new ChangeDescription[paramTypes.length]; ITypeBinding[] changedTypes= new ITypeBinding[diff]; for (int i= diff - 1; i >= 0; i--) { int idx= indexSkipped[i]; changeDesc[idx]= new RemoveDescription(); changedTypes[i]= paramTypes[idx]; } String[] arg= new String[] { getMethodSignature(methodBinding, !cu.equals(targetCU)), getTypeNames(changedTypes) }; String label; if (methodBinding.isConstructor()) { if (diff == 1) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removeparam.constr.description", arg); //$NON-NLS-1$ } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removeparams.constr.description", arg); //$NON-NLS-1$ } } else { if (diff == 1) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removeparam.description", arg); //$NON-NLS-1$ } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removeparams.description", arg); //$NON-NLS-1$ } } Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_REMOVE); ChangeMethodSignatureProposal proposal= new ChangeMethodSignatureProposal(label, targetCU, nameNode, methodBinding, changeDesc, 5, image); proposals.add(proposal); } } private static String getTypeNames(ITypeBinding[] types) { StringBuffer buf= new StringBuffer(); for (int i= 0; i < types.length; i++) { if (i > 0) { buf.append(", "); //$NON-NLS-1$ } buf.append(types[i].getName()); } return buf.toString(); } private static void doMoreArguments(IInvocationContext context, IProblemLocation problem, List arguments, ITypeBinding[] argTypes, IMethodBinding methodBinding, Collection proposals) throws CoreException { ITypeBinding[] paramTypes= methodBinding.getParameterTypes(); int k= 0, nSkipped= 0; int diff= argTypes.length - paramTypes.length; int[] indexSkipped= new int[diff]; for (int i= 0; i < argTypes.length; i++) { if (k < paramTypes.length && TypeRules.canAssign(argTypes[i], paramTypes[k])) { k++; // match } else { if (nSkipped >= diff) { return; // too different } indexSkipped[nSkipped++]= i; } } ITypeBinding declaringType= methodBinding.getDeclaringClass(); ICompilationUnit cu= context.getCompilationUnit(); CompilationUnit astRoot= context.getASTRoot(); ASTNode nameNode= problem.getCoveringNode(astRoot); if (nameNode == null) { return; } // remove arguments { ASTNode selectedNode= problem.getCoveringNode(astRoot); ASTRewrite rewrite= new ASTRewrite(selectedNode.getParent()); for (int i= diff - 1; i >= 0; i--) { rewrite.markAsRemoved((Expression) arguments.get(indexSkipped[i])); } String[] arg= new String[] { getMethodSignature(methodBinding, false) }; String label; if (diff == 1) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removeargument.description", arg); //$NON-NLS-1$ } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removearguments.description", arg); //$NON-NLS-1$ } Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_REMOVE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 8, image); proposal.ensureNoModifications(); proposals.add(proposal); } // add parameters if (!declaringType.isFromSource()) { return; } ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringType); if (targetCU != null) { boolean isDifferentCU= !cu.equals(targetCU); if (isDifferentCU && isImplicitConstructor(methodBinding, targetCU)) { return; } ChangeDescription[] changeDesc= new ChangeDescription[argTypes.length]; ITypeBinding[] changeTypes= new ITypeBinding[diff]; for (int i= diff - 1; i >= 0; i--) { int idx= indexSkipped[i]; Expression arg= (Expression) arguments.get(idx); String name= arg instanceof SimpleName ? ((SimpleName) arg).getIdentifier() : null; ITypeBinding newType= Bindings.normalizeTypeBinding(argTypes[idx]); if (newType == null) { newType= astRoot.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$ } changeDesc[idx]= new InsertDescription(newType, name); changeTypes[i]= newType; } String[] arg= new String[] { getMethodSignature(methodBinding, isDifferentCU), getTypeNames(changeTypes) }; String label; if (methodBinding.isConstructor()) { if (diff == 1) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addparam.constr.description", arg); //$NON-NLS-1$ } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addparams.constr.description", arg); //$NON-NLS-1$ } } else { if (diff == 1) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addparam.description", arg); //$NON-NLS-1$ } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addparams.description", arg); //$NON-NLS-1$ } } Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD); ChangeMethodSignatureProposal proposal= new ChangeMethodSignatureProposal(label, targetCU, nameNode, methodBinding, changeDesc, 5, image); proposals.add(proposal); } } private static boolean isImplicitConstructor(IMethodBinding meth, ICompilationUnit targetCU) { if (meth.isConstructor() && meth.getParameterTypes().length == 0) { IMethodBinding[] bindings= meth.getDeclaringClass().getDeclaredMethods(); // implicit constructors must be the only constructor for (int i= 0; i < bindings.length; i++) { IMethodBinding curr= bindings[i]; if (curr.isConstructor() && curr != meth) { return false; } } CompilationUnit unit= AST.parsePartialCompilationUnit(targetCU, 0, true); return unit.findDeclaringNode(meth.getKey()) == null; } return false; } private static String getMethodSignature(IMethodBinding binding, boolean inOtherCU) { StringBuffer buf= new StringBuffer(); if (inOtherCU && !binding.isConstructor()) { buf.append(binding.getDeclaringClass().getName()).append('.'); } buf.append(binding.getName()); return getMethodSignature(buf.toString(), binding.getParameterTypes()); } private static String getMethodSignature(String name, List args) { ITypeBinding[] params= new ITypeBinding[args.size()]; for (int i= 0; i < args.size(); i++) { Expression expr= (Expression) args.get(i); ITypeBinding curr= Bindings.normalizeTypeBinding(expr.resolveTypeBinding()); if (curr == null) { curr= expr.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$ } params[i]= curr; } return getMethodSignature(name, params); } private static String getMethodSignature(String name, ITypeBinding[] params) { StringBuffer buf= new StringBuffer(); buf.append(name).append('('); for (int i= 0; i < params.length; i++) { if (i > 0) { buf.append(", "); //$NON-NLS-1$ } buf.append(params[i].getName()); } buf.append(')'); return buf.toString(); } private static void doEqualNumberOfParameters(IInvocationContext context, IProblemLocation problem, List arguments, ITypeBinding[] argTypes, IMethodBinding methodBinding, Collection proposals) throws CoreException { ITypeBinding[] paramTypes= methodBinding.getParameterTypes(); int[] indexOfDiff= new int[paramTypes.length]; int nDiffs= 0; for (int n= 0; n < argTypes.length; n++) { if (!TypeRules.canAssign(argTypes[n], paramTypes[n])) { indexOfDiff[nDiffs++]= n; } } ITypeBinding declaringType= methodBinding.getDeclaringClass(); ICompilationUnit cu= context.getCompilationUnit(); CompilationUnit astRoot= context.getASTRoot(); ASTNode nameNode= problem.getCoveringNode(astRoot); if (nameNode == null) { return; } if (nDiffs == 0) { if (nameNode.getParent() instanceof MethodInvocation) { MethodInvocation inv= (MethodInvocation) nameNode.getParent(); if (inv.getExpression() == null) { addQualifierToOuterProposal(context, inv, methodBinding, proposals); } } return; } if (nDiffs == 1) { // one argument missmatching: try to fix int idx= indexOfDiff[0]; Expression nodeToCast= (Expression) arguments.get(idx); String castType= paramTypes[idx].getQualifiedName(); ASTRewriteCorrectionProposal proposal= LocalCorrectionsSubProcessor.getCastProposal(context, castType, nodeToCast, 6); if (proposal != null) { // null returned when no cast is possible proposals.add(proposal); String[] arg= new String[] { String.valueOf(idx + 1), castType }; proposal.setDisplayName(CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addargumentcast.description", arg)); //$NON-NLS-1$ } } if (nDiffs == 2) { // try to swap int idx1= indexOfDiff[0]; int idx2= indexOfDiff[1]; boolean canSwap= TypeRules.canAssign(argTypes[idx1], paramTypes[idx2]) && TypeRules.canAssign(argTypes[idx2], paramTypes[idx1]); if (canSwap) { Expression arg1= (Expression) arguments.get(idx1); Expression arg2= (Expression) arguments.get(idx2); ASTRewrite rewrite= new ASTRewrite(arg1.getParent()); rewrite.markAsReplaced(arg1, rewrite.createCopy(arg2)); rewrite.markAsReplaced(arg2, rewrite.createCopy(arg1)); { String[] arg= new String[] { String.valueOf(idx1 + 1), String.valueOf(idx2 + 1) }; String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.swaparguments.description", arg); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 8, image); proposal.ensureNoModifications(); proposals.add(proposal); } if (declaringType.isFromSource()) { ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringType); if (targetCU != null) { ChangeDescription[] changeDesc= new ChangeDescription[paramTypes.length]; for (int i= 0; i < nDiffs; i++) { changeDesc[idx1]= new SwapDescription(idx2); } ITypeBinding[] swappedTypes= new ITypeBinding[] { argTypes[idx1], paramTypes[idx2] }; String[] args= new String[] { getMethodSignature(methodBinding, !targetCU.equals(cu)), getTypeNames(swappedTypes) }; String label; if (methodBinding.isConstructor()) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.swapparams.constr.description", args); //$NON-NLS-1$ } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.swapparams.description", args); //$NON-NLS-1$ } Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ChangeMethodSignatureProposal proposal= new ChangeMethodSignatureProposal(label, targetCU, nameNode, methodBinding, changeDesc, 5, image); proposals.add(proposal); } } return; } } if (declaringType.isFromSource()) { ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringType); if (targetCU != null) { ChangeDescription[] changeDesc= new ChangeDescription[paramTypes.length]; for (int i= 0; i < nDiffs; i++) { int diffIndex= indexOfDiff[i]; Expression arg= (Expression) arguments.get(diffIndex); String name= arg instanceof SimpleName ? ((SimpleName) arg).getIdentifier() : null; changeDesc[diffIndex]= new EditDescription(argTypes[diffIndex], name); } String[] args= new String[] { getMethodSignature(methodBinding, !targetCU.equals(cu)), getMethodSignature(methodBinding.getName(), arguments) }; String label; if (methodBinding.isConstructor()) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changeparamsignature.constr.description", args); //$NON-NLS-1$ } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changeparamsignature.description", args); //$NON-NLS-1$ } Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ChangeMethodSignatureProposal proposal= new ChangeMethodSignatureProposal(label, targetCU, nameNode, methodBinding, changeDesc, 7, image); proposals.add(proposal); } } } private static ITypeBinding[] getArgumentTypes(List arguments) { ITypeBinding[] res= new ITypeBinding[arguments.size()]; for (int i= 0; i < res.length; i++) { Expression expression= (Expression) arguments.get(i); ITypeBinding curr= expression.resolveTypeBinding(); if (curr == null) { return null; } curr= Bindings.normalizeTypeBinding(curr); if (curr == null) { curr= expression.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$ } res[i]= curr; } return res; } private static void addQualifierToOuterProposal(IInvocationContext context, MethodInvocation invocationNode, IMethodBinding binding, Collection proposals) throws CoreException { ITypeBinding declaringType= binding.getDeclaringClass(); ITypeBinding parentType= Bindings.getBindingOfParentType(invocationNode); ITypeBinding currType= parentType; boolean isInstanceMethod= !Modifier.isStatic(binding.getModifiers()); while (currType != null && !Bindings.isSuperType(declaringType, currType)) { if (isInstanceMethod && Modifier.isStatic(currType.getModifiers())) { return; } currType= currType.getDeclaringClass(); } if (currType == null || currType == parentType) { return; } ASTRewrite rewrite= new ASTRewrite(invocationNode.getParent()); AST ast= invocationNode.getAST(); String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changetoouter.description", currType.getName()); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 8, image); proposal.ensureNoModifications(); proposals.add(proposal); String qualifier= proposal.addImport(currType); Name name= ASTNodeFactory.newName(ast, qualifier); if (isInstanceMethod) { ThisExpression expr= ast.newThisExpression(); expr.setQualifier(name); invocationNode.setExpression(expr); } else { invocationNode.setExpression(name); } rewrite.markAsInserted(invocationNode.getExpression()); } public static void getConstructorProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); CompilationUnit astRoot= context.getASTRoot(); ASTNode selectedNode= problem.getCoveringNode(astRoot); if (selectedNode == null) { return; } ITypeBinding targetBinding= null; List arguments= null; IMethodBinding recursiveConstructor= null; int type= selectedNode.getNodeType(); if (type == ASTNode.CLASS_INSTANCE_CREATION) { ClassInstanceCreation creation= (ClassInstanceCreation) selectedNode; IBinding binding= creation.getName().resolveBinding(); if (binding instanceof ITypeBinding) { targetBinding= (ITypeBinding) binding; arguments= creation.arguments(); } } else if (type == ASTNode.SUPER_CONSTRUCTOR_INVOCATION) { ITypeBinding typeBinding= Bindings.getBindingOfParentType(selectedNode); if (typeBinding != null && !typeBinding.isAnonymous()) { targetBinding= typeBinding.getSuperclass(); arguments= ((SuperConstructorInvocation) selectedNode).arguments(); } } else if (type == ASTNode.CONSTRUCTOR_INVOCATION) { ITypeBinding typeBinding= Bindings.getBindingOfParentType(selectedNode); if (typeBinding != null && !typeBinding.isAnonymous()) { targetBinding= typeBinding; arguments= ((ConstructorInvocation) selectedNode).arguments(); recursiveConstructor= ASTResolving.findParentMethodDeclaration(selectedNode).resolveBinding(); } } if (targetBinding == null) { return; } IMethodBinding[] methods= targetBinding.getDeclaredMethods(); ArrayList similarElements= new ArrayList(); for (int i= 0; i < methods.length; i++) { IMethodBinding curr= methods[i]; if (curr.isConstructor() && recursiveConstructor != curr) { similarElements.add(curr); // similar elements can contain a implicit default constructor } } addParameterMissmatchProposals(context, problem, similarElements, arguments, proposals); if (targetBinding.isFromSource()) { ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, targetBinding); if (targetCU != null) { String[] args= new String[] { getMethodSignature( targetBinding.getName(), arguments) }; String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createconstructor.description", args); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC); proposals.add(new NewMethodCompletionProposal(label, targetCU, selectedNode, arguments, targetBinding, 5, image)); } } } public static void getAmbiguosTypeReferenceProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { final ICompilationUnit cu= context.getCompilationUnit(); int offset= problem.getOffset(); int len= problem.getLength(); IJavaElement[] elements= cu.codeSelect(offset, len); for (int i= 0; i < elements.length; i++) { IJavaElement curr= elements[i]; if (curr instanceof IType) { String qualifiedTypeName= JavaModelUtil.getFullyQualifiedName((IType) curr); String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.importexplicit.description", qualifiedTypeName); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_IMPDECL); CUCorrectionProposal proposal= new CUCorrectionProposal(label, cu, 5, image); TextBuffer buffer= null; try { buffer= TextBuffer.acquire((IFile)WorkingCopyUtil.getOriginal(cu).getResource()); ImportRewrite importRewrite= new ImportRewrite(cu, JavaPreferencesSettings.getCodeGenerationSettings()); importRewrite.addImport(qualifiedTypeName); importRewrite.setFindAmbiguosImports(true); proposal.getRootTextEdit().addChild(importRewrite.createEdit(buffer)); proposals.add(proposal); } finally { if (buffer != null) TextBuffer.release(buffer); } } } } }
41,514
Bug 41514 Stubs for implemented methods are created when the supertype's method implementation declares a runtime exception [code manipulation]
I have a class hierarchy like this: public interface MyInterface { void method(); } public class Implementor implements MyInterface { // note the exception declaration public void method() throws RuntimeException { ... } } When I create a new class which extends Implementor with the wizard and check the "Inherited abstract methods" checkbox, i get a method stub for method(), although it is already implemented in the superclass: class ExtendedClass extends Implementor { public void method() throws RuntimeException { // TODO Auto-generated method stub return super.trickMethod(); } }
resolved fixed
9651616
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-06T18:52:03Z
2003-08-13T21:26:40Z
org.eclipse.jdt.ui/core
41,514
Bug 41514 Stubs for implemented methods are created when the supertype's method implementation declares a runtime exception [code manipulation]
I have a class hierarchy like this: public interface MyInterface { void method(); } public class Implementor implements MyInterface { // note the exception declaration public void method() throws RuntimeException { ... } } When I create a new class which extends Implementor with the wizard and check the "Inherited abstract methods" checkbox, i get a method stub for method(), although it is already implemented in the superclass: class ExtendedClass extends Implementor { public void method() throws RuntimeException { // TODO Auto-generated method stub return super.trickMethod(); } }
resolved fixed
9651616
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-06T18:52:03Z
2003-08-13T21:26:40Z
extension/org/eclipse/jdt/internal/corext/codemanipulation/StubUtility.java
44,287
Bug 44287 Need filter to hide anonymous inner classes in Package Explorer
null
resolved fixed
bcd187c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-10-07T13:28:18Z
2003-10-07T09:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/filters/LocalTypesFilter.java