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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
49,599 |
Bug 49599 Occurrences finder should use a job
|
Build: 3.0 M6 I noticed that the background task to find occurrences in the file creates a new thread every time, rather than using jobs. This is exactly the situation that jobs were created for (in fact Erich used this as a demo of the job infrastructure at a code camp). Some advantages of changing to jobs: - less overhead (currently a new thread is created per key press, jobs use a thread pool) - better handling of priority (currently running in a thread with same priority as the UI, and thus is competing with UI thread for CPU more than it should) - smarter scheduling. Jobs with "DECORATE" priority are run based on a check of how busy the system is. Thus they do not run immediately if there are other things going on (they will run eventually, just not as quickly). This smooths over bottlenecks when the system is busy. Note that you can prevent this job from showing in the progress view or making the progress animation (cigarette) move by making it a system job (Job.setSystem(true)). Generally jobs that the user didn't explicitly start can be marked as system jobs. If there was a reason why jobs were considered and rejected, I'd be curious to know. If the infrastructure isn't useful to you then I want to fix it.
|
resolved fixed
|
c0a3666
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-07T17:16:59Z | 2004-01-06T20:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/viewsupport/SelectionListenerWithASTManager.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 java.util.HashMap;
import java.util.Map;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.util.ListenerList;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.ISelectionService;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.internal.ui.JavaUIMessages;
/**
* Infrastructure to share an AST for editor post selection listeners.
*/
public class SelectionListenerWithASTManager {
private static SelectionListenerWithASTManager fgDefault;
/**
* @return Returns the default manager instance.
*/
public static SelectionListenerWithASTManager getDefault() {
if (fgDefault == null) {
fgDefault= new SelectionListenerWithASTManager();
}
return fgDefault;
}
private static class PartListenerGroup {
private IEditorPart fPart;
private Job fCurrentJob;
private ListenerList fAstListeners;
public PartListenerGroup(IEditorPart part) {
fPart= part;
fCurrentJob= null;
fAstListeners= new ListenerList();
}
public boolean isEmpty() {
return fAstListeners.isEmpty();
}
public void install(ISelectionListenerWithAST listener) {
fAstListeners.add(listener);
}
public void uninstall(ISelectionListenerWithAST listener) {
fAstListeners.remove(listener);
}
public void fireSelectionChanged(final ITextSelection selection) {
if (fCurrentJob != null) {
fCurrentJob.cancel();
fCurrentJob= null;
}
fCurrentJob= new Job(JavaUIMessages.getString("SelectionListenerWithASTManager.job.title")) { //$NON-NLS-1$
public IStatus run(IProgressMonitor monitor) {
synchronized (PartListenerGroup.this) {
if (this != fCurrentJob) {
return Status.OK_STATUS;
}
calculateASTandInform(selection);
return Status.OK_STATUS;
}
}
};
fCurrentJob.setPriority(Job.DECORATE);
fCurrentJob.schedule();
}
private CompilationUnit computeAST() {
IEditorInput editorInput= fPart.getEditorInput();
if (editorInput != null) {
IJavaElement element= (IJavaElement) editorInput.getAdapter(IJavaElement.class);
if (element instanceof ICompilationUnit) {
synchronized (element) { // sychronize on cu to avoid conflict with reconciler: bug
return AST.parseCompilationUnit((ICompilationUnit) element, true);
}
}
if (element instanceof IClassFile) {
return AST.parseCompilationUnit((IClassFile) element, true);
}
}
return null;
}
protected void calculateASTandInform(ITextSelection selection) {
CompilationUnit astRoot= computeAST();
if (astRoot != null) {
Object[] listeners= fAstListeners.getListeners();
for (int i= 0; i < listeners.length; i++) {
((ISelectionListenerWithAST) listeners[i]).selectionChanged(fPart, selection, astRoot);
}
}
}
}
private static class WorkbenchWindowListener implements ISelectionListener {
private ISelectionService fSelectionService;
private Map fPartListeners; // key: IEditorPart, value: PartListenerGroup
public WorkbenchWindowListener(ISelectionService service) {
fSelectionService= service;
fPartListeners= new HashMap();
}
public boolean isEmpty() {
return fPartListeners.isEmpty();
}
public void install(IEditorPart part, ISelectionListenerWithAST listener) {
if (fPartListeners.isEmpty()) {
fSelectionService.addPostSelectionListener(this);
}
PartListenerGroup listenerGroup= (PartListenerGroup) fPartListeners.get(part);
if (listenerGroup == null) {
listenerGroup= new PartListenerGroup(part);
fPartListeners.put(part, listenerGroup);
}
listenerGroup.install(listener);
}
public void uninstall(IEditorPart part, ISelectionListenerWithAST listener) {
PartListenerGroup listenerGroup= (PartListenerGroup) fPartListeners.get(part);
if (listenerGroup == null) {
return;
}
listenerGroup.uninstall(listener);
if (listenerGroup.isEmpty()) {
fPartListeners.remove(part);
if (fPartListeners.isEmpty()) {
fSelectionService.removePostSelectionListener(this);
}
}
}
/* (non-Javadoc)
* @see org.eclipse.ui.ISelectionListener#selectionChanged(org.eclipse.ui.IWorkbenchPart, org.eclipse.jface.viewers.ISelection)
*/
public void selectionChanged(IWorkbenchPart part, ISelection selection) {
if (part instanceof IEditorPart && selection instanceof ITextSelection) { // only editor parts are interesting
PartListenerGroup listenerGroup= (PartListenerGroup) fPartListeners.get(part);
if (listenerGroup != null) {
listenerGroup.fireSelectionChanged((ITextSelection) selection);
}
}
}
}
private Map fListenerGroups;
private SelectionListenerWithASTManager() {
fListenerGroups= new HashMap();
}
/**
* Registers a selection listener for the given editor part.
* @param part The editor part to listen to.
* @param listener The listener to register.
*/
public void addListener(IEditorPart part, ISelectionListenerWithAST listener) {
ISelectionService service= part.getSite().getWorkbenchWindow().getSelectionService();
WorkbenchWindowListener windowListener= (WorkbenchWindowListener) fListenerGroups.get(service);
if (windowListener == null) {
windowListener= new WorkbenchWindowListener(service);
fListenerGroups.put(service, windowListener);
}
windowListener.install(part, listener);
}
/**
* Unregisters a selection listener.
* @param part The editor part the listener was registered.
* @param listener The listener to unregister.
*/
public void removeListener(IEditorPart part, ISelectionListenerWithAST listener) {
ISelectionService service= part.getSite().getWorkbenchWindow().getSelectionService();
WorkbenchWindowListener windowListener= (WorkbenchWindowListener) fListenerGroups.get(service);
if (windowListener != null) {
windowListener.uninstall(part, listener);
if (windowListener.isEmpty()) {
fListenerGroups.remove(service);
}
}
}
/**
* Forces a selection changed event that is sent to all listeners registered to the given editor
* part. The event is sent from a background thread: this method call can return before the listeners
* are informed.
*/
public void forceSelectionChange(IEditorPart part, ITextSelection selection) {
ISelectionService service= part.getSite().getWorkbenchWindow().getSelectionService();
WorkbenchWindowListener windowListener= (WorkbenchWindowListener) fListenerGroups.get(service);
if (windowListener != null) {
windowListener.selectionChanged(part, selection);
}
}
}
|
48,641 |
Bug 48641 [typing] Smart paste "fixes" comments
|
A new feature was added to M5 where smart paste fixes C style comments into Java style comments: /* * */ becomes: /* * */ The problem is that we have lots of text that is formatted the using C style and using smart paste makes the code inconistent. I don't use the feature but others on the team do. Shouldn't smart paste just indent the code?
|
resolved fixed
|
ff15185
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-07T17:44:17Z | 2003-12-12T14:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/JavaHeuristicScanner.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 java.util.Arrays;
import org.eclipse.jface.text.Assert;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.TextUtilities;
/**
* Utility methods for heuristic based Java manipulations in an incomplete Java source file.
*
* <p>An instance holds some internal position in the document and is therefore not threadsafe.</p>
*
* @since 3.0
*/
public class JavaHeuristicScanner implements Symbols {
/**
* Returned by all methods when the requested position could not be found, or if a
* {@link BadLocationException} was thrown while scanning.
*/
public static final int NOT_FOUND= -1;
/**
* Special bound parameter that means either -1 (backward scanning) or
* <code>fDocument.getLength()</code> (forward scanning).
*/
public static final int UNBOUND= -2;
/* character constants */
private static final char LBRACE= '{';
private static final char RBRACE= '}';
private static final char LPAREN= '(';
private static final char RPAREN= ')';
private static final char SEMICOLON= ';';
private static final char COLON= ':';
private static final char COMMA= ',';
private static final char LBRACKET= '[';
private static final char RBRACKET= ']';
private static final char QUESTIONMARK= '?';
private static final char EQUAL= '=';
/**
* Specifies the stop condition, upon which the <code>scanXXX</code> methods will decide whether
* to keep scanning or not. This interface may implemented by clients.
*/
public interface StopCondition {
/**
* Instructs the scanner to return the current position.
*
* @param ch the char at the current position
* @param position the current position
* @param forward the iteration direction
* @return <code>true</code> if the stop condition is met.
*/
boolean stop(char ch, int position, boolean forward);
}
/**
* Stops upon a non-whitespace (as defined by {@link Character#isWhitespace(char)}) character.
*/
private static class NonWhitespace implements StopCondition {
/*
* @see org.eclipse.jdt.internal.ui.text.JavaHeuristicScanner.StopCondition#stop(char)
*/
public boolean stop(char ch, int position, boolean forward) {
return !Character.isWhitespace(ch);
}
}
/**
* Stops upon a non-whitespace character in the default partition.
*
* @see NonWhitespace
*/
private class NonWhitespaceDefaultPartition extends NonWhitespace {
/*
* @see org.eclipse.jdt.internal.ui.text.JavaHeuristicScanner.StopCondition#stop(char)
*/
public boolean stop(char ch, int position, boolean forward) {
return super.stop(ch, position, true) && isDefaultPartition(position);
}
}
/**
* Stops upon a non-java identifier (as defined by {@link Character#isJavaIdentifierPart(char)}) character.
*/
private static class NonJavaIdentifierPart implements StopCondition {
/*
* @see org.eclipse.jdt.internal.ui.text.JavaHeuristicScanner.StopCondition#stop(char)
*/
public boolean stop(char ch, int position, boolean forward) {
return !Character.isJavaIdentifierPart(ch);
}
}
/**
* Stops upon a non-java identifier character in the default partition.
*
* @see NonJavaIdentifierPart
*/
private class NonJavaIdentifierPartDefaultPartition extends NonJavaIdentifierPart {
/*
* @see org.eclipse.jdt.internal.ui.text.JavaHeuristicScanner.StopCondition#stop(char)
*/
public boolean stop(char ch, int position, boolean forward) {
return super.stop(ch, position, true) || !isDefaultPartition(position);
}
}
/**
* Stops upon a character in the default partition that matches the given character list.
*/
private class CharacterMatch implements StopCondition {
private final char[] fChars;
/**
* Creates a new instance.
* @param ch the single character to match
*/
public CharacterMatch(char ch) {
this(new char[] {ch});
}
/**
* Creates a new instance.
* @param chars the chars to match.
*/
public CharacterMatch(char[] chars) {
Assert.isNotNull(chars);
Assert.isTrue(chars.length > 0);
fChars= chars;
Arrays.sort(chars);
}
/*
* @see org.eclipse.jdt.internal.ui.text.JavaHeuristicScanner.StopCondition#stop(char, int)
*/
public boolean stop(char ch, int position, boolean forward) {
return Arrays.binarySearch(fChars, ch) >= 0 && isDefaultPartition(position);
}
}
/**
* Acts like character match, but skips all scopes introduced by parenthesis, brackets, and
* braces.
*/
protected class SkippingScopeMatch extends CharacterMatch {
private char fOpening, fClosing;
private int fDepth= 0;
/**
* Creates a new instance.
* @param ch the single character to match
*/
public SkippingScopeMatch(char ch) {
super(ch);
}
/**
* Creates a new instance.
* @param chars the chars to match.
*/
public SkippingScopeMatch(char[] chars) {
super(chars);
}
/*
* @see org.eclipse.jdt.internal.ui.text.JavaHeuristicScanner.StopCondition#stop(char, int)
*/
public boolean stop(char ch, int position, boolean forward) {
if (fDepth == 0 && super.stop(ch, position, true))
return true;
else if (ch == fOpening)
fDepth++;
else if (ch == fClosing) {
fDepth--;
if (fDepth == 0) {
fOpening= 0;
fClosing= 0;
}
} else if (fDepth == 0) {
fDepth= 1;
if (forward) {
switch (ch) {
case LBRACE:
fOpening= LBRACE;
fClosing= RBRACE;
break;
case LPAREN:
fOpening= LPAREN;
fClosing= RPAREN;
break;
case LBRACKET:
fOpening= LBRACKET;
fClosing= RBRACKET;
break;
}
} else {
switch (ch) {
case RBRACE:
fOpening= RBRACE;
fClosing= LBRACE;
break;
case RPAREN:
fOpening= RPAREN;
fClosing= LPAREN;
break;
case RBRACKET:
fOpening= RBRACKET;
fClosing= LBRACKET;
break;
}
}
}
return false;
}
}
/** The document being scanned. */
private IDocument fDocument;
/** The partitioning being used for scanning. */
private String fPartitioning;
/** The partition to scan in. */
private String fPartition;
/* internal scan state */
/** the most recently read character. */
private char fChar;
/** the most recently read position. */
private int fPos;
/* preset stop conditions */
private final StopCondition fNonWSDefaultPart= new NonWhitespaceDefaultPartition();
private final static StopCondition fNonWS= new NonWhitespace();
private final StopCondition fNonIdent= new NonJavaIdentifierPartDefaultPartition();
/**
* Creates a new instance.
*
* @param document the document to scan
* @param partitioning the partitioning to use for scanning
* @param partition the partition to scan in
*/
public JavaHeuristicScanner(IDocument document, String partitioning, String partition) {
Assert.isNotNull(document);
Assert.isNotNull(partitioning);
Assert.isNotNull(partition);
fDocument= document;
fPartitioning= partitioning;
fPartition= partition;
}
/**
* Calls <code>this(document, IJavaPartitions.JAVA_PARTITIONING, IDocument.DEFAULT_CONTENT_TYPE)</code>.
*
* @param document the document to scan.
*/
public JavaHeuristicScanner(IDocument document) {
this(document, IJavaPartitions.JAVA_PARTITIONING, IDocument.DEFAULT_CONTENT_TYPE);
}
/**
* Returns the most recent internal scan position.
*
* @return the most recent internal scan position.
*/
public int getPosition() {
return fPos;
}
/**
* Returns the next token in forward direction, starting at <code>start</code>, and not extending
* further than <code>bound</code>. The return value is one of the constants defined in {@link Symbols}.
* After a call, {@link #getPosition()} will return the position just after the scanned token
* (i.e. the next position that will be scanned).
*
* @param start the first character position in the document to consider
* @param bound the first position not to consider any more
* @return a constant from {@link Symbols} describing the next token
*/
public int nextToken(int start, int bound) {
int pos= scanForward(start, bound, fNonWSDefaultPart);
if (pos == NOT_FOUND)
return TokenEOF;
fPos++;
switch (fChar) {
case LBRACE:
return TokenLBRACE;
case RBRACE:
return TokenRBRACE;
case LBRACKET:
return TokenLBRACKET;
case RBRACKET:
return TokenRBRACKET;
case LPAREN:
return TokenLPAREN;
case RPAREN:
return TokenRPAREN;
case SEMICOLON:
return TokenSEMICOLON;
case COMMA:
return TokenCOMMA;
case QUESTIONMARK:
return TokenQUESTIONMARK;
case EQUAL:
return TokenEQUAL;
}
// else
if (Character.isJavaIdentifierPart(fChar)) {
// assume an ident or keyword
int from= pos, to;
pos= scanForward(pos + 1, bound, fNonIdent);
if (pos == NOT_FOUND)
to= bound;
else
to= pos;
String identOrKeyword;
try {
identOrKeyword= fDocument.get(from, to - from);
} catch (BadLocationException e) {
return TokenEOF;
}
return getToken(identOrKeyword);
} else {
// operators, number literals etc
return TokenOTHER;
}
}
/**
* Returns the next token in backward direction, starting at <code>start</code>, and not extending
* further than <code>bound</code>. The return value is one of the constants defined in {@link Symbols}.
* After a call, {@link #getPosition()} will return the position just before the scanned token
* starts (i.e. the next position that will be scanned).
*
* @param start the first character position in the document to consider
* @param bound the first position not to consider any more
* @return a constant from {@link Symbols} describing the previous token
*/
public int previousToken(int start, int bound) {
int pos= scanBackward(start, bound, fNonWSDefaultPart);
if (pos == NOT_FOUND)
return TokenEOF;
fPos--;
switch (fChar) {
case LBRACE:
return TokenLBRACE;
case RBRACE:
return TokenRBRACE;
case LBRACKET:
return TokenLBRACKET;
case RBRACKET:
return TokenRBRACKET;
case LPAREN:
return TokenLPAREN;
case RPAREN:
return TokenRPAREN;
case SEMICOLON:
return TokenSEMICOLON;
case COLON:
return TokenCOLON;
case COMMA:
return TokenCOMMA;
case QUESTIONMARK:
return TokenQUESTIONMARK;
case EQUAL:
return TokenEQUAL;
}
// else
if (Character.isJavaIdentifierPart(fChar)) {
// assume an ident or keyword
int from, to= pos + 1;
pos= scanBackward(pos - 1, bound, fNonIdent);
if (pos == NOT_FOUND)
from= bound + 1;
else
from= pos + 1;
String identOrKeyword;
try {
identOrKeyword= fDocument.get(from, to - from);
} catch (BadLocationException e) {
return TokenEOF;
}
return getToken(identOrKeyword);
} else {
// operators, number literals etc
return TokenOTHER;
}
}
/**
* Returns one of the keyword constants or <code>TokenIDENT</code> for a scanned identifier.
*
* @param s a scanned identifier
* @return one of the constants defined in {@link Symbols}
*/
private int getToken(String s) {
Assert.isNotNull(s);
switch (s.length()) {
case 2:
if ("if".equals(s)) //$NON-NLS-1$
return TokenIF;
if ("do".equals(s)) //$NON-NLS-1$
return TokenDO;
break;
case 3:
if ("for".equals(s)) //$NON-NLS-1$
return TokenFOR;
if ("try".equals(s)) //$NON-NLS-1$
return TokenTRY;
if ("new".equals(s)) //$NON-NLS-1$
return TokenNEW;
break;
case 4:
if ("case".equals(s)) //$NON-NLS-1$
return TokenCASE;
if ("else".equals(s)) //$NON-NLS-1$
return TokenELSE;
if ("goto".equals(s)) //$NON-NLS-1$
return TokenGOTO;
break;
case 5:
if ("break".equals(s)) //$NON-NLS-1$
return TokenBREAK;
if ("catch".equals(s)) //$NON-NLS-1$
return TokenCATCH;
if ("while".equals(s)) //$NON-NLS-1$
return TokenWHILE;
break;
case 6:
if ("return".equals(s)) //$NON-NLS-1$
return TokenRETURN;
if ("static".equals(s)) //$NON-NLS-1$
return TokenSTATIC;
if ("switch".equals(s)) //$NON-NLS-1$
return TokenSWITCH;
break;
case 7:
if ("default".equals(s)) //$NON-NLS-1$
return TokenDEFAULT;
if ("finally".equals(s)) //$NON-NLS-1$
return TokenFINALLY;
break;
case 12:
if ("synchronized".equals(s)) //$NON-NLS-1$
return TokenSYNCHRONIZED;
break;
}
return TokenIDENT;
}
/**
* Returns the position of the closing peer character (forward search). Any scopes introduced by opening peers
* are skipped. All peers accounted for must reside in the default partition.
*
* <p>Note that <code>start</code> must not point to the opening peer, but to the first
* character being searched.</p>
*
* @param start the start position
* @param openingPeer the opening peer character (e.g. '{')
* @param closingPeer the closing peer character (e.g. '}')
* @return the matching peer character position, or <code>NOT_FOUND</code>
*/
public int findClosingPeer(int start, final char openingPeer, final char closingPeer) {
Assert.isNotNull(fDocument);
Assert.isTrue(start >= 0);
try {
int depth= 1;
start -= 1;
while (true) {
start= scanForward(start + 1, UNBOUND, new CharacterMatch(new char[] {openingPeer, closingPeer}));
if (start == NOT_FOUND)
return NOT_FOUND;
if (fDocument.getChar(start) == openingPeer)
depth++;
else
depth--;
if (depth == 0)
return start;
}
} catch (BadLocationException e) {
return NOT_FOUND;
}
}
/**
* Returns the position of the opening peer character (backward search). Any scopes introduced by closing peers
* are skipped. All peers accounted for must reside in the default partition.
*
* <p>Note that <code>start</code> must not point to the closing peer, but to the first
* character being searched.</p>
*
* @param start the start position
* @param openingPeer the opening peer character (e.g. '{')
* @param closingPeer the closing peer character (e.g. '}')
* @return the matching peer character position, or <code>NOT_FOUND</code>
*/
public int findOpeningPeer(int start, char openingPeer, char closingPeer) {
Assert.isTrue(start < fDocument.getLength());
try {
int depth= 1;
start += 1;
while (true) {
start= scanBackward(start - 1, UNBOUND, new CharacterMatch(new char[] {openingPeer, closingPeer}));
if (start == NOT_FOUND)
return NOT_FOUND;
if (fDocument.getChar(start) == closingPeer)
depth++;
else
depth--;
if (depth == 0)
return start;
}
} catch (BadLocationException e) {
return NOT_FOUND;
}
}
/**
* Computes the surrounding block around <code>offset</code>. The search is started at the
* beginning of <code>offset</code>, i.e. an opening brace at <code>offset</code> will not be
* part of the surrounding block, but a closing brace will.
*
* @param offset the offset for which the surrounding block is computed
* @return a region describing the surrounding block, or <code>null</code> if none can be found
*/
public IRegion findSurroundingBlock(int offset) {
if (offset < 1 || offset >= fDocument.getLength())
return null;
int begin= findOpeningPeer(offset - 1, LBRACE, RBRACE);
int end= findClosingPeer(offset, LBRACE, RBRACE);
if (begin == NOT_FOUND || end == NOT_FOUND)
return null;
return new Region(begin, end + 1 - begin);
}
/**
* Finds the smallest position in <code>fDocument</code> such that the position is >= <code>position</code>
* and < <code>bound</code> and <code>Character.isWhitespace(fDocument.getChar(pos))</code> evaluates to <code>false</code>
* and the position is in the default partition.
*
* @param position the first character position in <code>fDocument</code> to be considered
* @param bound the first position in <code>fDocument</code> to not consider any more, with <code>bound</code> > <code>position</code>, or <code>UNBOUND</code>
* @return the smallest position of a non-whitespace character in [<code>position</code>, <code>bound</code>) that resides in a Java partition, or <code>NOT_FOUND</code> if none can be found
*/
public int findNonWhitespaceForward(int position, int bound) {
return scanForward(position, bound, fNonWSDefaultPart);
}
/**
* Finds the smallest position in <code>fDocument</code> such that the position is >= <code>position</code>
* and < <code>bound</code> and <code>Character.isWhitespace(fDocument.getChar(pos))</code> evaluates to <code>false</code>.
*
* @param position the first character position in <code>fDocument</code> to be considered
* @param bound the first position in <code>fDocument</code> to not consider any more, with <code>bound</code> > <code>position</code>, or <code>UNBOUND</code>
* @return the smallest position of a non-whitespace character in [<code>position</code>, <code>bound</code>), or <code>NOT_FOUND</code> if none can be found
*/
public int findNonWhitespaceForwardInAnyPartition(int position, int bound) {
return scanForward(position, bound, fNonWS);
}
/**
* Finds the highest position in <code>fDocument</code> such that the position is <= <code>position</code>
* and > <code>bound</code> and <code>Character.isWhitespace(fDocument.getChar(pos))</code> evaluates to <code>false</code>
* and the position is in the default partition.
*
* @param position the first character position in <code>fDocument</code> to be considered
* @param bound the first position in <code>fDocument</code> to not consider any more, with <code>bound</code> < <code>position</code>, or <code>UNBOUND</code>
* @return the highest position of a non-whitespace character in (<code>bound</code>, <code>position</code>] that resides in a Java partition, or <code>NOT_FOUND</code> if none can be found
*/
public int findNonWhitespaceBackward(int position, int bound) {
return scanBackward(position, bound, fNonWSDefaultPart);
}
/**
* Finds the lowest position <code>p</code> in <code>fDocument</code> such that <code>start</code> <= p <
* <code>bound</code> and <code>condition.stop(fDocument.getChar(p), p)</code> evaluates to <code>true</code>.
*
* @param start the first character position in <code>fDocument</code> to be considered
* @param bound the first position in <code>fDocument</code> to not consider any more, with <code>bound</code> > <code>start</code>, or <code>UNBOUND</code>
* @param condition the <code>StopCondition</code> to check
* @return the lowest position in [<code>start</code>, <code>bound</code>) for which <code>condition</code> holds, or <code>NOT_FOUND</code> if none can be found
*/
public int scanForward(int start, int bound, StopCondition condition) {
Assert.isTrue(start >= 0);
if (bound == UNBOUND)
bound= fDocument.getLength();
Assert.isTrue(bound <= fDocument.getLength());
try {
fPos= start;
while (fPos < bound) {
fChar= fDocument.getChar(fPos);
if (condition.stop(fChar, fPos, true))
return fPos;
fPos++;
}
} catch (BadLocationException e) {
}
return NOT_FOUND;
}
/**
* Finds the lowest position in <code>fDocument</code> such that the position is >= <code>position</code>
* and < <code>bound</code> and <code>fDocument.getChar(position) == ch</code> evaluates to <code>true</code>
* and the position is in the default partition.
*
* @param position the first character position in <code>fDocument</code> to be considered
* @param bound the first position in <code>fDocument</code> to not consider any more, with <code>bound</code> > <code>position</code>, or <code>UNBOUND</code>
* @param ch the <code>char</code> to search for
* @return the lowest position of <code>ch</code> in (<code>bound</code>, <code>position</code>] that resides in a Java partition, or <code>NOT_FOUND</code> if none can be found
*/
public int scanForward(int position, int bound, char ch) {
return scanForward(position, bound, new CharacterMatch(ch));
}
/**
* Finds the lowest position in <code>fDocument</code> such that the position is >= <code>position</code>
* and < <code>bound</code> and <code>fDocument.getChar(position) == ch</code> evaluates to <code>true</code> for at least one
* ch in <code>chars</code> and the position is in the default partition.
*
* @param position the first character position in <code>fDocument</code> to be considered
* @param bound the first position in <code>fDocument</code> to not consider any more, with <code>bound</code> > <code>position</code>, or <code>UNBOUND</code>
* @param chars an array of <code>char</code> to search for
* @return the lowest position of a non-whitespace character in [<code>position</code>, <code>bound</code>) that resides in a Java partition, or <code>NOT_FOUND</code> if none can be found
*/
public int scanForward(int position, int bound, char[] chars) {
return scanForward(position, bound, new CharacterMatch(chars));
}
/**
* Finds the highest position <code>p</code> in <code>fDocument</code> such that <code>bound</code> < <code>p</code> <= <code>start</code>
* and <code>condition.stop(fDocument.getChar(p), p)</code> evaluates to <code>true</code>.
*
* @param start the first character position in <code>fDocument</code> to be considered
* @param bound the first position in <code>fDocument</code> to not consider any more, with <code>bound</code> < <code>start</code>, or <code>UNBOUND</code>
* @param condition the <code>StopCondition</code> to check
* @return the highest position in (<code>bound</code>, <code>start</code> for which <code>condition</code> holds, or <code>NOT_FOUND</code> if none can be found
*/
public int scanBackward(int start, int bound, StopCondition condition) {
if (bound == UNBOUND)
bound= -1;
Assert.isTrue(bound >= -1);
Assert.isTrue(start < fDocument.getLength() );
try {
fPos= start;
while (fPos > bound) {
fChar= fDocument.getChar(fPos);
if (condition.stop(fChar, fPos, false))
return fPos;
fPos--;
}
} catch (BadLocationException e) {
}
return NOT_FOUND;
}
/**
* Finds the highest position in <code>fDocument</code> such that the position is <= <code>position</code>
* and > <code>bound</code> and <code>fDocument.getChar(position) == ch</code> evaluates to <code>true</code> for at least one
* ch in <code>chars</code> and the position is in the default partition.
*
* @param position the first character position in <code>fDocument</code> to be considered
* @param bound the first position in <code>fDocument</code> to not consider any more, with <code>bound</code> < <code>position</code>, or <code>UNBOUND</code>
* @param ch the <code>char</code> to search for
* @return the highest position of one element in <code>chars</code> in (<code>bound</code>, <code>position</code>] that resides in a Java partition, or <code>NOT_FOUND</code> if none can be found
*/
public int scanBackward(int position, int bound, char ch) {
return scanBackward(position, bound, new CharacterMatch(ch));
}
/**
* Finds the highest position in <code>fDocument</code> such that the position is <= <code>position</code>
* and > <code>bound</code> and <code>fDocument.getChar(position) == ch</code> evaluates to <code>true</code> for at least one
* ch in <code>chars</code> and the position is in the default partition.
*
* @param position the first character position in <code>fDocument</code> to be considered
* @param bound the first position in <code>fDocument</code> to not consider any more, with <code>bound</code> < <code>position</code>, or <code>UNBOUND</code>
* @param chars an array of <code>char</code> to search for
* @return the highest position of one element in <code>chars</code> in (<code>bound</code>, <code>position</code>] that resides in a Java partition, or <code>NOT_FOUND</code> if none can be found
*/
public int scanBackward(int position, int bound, char[] chars) {
return scanBackward(position, bound, new CharacterMatch(chars));
}
/**
* Checks whether <code>position</code> resides in a default (Java) partition of <code>fDocument</code>.
*
* @param position the position to be checked
* @return <code>true</code> if <code>position</code> is in the default partition of <code>fDocument</code>, <code>false</code> otherwise
*/
public boolean isDefaultPartition(int position) {
Assert.isTrue(position >= 0);
Assert.isTrue(position <= fDocument.getLength());
try {
ITypedRegion region= TextUtilities.getPartition(fDocument, fPartitioning, position);
return region.getType().equals(fPartition);
} catch (BadLocationException e) {
}
return false;
}
/**
* Checks if the line seems to be an open condition not followed by a block (i.e. an if, while,
* or for statement with just one following statement, see example below).
*
* <pre>
* if (condition)
* doStuff();
* </pre>
*
* <p>Algorithm: if the last non-WS, non-Comment code on the line is an if (condition), while (condition),
* for( expression), do, else, and there is no statement after that </p>
*
* @param position the insert position of the new character
* @param bound the lowest position to consider
* @return <code>true</code> if the code is a conditional statement or loop without a block, <code>false</code> otherwise
*/
public boolean isBracelessBlockStart(int position, int bound) {
if (position < 1)
return false;
switch (previousToken(position, bound)) {
case TokenDO:
case TokenELSE:
return true;
case TokenRPAREN:
position= findOpeningPeer(fPos, LPAREN, RPAREN);
if (position > 0) {
switch (previousToken(position - 1, bound)) {
case TokenIF:
case TokenFOR:
case TokenWHILE:
return true;
}
}
}
return false;
}
}
|
48,641 |
Bug 48641 [typing] Smart paste "fixes" comments
|
A new feature was added to M5 where smart paste fixes C style comments into Java style comments: /* * */ becomes: /* * */ The problem is that we have lots of text that is formatted the using C style and using smart paste makes the code inconistent. I don't use the feature but others on the team do. Shouldn't smart paste just indent the code?
|
resolved fixed
|
ff15185
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-07T17:44:17Z | 2003-12-12T14:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/JavaIndenter.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.core.runtime.Plugin;
import org.eclipse.jface.text.Assert;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
/**
* Uses the {@link org.eclipse.jdt.internal.ui.text.JavaHeuristicScanner}to
* get the indentation level for a certain position in a document.
*
* <p>
* An instance holds some internal position in the document and is therefore
* not threadsafe.
* </p>
*
* @since 3.0
*/
public class JavaIndenter {
/** The document being scanned. */
private IDocument fDocument;
/** The indentation accumulated by <code>findPreviousIndenationUnit</code>. */
private int fIndent;
/**
* The absolute (character-counted) indentation offset for special cases
* (method defs, array initializers)
*/
private int fAlign;
/** The stateful scanposition for the indentation methods. */
private int fPosition;
/** The previous position. */
private int fPreviousPos;
/** The most recent token. */
private int fToken;
/** The line of <code>fPosition</code>. */
private int fLine;
/**
* The scanner we will use to scan the document. It has to be installed
* on the same document as the one we get.
*/
private JavaHeuristicScanner fScanner;
/**
* Creates a new instance.
*
* @param document the document to scan
* @param scanner the {@link JavaHeuristicScanner} to be used for scanning
* the document. It must be installed on the same <code>IDocument</code>.
*/
public JavaIndenter(IDocument document, JavaHeuristicScanner scanner) {
Assert.isNotNull(document);
Assert.isNotNull(scanner);
fDocument= document;
fScanner= scanner;
}
/**
* Computes the indentation at the reference point of <code>position</code>.
*
* @param offset the offset in the document
* @return a String which reflects the indentation at the line in which the
* reference position to <code>offset</code> resides, or <code>null</code>
* if it cannot be determined
*/
public StringBuffer getReferenceIndentation(int offset) {
int unit= findReferencePosition(offset, true);
// if we were unable to find anything, return null
if (unit == JavaHeuristicScanner.NOT_FOUND)
return null;
return getLeadingWhitespace(unit);
}
/**
* Computes the indentation at <code>offset</code>.
*
* @param offset the offset in the document
* @return a String which reflects the correct indentation for the line in
* which offset resides, or <code>null</code> if it cannot be
* determined
*/
public StringBuffer computeIndentation(int offset) {
StringBuffer indent= getReferenceIndentation(offset);
// handle special alignment
if (fAlign != JavaHeuristicScanner.NOT_FOUND) {
try {
// a special case has been detected.
IRegion line= fDocument.getLineInformationOfOffset(fAlign);
int lineOffset= line.getOffset();
return createIndent(lineOffset, fAlign);
} catch (BadLocationException e) {
return null;
}
}
if (indent == null)
return null;
// add additional indent
indent.append(createIndent(fIndent));
if (fIndent < 0)
unindent(indent);
return indent;
}
/**
* Returns the indentation of the line at <code>offset</code> as a
* <code>StringBuffer</code>. If the offset is not valid, the empty string
* is returned.
*
* @param offset the offset in the document
* @return the indentation (leading whitespace) of the line in which
* <code>offset</code> is located
*/
private StringBuffer getLeadingWhitespace(int offset) {
StringBuffer indent= new StringBuffer();
try {
IRegion line= fDocument.getLineInformationOfOffset(offset);
int lineOffset= line.getOffset();
int nonWS= fScanner.findNonWhitespaceForwardInAnyPartition(lineOffset, lineOffset + line.getLength());
indent.append(fDocument.get(lineOffset, nonWS - lineOffset));
return indent;
} catch (BadLocationException e) {
return indent;
}
}
/**
* Reduces indentation in <code>indent</code> by one indentation unit.
*
* @param indent the indentation to be modified
*/
private void unindent(StringBuffer indent) {
CharSequence oneIndent= createIndent(1);
int i= indent.lastIndexOf(oneIndent.toString()); //$NON-NLS-1$
if (i != -1) {
indent.delete(i, i + oneIndent.length());
}
}
/**
* Creates an indentation string of the length indent - start + 1,
* consisting of the content in <code>fDocument</code> in the range
* [start, indent), with every character replaced by a space except for
* tabs, which are kept as such.
*
* <p>Every run of the number of spaces that make up a tab are replaced
* by a tab character.</p>
*
* @return the indentation corresponding to the document content specified
* by <code>start</code> and <code>indent</code>
*/
private StringBuffer createIndent(int start, int indent) {
final int tabLen= prefTabLength();
StringBuffer ret= new StringBuffer();
try {
int spaces= 0;
while (start < indent) {
char ch= fDocument.getChar(start);
if (ch == '\t') {
ret.append('\t');
spaces= 0;
} else if (tabLen == -1){
ret.append(' ');
} else {
spaces++;
if (spaces == tabLen) {
ret.append('\t');
spaces= 0;
}
}
start++;
}
// remainder
if (spaces == tabLen)
ret.append('\t');
else
while (spaces-- > 0)
ret.append(' ');
} catch (BadLocationException e) {
}
return ret;
}
/**
* Creates a string that represents the given number of indents (can be
* spaces or tabs..)
*
* @param indent the requested indentation level.
*
* @return the indentation specified by <code>indent</code>
*/
private CharSequence createIndent(int indent) {
// get a sensible default when running without the infrastructure for testing
JavaCore plugin= JavaCore.getJavaCore();
if (plugin == null) {
StringBuffer ret= new StringBuffer();
while (indent-- > 0)
ret.append('\t');
return ret;
} else {
StringBuffer oneIndent= new StringBuffer();
if (JavaCore.SPACE.equals(JavaCore.getOption(JavaCore.FORMATTER_TAB_CHAR))) {
int tabLen= Integer.parseInt(JavaCore.getOption(JavaCore.FORMATTER_TAB_SIZE));
for (int i= 0; i < tabLen; i++)
oneIndent.append(' ');
} else if (JavaCore.TAB.equals(JavaCore.getOption(JavaCore.FORMATTER_TAB_CHAR)))
oneIndent.append('\t');
else
oneIndent.append('\t'); // default
StringBuffer ret= new StringBuffer();
for (int i= 0; i < indent; i++)
ret.append(oneIndent);
return ret;
}
}
/**
* Returns the reference position regarding to indentation for <code>offset</code>,
* or <code>NOT_FOUND</code>. This method calls
* {@link #findReferencePosition(int, boolean) findReferencePosition(offset, false)}
*
* @param offset the offset for which the reference is computed
* @return the reference statement relative to which <code>offset</code>
* should be indented, or {@link JavaHeuristicScanner#NOT_FOUND}
*/
public int findReferencePosition(int offset) {
return findReferencePosition(offset, false);
}
/**
* Returns the reference position regarding to indentation for <code>position</code>,
* or <code>NOT_FOUND</code>.
*
* <p>If <code>peekNextChar</code> is <code>true</code>, the next token after
* <code>offset</code> is read and taken into account when computing the
* indentation. Currently, if the next token is the first token on the line
* (i.e. only preceded by whitespace), the following tokens are specially
* handled:
* <ul>
* <li><code>switch</code> labels are indented relative to the switch block</li>
* <li>opening curly braces are aligned correctly with the introducing code</li>
* <li>closing curly braces are aligned properly with the introducing code of
* the matching opening brace</li>
* <li>closing parenthesis' are aligned with their opening peer</li>
* <li>the <code>else</code> keyword is aligned with its <code>if</code>, anything
* else is aligned normally (i.e. with the base of any introducing statements).</li>
* <li>if there is no token on the same line after <code>offset</code>, the indentation
* is the same as for an <code>else</code> keyword</li>
* </ul>
*
* @param offset the offset for which the reference is computed
* @param peekNextChar whether to take the next character (closing
* brace etc.) on the same line as <code>offset</code> into account
* and handle indentation accordingly
* @return the reference statement relative to which <code>offset</code>
* should be indented, or {@link JavaHeuristicScanner#NOT_FOUND}
*/
public int findReferencePosition(int offset, boolean peekNextChar) {
boolean danglingElse= false;
boolean unindent= false;
boolean matchBrace= false;
boolean matchParen= false;
boolean matchCase= false;
// account for unindenation characters already typed in, but after position
// if they are on a line by themselves, the indentation gets adjusted
// accordingly
//
// also account for a dangling else
if (peekNextChar) {
if (offset < fDocument.getLength()) {
try {
IRegion line= fDocument.getLineInformationOfOffset(offset);
int lineOffset= line.getOffset();
int next= fScanner.nextToken(offset, lineOffset + line.getLength());
int prevPos= Math.max(offset - 1, 0);
boolean isFirstTokenOnLine= fDocument.get(lineOffset, prevPos + 1 - lineOffset).trim().length() == 0;
switch (next) {
case Symbols.TokenEOF:
case Symbols.TokenELSE:
danglingElse= true;
break;
case Symbols.TokenCASE:
case Symbols.TokenDEFAULT:
if (isFirstTokenOnLine)
matchCase= true;
break;
case Symbols.TokenLBRACE: // for opening-brace-on-new-line style
if (fScanner.isBracelessBlockStart(prevPos, JavaHeuristicScanner.UNBOUND))
unindent= true;
if (fScanner.previousToken(prevPos, JavaHeuristicScanner.UNBOUND) == Symbols.TokenCOLON)
unindent= true;
break;
case Symbols.TokenRBRACE: // closing braces get unindented
if (isFirstTokenOnLine)
matchBrace= true;
break;
case Symbols.TokenRPAREN:
if (isFirstTokenOnLine)
matchParen= true;
break;
}
} catch (BadLocationException e) {
}
} else {
// assume an else could come if we are at the end of file
danglingElse= true;
}
}
int ref= findReferencePosition(offset, danglingElse, matchBrace, matchParen, matchCase);
if (unindent)
fIndent--;
return ref;
}
/**
* Returns the reference position regarding to indentation for <code>position</code>,
* or <code>NOT_FOUND</code>.<code>fIndent</code> will contain the
* relative indentation (in indentation units, not characters) after the
* call. If there is a special alignment (e.g. for a method declaration
* where parameters should be aligned), <code>fAlign</code> will contain
* the absolute position of the alignment reference in <code>fDocument</code>,
* otherwise <code>fAlign</code> is set to <code>JavaHeuristicScanner.NOT_FOUND</code>.
*
* @param position the position for which the reference is computed
* @param danglingElse whether a dangling else should be assumed at <code>position</code>
* @param matchBrace whether the position of the matching brace should be
* returned instead of doing code analysis
* @param matchBrace whether the position of the matching parenthesis
* should be returned instead of doing code analysis
* @param matchCase whether the position of a switch statement reference
* should be returned (either an earlier case statement or the
* switch block brace)
* @return the reference statement relative to which <code>position</code>
* should be indented, or {@link JavaHeuristicScanner#NOT_FOUND}
*/
public int findReferencePosition(int offset, boolean danglingElse, boolean matchBrace, boolean matchParen, boolean matchCase) {
fIndent= 0; // the indentation modification
fAlign= JavaHeuristicScanner.NOT_FOUND;
fPosition= offset;
// forward cases
// an unindentation happens sometimes if the next token is special, namely on braces, parens and case labels
// align braces
if (matchBrace) {
if (skipScope(Symbols.TokenLBRACE, Symbols.TokenRBRACE))
return skipToStatementStart(true, true);
else {
// if we can't find the matching brace, the heuristic is to unindent
// by one against the normal position
int pos= findReferencePosition(offset, danglingElse, false, matchParen, matchCase);
fIndent--;
return pos;
}
}
// align parenthesis'
if (matchParen) {
if (skipScope(Symbols.TokenLPAREN, Symbols.TokenRPAREN))
return fPosition;
else {
// if we can't find the matching paren, the heuristic is to unindent
// by one against the normal position
int pos= findReferencePosition(offset, danglingElse, matchBrace, false, matchCase);
fIndent--;
return pos;
}
}
// the only reliable way to get case labels aligned (due to many different styles of using braces in a block)
// is to go for another case statement, or the scope opening brace
if (matchCase) {
return matchCaseAlignment();
}
nextToken();
switch (fToken) {
case Symbols.TokenRBRACE:
// skip the block and fall through
// if we can't complete the scope, reset the scan position
int pos= fPosition;
if (!skipScope())
fPosition= pos;
case Symbols.TokenSEMICOLON:
// this is the 90% case: after a statement block
// the end of the previous statement / block previous.end
// search to the end of the statement / block before the previous; the token just after that is previous.start
return skipToStatementStart(danglingElse, false);
// scope introduction: special treat who special is
case Symbols.TokenLPAREN:
case Symbols.TokenLBRACE:
case Symbols.TokenLBRACKET:
return handleScopeIntroduction(offset + 1);
case Symbols.TokenEOF:
// trap when hitting start of document
return 0;
case Symbols.TokenEQUAL:
// indent assignments
fIndent= prefAssignmentIndent();
return fPosition;
case Symbols.TokenCOLON:
// TODO handle ternary deep indentation
fIndent= prefCaseBlockIndent();
return fPosition;
case Symbols.TokenQUESTIONMARK:
if (prefTernaryDeepAlign()) {
setFirstElementAlignment(fPosition, offset + 1);
return fPosition;
} else {
fIndent= prefTernaryIndent();
return fPosition;
}
// indentation for blockless introducers:
case Symbols.TokenDO:
case Symbols.TokenWHILE:
case Symbols.TokenELSE:
fIndent= prefSimpleIndent();
return fPosition;
case Symbols.TokenRPAREN:
if (skipScope(Symbols.TokenLPAREN, Symbols.TokenRPAREN)) {
nextToken();
if (fToken == Symbols.TokenIF || fToken == Symbols.TokenWHILE || fToken == Symbols.TokenFOR) {
fIndent= prefSimpleIndent();
return fPosition;
}
}
// else: fall through to default
case Symbols.TokenCOMMA:
// inside a list of some type
// easy if there is already a list item before with its own indentation - we just align
// if not: take the start of the list ( LPAREN, LBRACE, LBRACKET ) and either align or
// indent by list-indent
default:
// inside whatever we don't know about: similar to the list case:
// if we are inside a continued expression, then either align with a previous line that has indentation
// or indent from the expression start line (either a scope introducer or the start of the expr).
return skipToPreviousListItemOrListStart();
}
}
/**
* Skips to the start of a statement that ends at the current position.
*
* @param danglingElse whether to indent aligned with the last <code>if</code>
* @return the reference offset of the start of the statement
*/
private int skipToStatementStart(boolean danglingElse, boolean isInBlock) {
while (true) {
nextToken();
if (isInBlock) {
switch (fToken) {
// exit on all block introducers
case Symbols.TokenIF:
case Symbols.TokenELSE:
case Symbols.TokenSYNCHRONIZED:
case Symbols.TokenCOLON:
case Symbols.TokenSTATIC:
case Symbols.TokenCATCH:
case Symbols.TokenDO:
case Symbols.TokenWHILE:
case Symbols.TokenFINALLY:
case Symbols.TokenFOR:
case Symbols.TokenTRY:
return fPosition;
case Symbols.TokenSWITCH:
fIndent= prefCaseIndent();
return fPosition;
}
}
switch (fToken) {
// scope introduction through: LPAREN, LBRACE, LBRACKET
// search stop on SEMICOLON, RBRACE, COLON, EOF
// -> the next token is the start of the statement (i.e. previousPos when backward scanning)
case Symbols.TokenLPAREN:
case Symbols.TokenLBRACE:
case Symbols.TokenLBRACKET:
case Symbols.TokenSEMICOLON:
case Symbols.TokenEOF:
case Symbols.TokenCOLON:
return fPreviousPos;
case Symbols.TokenRBRACE:
// RBRACE is a little tricky: it can be the end of an array definition, but
// usually it is the end of a previous block
int pos= fPreviousPos; // store state
if (skipScope() && looksLikeArrayInitializerIntro())
continue; // it's an array
else
return pos; // it's not - do as with all the above
// scopes: skip them
case Symbols.TokenRPAREN:
case Symbols.TokenRBRACKET:
pos= fPreviousPos;
if (skipScope())
break;
else
return pos;
// IF / ELSE: align the position after the conditional block with the if
// so we are ready for an else, except if danglingElse is false
// in order for this to work, we must skip an else to its if
case Symbols.TokenIF:
if (danglingElse)
return fPosition;
else
break;
case Symbols.TokenELSE:
// skip behind the next if, as we have that one covered
pos= fPosition;
if (skipNextIF())
break;
else
return pos;
case Symbols.TokenDO:
// align the WHILE position with its do
return fPosition;
case Symbols.TokenWHILE:
// this one is tricky: while can be the start of a while loop
// or the end of a do - while
pos= fPosition;
if (hasMatchingDo()) {
// continue searching from the DO on
break;
} else {
// continue searching from the WHILE on
fPosition= pos;
break;
}
default:
// keep searching
}
}
}
/**
* Returns as a reference any previous <code>switch</code> labels (<code>case</code>
* or <code>default</code>) or the offset of the brace that scopes the switch
* statement. Sets <code>fIndent</code> to <code>prefCaseIndent</code> upon
* a match.
*
* @return the reference offset for a <code>switch</code> label
*/
private int matchCaseAlignment() {
while (true) {
nextToken();
switch (fToken) {
// invalid cases: another case label or an LBRACE must come before a case
// -> bail out with the current position
case Symbols.TokenLPAREN:
case Symbols.TokenLBRACKET:
case Symbols.TokenEOF:
return fPosition;
case Symbols.TokenLBRACE:
// opening brace of switch statement
fIndent= prefCaseIndent();
return fPosition;
case Symbols.TokenCASE:
case Symbols.TokenDEFAULT:
// align with previous label
fIndent= 0;
return fPosition;
// scopes: skip them
case Symbols.TokenRPAREN:
case Symbols.TokenRBRACKET:
case Symbols.TokenRBRACE:
skipScope();
break;
default:
// keep searching
continue;
}
}
}
/**
* Returns the reference position for a list element. The algorithm
* tries to match any previous indentation on the same list. If there is none,
* the reference position returned is determined depending on the type of list:
* The indentation will either match the list scope introducer (e.g. for
* method declarations), so called deep indents, or simply increase the
* indentation by a number of standard indents. See also {@link #handleScopeIntroduction(int)}.
*
* @return the reference position for a list item: either a previous list item
* that has its own indentation, or the list introduction start.
*/
private int skipToPreviousListItemOrListStart() {
int startLine= fLine;
int startPosition= fPosition;
while (true) {
nextToken();
// if any line item comes with its own indentation, adapt to it
if (fLine < startLine) {
try {
int lineOffset= fDocument.getLineOffset(startLine);
fAlign= fScanner.findNonWhitespaceForwardInAnyPartition(lineOffset, startPosition + 1);
} catch (BadLocationException e) {
// ignore and return just the position
}
return startPosition;
}
switch (fToken) {
// scopes: skip them
case Symbols.TokenRPAREN:
case Symbols.TokenRBRACKET:
case Symbols.TokenRBRACE:
skipScope();
break;
// scope introduction: special treat who special is
case Symbols.TokenLPAREN:
case Symbols.TokenLBRACE:
case Symbols.TokenLBRACKET:
return handleScopeIntroduction(startPosition + 1);
case Symbols.TokenSEMICOLON:
return fPosition;
case Symbols.TokenEOF:
return 0;
}
}
}
/**
* Skips a scope and positions the cursor (<code>fPosition</code>) on the
* token that opens the scope. Returns <code>true</code> if a matching peer
* could be found, <code>false</code> otherwise. The current token when calling
* must be one out of <code>Symbols.TokenRPAREN</code>, <code>Symbols.TokenRBRACE</code>,
* and <code>Symbols.TokenRBRACKET</code>.
*
* @return <code>true</code> if a matching peer was found, <code>false</code> otherwise
*/
private boolean skipScope() {
switch (fToken) {
case Symbols.TokenRPAREN:
return skipScope(Symbols.TokenLPAREN, Symbols.TokenRPAREN);
case Symbols.TokenRBRACKET:
return skipScope(Symbols.TokenLBRACKET, Symbols.TokenRBRACKET);
case Symbols.TokenRBRACE:
return skipScope(Symbols.TokenLBRACE, Symbols.TokenRBRACE);
default:
Assert.isTrue(false);
return false;
}
}
/**
* Handles the introduction of a new scope. The current token must be one out
* of <code>Symbols.TokenLPAREN</code>, <code>Symbols.TokenLBRACE</code>,
* and <code>Symbols.TokenLBRACKET</code>. Returns as the reference position
* either the token introducing the scope or - if available - the first
* java token after that.
*
* <p>Depending on the type of scope introduction, the indentation will align
* (deep indenting) with the reference position (<code>fAlign</code> will be
* set to the reference position) or <code>fIndent</code> will be set to
* the number of indentation units.
* </p>
*
* @param bound the bound for the search for the first token after the scope
* introduction.
* @return
*/
private int handleScopeIntroduction(int bound) {
switch (fToken) {
// scope introduction: special treat who special is
case Symbols.TokenLPAREN:
int pos= fPosition; // store
// special: method declaration deep indentation
if (looksLikeMethodDecl()) {
if (prefMethodDeclDeepIndent())
return setFirstElementAlignment(pos, bound);
else {
fIndent= prefMethodDeclIndent();
return pos;
}
} else {
fPosition= pos;
if (looksLikeMethodCall()) {
if (prefMethodCallDeepIndent())
return setFirstElementAlignment(pos, bound);
else {
fIndent= prefMethodCallIndent();
return pos;
}
} else if (prefParenthesisDeepIndent())
return setFirstElementAlignment(pos, bound);
}
// normal: return the parenthesis as reference
fIndent= prefParenthesisIndent();
return pos;
case Symbols.TokenLBRACE:
pos= fPosition; // store
// special: array initializer
if (looksLikeArrayInitializerIntro())
if (prefArrayDeepIndent())
return setFirstElementAlignment(pos, bound);
else
fIndent= prefArrayIndent();
else
fIndent= prefBlockIndent();
// normal: skip to the statement start before the scope introducer
// opening braces are often on differently ending indents than e.g. a method definition
fPosition= pos; // restore
return skipToStatementStart(true, true); // set to true to match the first if
case Symbols.TokenLBRACKET:
pos= fPosition; // store
// special: method declaration deep indentation
if (prefArrayDimensionsDeepIndent()) {
return setFirstElementAlignment(pos, bound);
}
// normal: return the bracket as reference
fIndent= prefBracketIndent();
return pos; // restore
default:
Assert.isTrue(false);
return -1; // dummy
}
}
/**
* Sets the deep indent offset (<code>fAlign</code>) to either the offset
* right after <code>scopeIntroducerOffset</code> or - if available - the
* first Java token after <code>scopeIntroducerOffset</code>, but before
* <code>bound</code>.
*
* @param scopeIntroducerOffset the offset of the scope introducer
* @param bound the bound for the search for another element
* @return the reference position
*/
private int setFirstElementAlignment(int scopeIntroducerOffset, int bound) {
int firstPossible= scopeIntroducerOffset + 1; // align with the first position after the scope intro
fAlign= fScanner.findNonWhitespaceForwardInAnyPartition(firstPossible, bound);
if (fAlign == JavaHeuristicScanner.NOT_FOUND)
fAlign= firstPossible;
return fAlign;
}
/**
* Returns <code>true</code> if the next token received after calling
* <code>nextToken</code> is either an equal sign or an array designator ('[]').
*
* @return <code>true</code> if the next elements look like the start of an array definition
*/
private boolean looksLikeArrayInitializerIntro() {
nextToken();
if (fToken == Symbols.TokenEQUAL || skipBrackets()) {
return true;
}
return false;
}
/**
* Skips over the next <code>if</code> keyword. The current token when calling
* this method must be an <code>else</code> keyword. Returns <code>true</code>
* if a matching <code>if</code> could be found, <code>false</code> otherwise.
* The cursor (<code>fPosition</code>) is set to the offset of the <code>if</code>
* token.
*
* @return <code>true</code> if a matching <code>if</code> token was found, <code>false</code> otherwise
*/
private boolean skipNextIF() {
Assert.isTrue(fToken == Symbols.TokenELSE);
while (true) {
nextToken();
switch (fToken) {
// scopes: skip them
case Symbols.TokenRPAREN:
case Symbols.TokenRBRACKET:
case Symbols.TokenRBRACE:
skipScope();
break;
case Symbols.TokenIF:
// found it, return
return true;
case Symbols.TokenELSE:
// recursively skip else-if blocks
skipNextIF();
break;
// shortcut scope starts
case Symbols.TokenLPAREN:
case Symbols.TokenLBRACE:
case Symbols.TokenLBRACKET:
case Symbols.TokenEOF:
return false;
}
}
}
/**
* while(condition); is ambiguous when parsed backwardly, as it is a valid
* statement by its own, so we have to check whether there is a matching
* do. A <code>do</code> can either be separated from the while by a
* block, or by a single statement, which limits our search distance.
*
* @return <code>true</code> if the <code>while</code> currently in
* <code>fToken</code> has a matching <code>do</code>.
*/
private boolean hasMatchingDo() {
Assert.isTrue(fToken == Symbols.TokenWHILE);
nextToken();
switch (fToken) {
case Symbols.TokenRBRACE:
skipScope(); // and fall thru
case Symbols.TokenSEMICOLON:
skipToStatementStart(false, false);
return fToken == Symbols.TokenDO;
}
return false;
}
/**
* Skips brackets if the current token is a RBRACKET. There can be nothing
* but whitespace in between, this is only to be used for <code>[]</code> elements.
*
* @return <code>true</code> if a <code>[]</code> could be scanned, the
* current token is left at the LBRACKET.
*/
private boolean skipBrackets() {
if (fToken == Symbols.TokenRBRACKET) {
nextToken();
if (fToken == Symbols.TokenLBRACKET) {
return true;
}
}
return false;
}
/**
* Reads the next token in backward direction from the heuristic scanner
* and sets the fields <code>fToken, fPreviousPosition</code> and <code>fPosition</code>
* accordingly.
*/
private void nextToken() {
nextToken(fPosition);
}
/**
* Reads the next token in backward direction of <code>start</code> from
* the heuristic scanner and sets the fields <code>fToken, fPreviousPosition</code>
* and <code>fPosition</code> accordingly.
*/
private void nextToken(int start) {
fToken= fScanner.previousToken(start - 1, JavaHeuristicScanner.UNBOUND);
fPreviousPos= start;
fPosition= fScanner.getPosition() + 1;
try {
fLine= fDocument.getLineOfOffset(fPosition);
} catch (BadLocationException e) {
fLine= -1;
}
}
/**
* Returns <code>true</code> if the current tokens look like a method
* declaration header (i.e. only the return type and method name). The
* heuristic calls <code>nextToken</code> and expects an identifier
* (method name) and a type declaration (an identifier with optional
* brackets) which also covers the visibility modifier of constructors; it
* does not recognize package visible constructors.
*
* @return <code>true</code> if the current position looks like a method
* declaration header.
*/
private boolean looksLikeMethodDecl() {
/*
* TODO This heuristic does not recognize package private constructors
* since those do have neither type nor visibility keywords.
* One option would be to go over the parameter list, but that might
* be empty as well - hard to do without an AST...
*/
nextToken();
if (fToken == Symbols.TokenIDENT) { // method name
do nextToken();
while (skipBrackets()); // optional brackets for array valued return types
return fToken == Symbols.TokenIDENT; // type name
}
return false;
}
/**
* Returns <code>true</code> if the current tokens look like a method
* call header (i.e. an identifier as opposed to a keyword taking parenthesized
* parameters such as <code>if</code>).
* <p>The heuristic calls <code>nextToken</code> and expects an identifier
* (method name).
*
* @return <code>true</code> if the current position looks like a method call
* header.
*/
private boolean looksLikeMethodCall() {
nextToken();
return fToken == Symbols.TokenIDENT; // method name
}
/**
* Scans tokens for the matching opening peer. The internal cursor
* (<code>fPosition</code>) is set to the offset of the opening peer if found.
*
* @return <code>true</code> if a matching token was found, <code>false</code>
* otherwise
*/
private boolean skipScope(int openToken, int closeToken) {
int depth= 1;
while (true) {
nextToken();
if (fToken == closeToken) {
depth++;
} else if (fToken == openToken) {
depth--;
if (depth == 0)
return true;
} else if (fToken == Symbols.TokenEOF) {
return false;
}
}
}
private int prefTabLength() {
int tabLen;
// TODO adjust once this is a per-project setting
JavaCore core= JavaCore.getJavaCore();
JavaPlugin plugin= JavaPlugin.getDefault();
if (core != null && plugin != null)
if (JavaCore.SPACE.equals(JavaCore.getOption(JavaCore.FORMATTER_TAB_CHAR)))
// if the formatter uses chars to mark indentation, then don't substitute any chars
tabLen= -1; // results in no tabs being substituted for space runs
else
// if the formatter uses tabs to mark indentations, use the visual setting from the editor
// to get nicely aligned indentations
tabLen= plugin.getPreferenceStore().getInt(PreferenceConstants.EDITOR_TAB_WIDTH);
else
tabLen= 4; // sensible default for testing
return tabLen;
}
// TODO add preference lookup or probing
private boolean prefArrayDimensionsDeepIndent() {
return true; // sensible default
}
private int prefArrayIndent() {
Plugin plugin= JavaCore.getPlugin();
if (plugin != null) {
String option= JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_ARRAY_INITIALIZER_EXPRESSIONS_ALIGNMENT);
try {
if ((Integer.parseInt(option) & Integer.parseInt(DefaultCodeFormatterConstants.FORMATTER_INDENT_BY_ONE)) != 0)
return 1;
else
return prefContinuationIndent();
} catch (NumberFormatException e) {
// ignore and return default
}
}
return prefContinuationIndent(); // default
}
private boolean prefArrayDeepIndent() {
Plugin plugin= JavaCore.getPlugin();
if (plugin != null) {
String option= JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_ARRAY_INITIALIZER_EXPRESSIONS_ALIGNMENT);
try {
if ((Integer.parseInt(option) & Integer.parseInt(DefaultCodeFormatterConstants.FORMATTER_INDENT_ON_COLUMN)) != 0)
return true;
else
return false;
} catch (NumberFormatException e) {
// ignore and return default
}
}
return true;
}
private boolean prefTernaryDeepAlign() {
return true; // sensible default
}
private int prefTernaryIndent() {
return 2; // default: double indent conditional expressions
}
private int prefCaseIndent() {
Plugin plugin= JavaCore.getPlugin();
if (plugin != null) {
if (DefaultCodeFormatterConstants.TRUE.equals(JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_SWITCH)))
return 0;
else
return prefBlockIndent();
}
return 0; // sun standard
}
private int prefAssignmentIndent() {
return prefBlockIndent();
}
private int prefCaseBlockIndent() {
if (true)
return prefBlockIndent();
Plugin plugin= JavaCore.getPlugin();
if (plugin != null) {
if (DefaultCodeFormatterConstants.TRUE.equals(JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_CASES)))
return 0;
else
return prefBlockIndent();
}
return prefBlockIndent(); // sun standard
}
private int prefSimpleIndent() {
return prefBlockIndent();
}
private int prefBracketIndent() {
return prefBlockIndent();
}
private boolean prefMethodDeclDeepIndent() {
Plugin plugin= JavaCore.getPlugin();
if (plugin != null) {
String option= JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_METHOD_DECLARATION_ARGUMENTS_ALIGNMENT);
try {
if ((Integer.parseInt(option) & Integer.parseInt(DefaultCodeFormatterConstants.FORMATTER_INDENT_ON_COLUMN)) != 0)
return true;
else
return false;
} catch (NumberFormatException e) {
// ignore and return default
}
}
return true;
}
private int prefMethodDeclIndent() {
Plugin plugin= JavaCore.getPlugin();
if (plugin != null) {
String option= JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_METHOD_DECLARATION_ARGUMENTS_ALIGNMENT);
try {
if ((Integer.parseInt(option) & Integer.parseInt(DefaultCodeFormatterConstants.FORMATTER_INDENT_BY_ONE)) != 0)
return 1;
else
return prefContinuationIndent();
} catch (NumberFormatException e) {
// ignore and return default
}
}
return 1;
}
private boolean prefMethodCallDeepIndent() {
Plugin plugin= JavaCore.getPlugin();
if (plugin != null) {
String option= JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_MESSAGE_SEND_ARGUMENTS_ALIGNMENT);
try {
if ((Integer.parseInt(option) & Integer.parseInt(DefaultCodeFormatterConstants.FORMATTER_INDENT_ON_COLUMN)) != 0)
return true;
else
return false;
} catch (NumberFormatException e) {
// ignore and return default
}
}
return false; // sensible default
}
private int prefMethodCallIndent() {
Plugin plugin= JavaCore.getPlugin();
if (plugin != null) {
String option= JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_MESSAGE_SEND_ARGUMENTS_ALIGNMENT);
try {
if ((Integer.parseInt(option) & Integer.parseInt(DefaultCodeFormatterConstants.FORMATTER_INDENT_BY_ONE)) != 0)
return 1;
else
return prefContinuationIndent();
} catch (NumberFormatException e) {
// ignore and return default
}
}
return 1; // sensible default
}
private boolean prefParenthesisDeepIndent() {
if (true)
return false;
Plugin plugin= JavaCore.getPlugin();
if (plugin != null) {
String option= JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_CONTINUATION_INDENTATION);
try {
if ((Integer.parseInt(option) & Integer.parseInt(DefaultCodeFormatterConstants.FORMATTER_INDENT_ON_COLUMN)) != 0)
return true;
else
return false;
} catch (NumberFormatException e) {
// ignore and return default
}
}
return false; // sensible default
}
private int prefParenthesisIndent() {
return prefContinuationIndent();
}
private int prefBlockIndent() {
return 1; // sensible default
}
private int prefContinuationIndent() {
Plugin plugin= JavaCore.getPlugin();
if (plugin != null) {
String option= JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_CONTINUATION_INDENTATION);
try {
return Integer.parseInt(option);
} catch (NumberFormatException e) {
// ignore and return default
}
}
return 2; // sensible default
}
}
|
48,641 |
Bug 48641 [typing] Smart paste "fixes" comments
|
A new feature was added to M5 where smart paste fixes C style comments into Java style comments: /* * */ becomes: /* * */ The problem is that we have lots of text that is formatted the using C style and using smart paste makes the code inconistent. I don't use the feature but others on the team do. Shouldn't smart paste just indent the code?
|
resolved fixed
|
ff15185
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-07T17:44:17Z | 2003-12-12T14:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/JavaAutoIndentStrategy.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Nikolay Metchev - Fixed bug 29909
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text.java;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.BadPartitioningException;
import org.eclipse.jface.text.DefaultAutoIndentStrategy;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.DocumentCommand;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.TextUtilities;
import org.eclipse.jface.text.rules.DefaultPartitioner;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.texteditor.ITextEditorExtension3;
import org.eclipse.jdt.core.ToolFactory;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.core.compiler.IScanner;
import org.eclipse.jdt.core.compiler.ITerminalSymbols;
import org.eclipse.jdt.core.compiler.InvalidInputException;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.DoStatement;
import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.ForStatement;
import org.eclipse.jdt.core.dom.IfStatement;
import org.eclipse.jdt.core.dom.Statement;
import org.eclipse.jdt.core.dom.WhileStatement;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.corext.Assert;
import org.eclipse.jdt.internal.corext.dom.NodeFinder;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.FastJavaPartitionScanner;
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.Symbols;
/**
* Auto indent strategy sensitive to brackets.
*/
public class JavaAutoIndentStrategy extends DefaultAutoIndentStrategy {
private static class CompilationUnitInfo {
public char[] buffer;
public int delta;
public CompilationUnitInfo(char[] buffer, int delta) {
this.buffer= buffer;
this.delta= delta;
}
}
private boolean fCloseBrace;
private boolean fIsSmartMode;
private String fPartitioning;
/**
* Creates a new Java auto indent strategy for the given document partitioning.
*
* @param partitioning the document partitioning
*/
public JavaAutoIndentStrategy(String partitioning) {
fPartitioning= partitioning;
}
private int getBracketCount(IDocument d, int startOffset, int endOffset, boolean ignoreCloseBrackets) throws BadLocationException {
int bracketCount= 0;
while (startOffset < endOffset) {
char curr= d.getChar(startOffset);
startOffset++;
switch (curr) {
case '/' :
if (startOffset < endOffset) {
char next= d.getChar(startOffset);
if (next == '*') {
// a comment starts, advance to the comment end
startOffset= getCommentEnd(d, startOffset + 1, endOffset);
} else if (next == '/') {
// '//'-comment: nothing to do anymore on this line
startOffset= endOffset;
}
}
break;
case '*' :
if (startOffset < endOffset) {
char next= d.getChar(startOffset);
if (next == '/') {
// we have been in a comment: forget what we read before
bracketCount= 0;
startOffset++;
}
}
break;
case '{' :
bracketCount++;
ignoreCloseBrackets= false;
break;
case '}' :
if (!ignoreCloseBrackets) {
bracketCount--;
}
break;
case '"' :
case '\'' :
startOffset= getStringEnd(d, startOffset, endOffset, curr);
break;
default :
}
}
return bracketCount;
}
// ----------- bracket counting ------------------------------------------------------
private int getCommentEnd(IDocument d, int offset, int endOffset) throws BadLocationException {
while (offset < endOffset) {
char curr= d.getChar(offset);
offset++;
if (curr == '*') {
if (offset < endOffset && d.getChar(offset) == '/') {
return offset + 1;
}
}
}
return endOffset;
}
private String getIndentOfLine(IDocument d, int line) throws BadLocationException {
if (line > -1) {
int start= d.getLineOffset(line);
int end= start + d.getLineLength(line) - 1;
int whiteEnd= findEndOfWhiteSpace(d, start, end);
return d.get(start, whiteEnd - start);
} else {
return ""; //$NON-NLS-1$
}
}
private int getStringEnd(IDocument d, int offset, int endOffset, char ch) throws BadLocationException {
while (offset < endOffset) {
char curr= d.getChar(offset);
offset++;
if (curr == '\\') {
// ignore escaped characters
offset++;
} else if (curr == ch) {
return offset;
}
}
return endOffset;
}
private void smartIndentAfterClosingBracket(IDocument d, DocumentCommand c) {
if (c.offset == -1 || d.getLength() == 0)
return;
try {
int p= (c.offset == d.getLength() ? c.offset - 1 : c.offset);
int line= d.getLineOfOffset(p);
int start= d.getLineOffset(line);
int whiteend= findEndOfWhiteSpace(d, start, c.offset);
JavaHeuristicScanner scanner= new JavaHeuristicScanner(d);
JavaIndenter indenter= new JavaIndenter(d, scanner);
// shift only when line does not contain any text up to the closing bracket
if (whiteend == c.offset) {
// evaluate the line with the opening bracket that matches out closing bracket
int reference= indenter.findReferencePosition(c.offset, false, true, false, false);
int indLine= d.getLineOfOffset(reference);
if (indLine != -1 && indLine != line) {
// take the indent of the found line
StringBuffer replaceText= new StringBuffer(getIndentOfLine(d, indLine));
// add the rest of the current line including the just added close bracket
replaceText.append(d.get(whiteend, c.offset - whiteend));
replaceText.append(c.text);
// modify document command
c.length += c.offset - start;
c.offset= start;
c.text= replaceText.toString();
}
}
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
}
private void smartIndentAfterOpeningBracket(IDocument d, DocumentCommand c) {
if (c.offset < 1 || d.getLength() == 0)
return;
JavaHeuristicScanner scanner= new JavaHeuristicScanner(d);
int p= (c.offset == d.getLength() ? c.offset - 1 : c.offset);
try {
// current line
int line= d.getLineOfOffset(p);
int lineOffset= d.getLineOffset(line);
// line of last javacode
int pos= scanner.findNonWhitespaceBackward(p, JavaHeuristicScanner.UNBOUND);
if (pos == -1)
return;
int lastLine= d.getLineOfOffset(pos);
// only shift if the last java line is further up and is a braceless block candidate
if (lastLine < line) {
if (scanner.isBracelessBlockStart(pos + 1, JavaHeuristicScanner.UNBOUND)) {
// if the last line was a braceless block candidate, we have indented
// after the new line. This has to be undone as we *are* starting a block
// on the new line
StringBuffer replace= new StringBuffer(getIndentOfLine(d, lastLine));
c.length += replace.length();
replace.append(c.text);
c.offset= lineOffset;
c.text= replace.toString();
}
}
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
}
private void smartIndentAfterNewLine(IDocument d, DocumentCommand c) {
JavaHeuristicScanner scanner= new JavaHeuristicScanner(d);
JavaIndenter indenter= new JavaIndenter(d, scanner);
StringBuffer indent= indenter.computeIndentation(c.offset);
if (indent == null)
indent= new StringBuffer(); //$NON-NLS-1$
int docLength= d.getLength();
if (c.offset == -1 || docLength == 0)
return;
try {
int p= (c.offset == docLength ? c.offset - 1 : c.offset);
int line= d.getLineOfOffset(p);
StringBuffer buf= new StringBuffer(c.text + indent);
IRegion reg= d.getLineInformation(line);
int lineEnd= reg.getOffset() + reg.getLength();
int contentStart= findEndOfWhiteSpace(d, c.offset, lineEnd);
c.length= Math.max(contentStart - c.offset, 0);
int start= reg.getOffset();
ITypedRegion region= TextUtilities.getPartition(d, fPartitioning, start);
if (IJavaPartitions.JAVA_DOC.equals(region.getType()))
start= d.getLineInformationOfOffset(region.getOffset()).getOffset();
if (getBracketCount(d, start, c.offset, true) > 0 && closeBrace() && !isClosed(d, c.offset, c.length)) {
c.caretOffset= c.offset + buf.length();
c.shiftsCaret= false;
// copy old content of line behind insertion point to new line
// unless we think we are inserting an anonymous type definition
if (c.offset == 0 || !(computeAnonymousPosition(d, c.offset - 1, fPartitioning, lineEnd) != -1)) {
if (lineEnd - contentStart > 0) {
c.length= lineEnd - c.offset;
buf.append(d.get(contentStart, lineEnd - contentStart).toCharArray());
}
}
buf.append(getLineDelimiter(d));
StringBuffer reference= indenter.getReferenceIndentation(c.offset);
if (reference != null)
buf.append(reference);
buf.append('}');
}
c.text= buf.toString();
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
}
/**
* Computes an insert position for an opening brace if <code>offset</code> maps to a position in
* <code>document</code> with a expression in parenthesis that will take a block after the closing parenthesis.
*
* @param document the document being modified
* @param offset the offset of the caret position, relative to the line start.
* @param partitioning the document partitioning
* @param max the max position
* @return an insert position relative to the line start if <code>line</code> contains a parenthesized expression that can be followed by a block, -1 otherwise
*/
private static int computeAnonymousPosition(IDocument document, int offset, String partitioning, int max) {
// find the opening parenthesis for every closing parenthesis on the current line after offset
// return the position behind the closing parenthesis if it looks like a method declaration
// or an expression for an if, while, for, catch statement
JavaHeuristicScanner scanner= new JavaHeuristicScanner(document);
int pos= offset;
int length= max;
int scanTo= scanner.scanForward(pos, length, '}');
if (scanTo == -1)
scanTo= length;
int closingParen= findClosingParenToLeft(scanner, pos) - 1;
while (true) {
int startScan= closingParen + 1;
closingParen= scanner.scanForward(startScan, scanTo, ')');
if (closingParen == -1)
break;
int openingParen= scanner.findOpeningPeer(closingParen - 1, '(', ')');
// no way an expression at the beginning of the document can mean anything
if (openingParen < 1)
break;
// only select insert positions for parenthesis currently embracing the caret
if (openingParen > pos)
continue;
if (looksLikeAnonymousClassDef(document, partitioning, scanner, openingParen - 1))
return closingParen + 1;
}
return -1;
}
/**
* Finds a closing parenthesis to the left of <code>position</code> in document, where that parenthesis is only
* separated by whitespace from <code>position</code>. If no such parenthesis can be found, <code>position</code> is returned.
*
* @param document the document being modified
* @param position the first character position in <code>document</code> to be considered
* @param partitioning the document partitioning
* @return the position of a closing parenthesis left to <code>position</code> separated only by whitespace, or <code>position</code> if no parenthesis can be found
*/
private static int findClosingParenToLeft(JavaHeuristicScanner scanner, int position) {
if (position < 1)
return position;
if (scanner.previousToken(position - 1, JavaHeuristicScanner.UNBOUND) == Symbols.TokenRPAREN)
return scanner.getPosition() + 1;
return position;
}
/**
* Checks whether the content of <code>document</code> in the range (<code>offset</code>, <code>length</code>)
* contains the <code>new</code> keyword.
*
* @param document the document being modified
* @param offset the first character position in <code>document</code> to be considered
* @param length the length of the character range to be considered
* @param partitioning the document partitioning
* @return <code>true</code> if the specified character range contains a <code>new</code> keyword, <code>false</code> otherwise.
*/
private static boolean isNewMatch(IDocument document, int offset, int length, String partitioning) {
Assert.isTrue(length >= 0);
Assert.isTrue(offset >= 0);
Assert.isTrue(offset + length < document.getLength() + 1);
try {
String text= document.get(offset, length);
int pos= text.indexOf("new"); //$NON-NLS-1$
while (pos != -1 && !isDefaultPartition(document, pos + offset, partitioning))
pos= text.indexOf("new", pos + 2); //$NON-NLS-1$
if (pos < 0)
return false;
if (pos != 0 && Character.isJavaIdentifierPart(text.charAt(pos - 1)))
return false;
if (pos + 3 < length && Character.isJavaIdentifierPart(text.charAt(pos + 3)))
return false;
return true;
} catch (BadLocationException e) {
}
return false;
}
/**
* Checks whether the content of <code>document</code> at <code>position</code> looks like an
* anonymous class definition. <code>position</code> must be to the left of the opening
* parenthesis of the definition's parameter list.
*
* @param document the document being modified
* @param position the first character position in <code>document</code> to be considered
* @param partitioning the document partitioning
* @return <code>true</code> if the content of <code>document</code> looks like an anonymous class definition, <code>false</code> otherwise
*/
private static boolean looksLikeAnonymousClassDef(IDocument document, String partitioning, JavaHeuristicScanner scanner, int position) {
int previousCommaOrParen= scanner.scanBackward(position - 1, JavaHeuristicScanner.UNBOUND, new char[] {',', '('});
if (previousCommaOrParen == -1 || position < previousCommaOrParen + 5) // 2 for borders, 3 for "new"
return false;
if (isNewMatch(document, previousCommaOrParen + 1, position - previousCommaOrParen - 2, partitioning))
return true;
return false;
}
/**
* Checks whether <code>position</code> resides in a default (Java) partition of <code>document</code>.
*
* @param document the document being modified
* @param position the position to be checked
* @param partitioning the document partitioning
* @return <code>true</code> if <code>position</code> is in the default partition of <code>document</code>, <code>false</code> otherwise
*/
private static boolean isDefaultPartition(IDocument document, int position, String partitioning) {
Assert.isTrue(position >= 0);
Assert.isTrue(position <= document.getLength());
try {
ITypedRegion region= TextUtilities.getPartition(document, partitioning, position);
return region.getType().equals(IDocument.DEFAULT_CONTENT_TYPE);
} catch (BadLocationException e) {
}
return false;
}
private boolean isClosed(IDocument document, int offset, int length) {
CompilationUnitInfo info= getCompilationUnitForMethod(document, offset, fPartitioning);
if (info == null)
return false;
CompilationUnit compilationUnit= null;
try {
compilationUnit= AST.parseCompilationUnit(info.buffer);
} catch (ArrayIndexOutOfBoundsException x) {
// work around for parser problem
return false;
}
IProblem[] problems= compilationUnit.getProblems();
for (int i= 0; i != problems.length; ++i) {
if (problems[i].getID() == IProblem.UnmatchedBracket)
return true;
}
final int relativeOffset= offset - info.delta;
ASTNode node= NodeFinder.perform(compilationUnit, relativeOffset, length);
if (node == null)
return false;
if (length == 0) {
while (node != null && (relativeOffset == node.getStartPosition() || relativeOffset == node.getStartPosition() + node.getLength()))
node= node.getParent();
}
switch (node.getNodeType()) {
case ASTNode.BLOCK:
return areBlocksConsistent(document, offset, fPartitioning);
case ASTNode.IF_STATEMENT:
{
IfStatement ifStatement= (IfStatement) node;
Expression expression= ifStatement.getExpression();
IRegion expressionRegion= createRegion(expression, info.delta);
Statement thenStatement= ifStatement.getThenStatement();
IRegion thenRegion= createRegion(thenStatement, info.delta);
// between expression and then statement
if (expressionRegion.getOffset() + expressionRegion.getLength() <= offset && offset + length <= thenRegion.getOffset())
return thenStatement != null;
Statement elseStatement= ifStatement.getElseStatement();
IRegion elseRegion= createRegion(elseStatement, info.delta);
IRegion elseToken= null;
if (elseStatement != null) {
int sourceOffset= thenRegion.getOffset() + thenRegion.getLength();
int sourceLength= elseRegion.getOffset() - sourceOffset;
elseToken= getToken(document, new Region(sourceOffset, sourceLength), ITerminalSymbols.TokenNameelse);
}
// between 'else' keyword and else statement
if (elseToken.getOffset() + elseToken.getLength() <= offset && offset + length < elseRegion.getOffset())
return elseStatement != null;
}
break;
case ASTNode.WHILE_STATEMENT:
case ASTNode.FOR_STATEMENT:
{
Expression expression= node.getNodeType() == ASTNode.WHILE_STATEMENT ? ((WhileStatement) node).getExpression() : ((ForStatement) node).getExpression();
IRegion expressionRegion= createRegion(expression, info.delta);
Statement body= node.getNodeType() == ASTNode.WHILE_STATEMENT ? ((WhileStatement) node).getBody() : ((ForStatement) node).getBody();
IRegion bodyRegion= createRegion(body, info.delta);
// between expression and body statement
if (expressionRegion.getOffset() + expressionRegion.getLength() <= offset && offset + length <= bodyRegion.getOffset())
return body != null;
}
break;
case ASTNode.DO_STATEMENT:
{
DoStatement doStatement= (DoStatement) node;
IRegion doRegion= createRegion(doStatement, info.delta);
Statement body= doStatement.getBody();
IRegion bodyRegion= createRegion(body, info.delta);
if (doRegion.getOffset() + doRegion.getLength() <= offset && offset + length <= bodyRegion.getOffset())
return body != null;
}
break;
}
return true;
}
private static String getLineDelimiter(IDocument document) {
try {
if (document.getNumberOfLines() > 1)
return document.getLineDelimiter(0);
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
return System.getProperty("line.separator"); //$NON-NLS-1$
}
/**
* @param document
*/
private static void installJavaStuff(Document document) {
String[] types= new String[] {
IJavaPartitions.JAVA_DOC,
IJavaPartitions.JAVA_MULTI_LINE_COMMENT,
IJavaPartitions.JAVA_SINGLE_LINE_COMMENT,
IJavaPartitions.JAVA_STRING,
IJavaPartitions.JAVA_CHARACTER,
IDocument.DEFAULT_CONTENT_TYPE
};
DefaultPartitioner partitioner= new DefaultPartitioner(new FastJavaPartitionScanner(), types);
partitioner.connect(document);
document.setDocumentPartitioner(IJavaPartitions.JAVA_PARTITIONING, partitioner);
}
private static void smartPaste(IDocument document, DocumentCommand command) {
try {
JavaHeuristicScanner scanner= new JavaHeuristicScanner(document);
JavaIndenter indenter= new JavaIndenter(document, scanner);
int offset= command.offset;
// reference position to get the indent from
int refPos= indenter.findReferencePosition(offset);
if (refPos == JavaHeuristicScanner.NOT_FOUND)
return;
int peerPos= getPeerPosition(document, command);
peerPos= indenter.findReferencePosition(peerPos);
refPos= Math.min(refPos, peerPos);
IRegion region= document.getLineInformationOfOffset(refPos);
int lineOffset= region.getOffset();
// get the base indentation from the reference position
int endOfWS= scanner.findNonWhitespaceForwardInAnyPartition(lineOffset, JavaHeuristicScanner.UNBOUND);
if (endOfWS == JavaHeuristicScanner.NOT_FOUND)
endOfWS= lineOffset;
String baseIndent= document.get(lineOffset, endOfWS - lineOffset);
if (refPos == JavaHeuristicScanner.NOT_FOUND)
return;
// eat any WS before the insertion to the beginning of the line
region= document.getLineInformationOfOffset(offset);
String notSelected= document.get(region.getOffset(), offset - region.getOffset());
if (notSelected.trim().length() == 0) {
command.length += notSelected.length();
command.offset= region.getOffset();
}
// prefix: the part we need for formatting but won't paste
String prefix= baseIndent + document.get(refPos, command.offset - refPos);
Document temp= new Document(prefix + command.text);
// eat any WS after the insertion, up to the delimiter, if the pasted text ends with
// a newline (with optional WS on the new line).
region= temp.getLineInformation(temp.getNumberOfLines() - 1);
boolean eatAfterSpace= temp.get(region.getOffset(), region.getLength()).trim().length() == 0;
String afterContent= new String();
if (eatAfterSpace) {
int selectionEnd= command.offset + command.length;
region= document.getLineInformationOfOffset(selectionEnd);
endOfWS= scanner.findNonWhitespaceForwardInAnyPartition(selectionEnd, region.getOffset() + region.getLength());
if (endOfWS != JavaHeuristicScanner.NOT_FOUND) {
int token= scanner.nextToken(selectionEnd, region.getOffset() + region.getLength());
if (token != Symbols.TokenEOF && token != Symbols.TokenCASE) { // doesn't work nicely with case
command.length += endOfWS - selectionEnd;
afterContent= document.get(endOfWS, scanner.getPosition() - endOfWS);
}
} else {
// simulate something to get the indentation
command.length += region.getOffset() + region.getLength() - selectionEnd;
afterContent= "x"; //$NON-NLS-1$
}
}
// add context behind the insertion
temp.replace(temp.getLength(), 0, afterContent);
scanner= new JavaHeuristicScanner(temp);
indenter= new JavaIndenter(temp, scanner);
installJavaStuff(temp);
int lines= temp.getNumberOfLines();
for (int l= document.computeNumberOfLines(prefix); l < lines; l++) { // we don't change the number of lines while adding indents
IRegion r= temp.getLineInformation(l);
lineOffset= r.getOffset();
int lineLength= r.getLength();
if (lineLength == 0) // don't format empty lines
continue;
if (lineOffset < temp.getLength() - 1) {
// special single line comment handling: if comment starts at the start of the line, leave it alone.
String s= temp.get(lineOffset, 2);
if ("//".equals(s)) { //$NON-NLS-1$
continue;
}
}
StringBuffer indent= indenter.computeIndentation(lineOffset);
if (indent == null) // bail out
return;
// add single character for *-ed multiline comments
ITypedRegion partition= temp.getPartition(IJavaPartitions.JAVA_PARTITIONING, lineOffset);
String type= partition.getType();
if (type.equals(IJavaPartitions.JAVA_DOC) || type.equals(IJavaPartitions.JAVA_MULTI_LINE_COMMENT))
if (partition.getOffset() != lineOffset) // not for first line
indent.append(' ');
endOfWS= scanner.findNonWhitespaceForwardInAnyPartition(lineOffset, lineOffset + lineLength);
if (endOfWS == JavaHeuristicScanner.NOT_FOUND)
endOfWS= lineOffset + lineLength;
int wsLen= Math.max(endOfWS - lineOffset, 0);
temp.replace(lineOffset, wsLen, indent.toString());
}
temp.setDocumentPartitioner(IJavaPartitions.JAVA_PARTITIONING, null);
command.text= temp.get(prefix.length(), temp.getLength() - prefix.length() - afterContent.length());
} catch (BadLocationException e) {
JavaPlugin.log(e);
} catch (BadPartitioningException e) {
JavaPlugin.log(e);
}
}
private static int getPeerPosition(IDocument document, DocumentCommand command) {
/*
* Search for scope closers in the pasted text and find their opening peers
* in the document.
*/
Document pasted= new Document(command.text);
installJavaStuff(pasted);
int firstPeer= command.offset;
JavaHeuristicScanner pScanner= new JavaHeuristicScanner(pasted);
JavaHeuristicScanner dScanner= new JavaHeuristicScanner(document);
// add scope relevant after context to peer search
int afterToken= dScanner.nextToken(command.offset + command.length, JavaHeuristicScanner.UNBOUND);
try {
switch (afterToken) {
case Symbols.TokenRBRACE:
pasted.replace(pasted.getLength(), 0, "}"); //$NON-NLS-1$
break;
case Symbols.TokenRPAREN:
pasted.replace(pasted.getLength(), 0, ")"); //$NON-NLS-1$
break;
case Symbols.TokenRBRACKET:
pasted.replace(pasted.getLength(), 0, "]"); //$NON-NLS-1$
break;
}
} catch (BadLocationException e) {
// cannot happen
Assert.isTrue(false);
}
int pPos= 0; // paste text position (increasing from 0)
int dPos= Math.max(0, command.offset - 1); // document position (decreasing from paste offset)
while (true) {
int token= pScanner.nextToken(pPos, JavaHeuristicScanner.UNBOUND);
pPos= pScanner.getPosition();
switch (token) {
case Symbols.TokenLBRACE:
case Symbols.TokenLBRACKET:
case Symbols.TokenLPAREN:
pPos= skipScope(pScanner, pPos, token);
if (pPos == JavaHeuristicScanner.NOT_FOUND)
return firstPeer;
break; // closed scope -> keep searching
case Symbols.TokenRBRACE:
int peer= dScanner.findOpeningPeer(dPos, '{', '}');
dPos= peer - 1;
if (peer == JavaHeuristicScanner.NOT_FOUND)
return firstPeer;
firstPeer= peer;
break; // keep searching
case Symbols.TokenRBRACKET:
peer= dScanner.findOpeningPeer(dPos, '[', ']');
dPos= peer - 1;
if (peer == JavaHeuristicScanner.NOT_FOUND)
return firstPeer;
firstPeer= peer;
break; // keep searching
case Symbols.TokenRPAREN:
peer= dScanner.findOpeningPeer(dPos, '(', ')');
dPos= peer - 1;
if (peer == JavaHeuristicScanner.NOT_FOUND)
return firstPeer;
firstPeer= peer;
break; // keep searching
case Symbols.TokenCASE:
case Symbols.TokenDEFAULT:
JavaIndenter indenter= new JavaIndenter(document, dScanner);
peer= indenter.findReferencePosition(dPos, false, false, false, true);
if (peer == JavaHeuristicScanner.NOT_FOUND)
return firstPeer;
firstPeer= peer;
break; // keep searching
case Symbols.TokenEOF:
return firstPeer;
default:
// keep searching
}
}
}
/**
* Skips the scope opened by <code>token</code> in <code>document</code>,
* returns either the position of the
* @param pos
* @param token
* @return
*/
private static int skipScope(JavaHeuristicScanner scanner, int pos, int token) {
int openToken= token;
int closeToken;
switch (token) {
case Symbols.TokenLPAREN:
closeToken= Symbols.TokenRPAREN;
break;
case Symbols.TokenLBRACKET:
closeToken= Symbols.TokenRBRACKET;
break;
case Symbols.TokenLBRACE:
closeToken= Symbols.TokenRBRACE;
break;
default:
Assert.isTrue(false);
return -1; // dummy
}
int depth= 1;
int p= pos;
while (true) {
int tok= scanner.nextToken(p, JavaHeuristicScanner.UNBOUND);
p= scanner.getPosition();
if (tok == openToken) {
depth++;
} else if (tok == closeToken) {
depth--;
if (depth == 0)
return p + 1;
} else if (tok == Symbols.TokenEOF) {
return JavaHeuristicScanner.NOT_FOUND;
}
}
}
private boolean isLineDelimiter(IDocument document, String text) {
String[] delimiters= document.getLegalLineDelimiters();
if (delimiters != null)
return TextUtilities.equals(delimiters, text) > -1;
return false;
}
private void smartIndentAfterBlockDelimiter(IDocument document, DocumentCommand command) {
if (command.text.charAt(0) == '}')
smartIndentAfterClosingBracket(document, command);
else if (command.text.charAt(0) == '{')
smartIndentAfterOpeningBracket(document, command);
}
/*
* @see org.eclipse.jface.text.IAutoIndentStrategy#customizeDocumentCommand(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.DocumentCommand)
*/
public void customizeDocumentCommand(IDocument d, DocumentCommand c) {
clearCachedValues();
if (!isSmartMode() || c.doit == false)
return;
if (c.length == 0 && c.text != null && isLineDelimiter(d, c.text))
smartIndentAfterNewLine(d, c);
else if (c.text.length() == 1)
smartIndentAfterBlockDelimiter(d, c);
else if (c.text.length() > 1 && getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SMART_PASTE))
smartPaste(d, c);
}
private static IPreferenceStore getPreferenceStore() {
return JavaPlugin.getDefault().getPreferenceStore();
}
private boolean closeBrace() {
return fCloseBrace;
}
private boolean isSmartMode() {
return fIsSmartMode;
}
private void clearCachedValues() {
IPreferenceStore preferenceStore= getPreferenceStore();
fCloseBrace= preferenceStore.getBoolean(PreferenceConstants.EDITOR_CLOSE_BRACES);
fIsSmartMode= computeSmartMode();
}
private boolean computeSmartMode() {
IWorkbenchPage page= JavaPlugin.getActivePage();
if (page != null) {
IEditorPart part= page.getActiveEditor();
if (part instanceof ITextEditorExtension3) {
ITextEditorExtension3 extension= (ITextEditorExtension3) part;
return extension.getInsertMode() == ITextEditorExtension3.SMART_INSERT;
}
}
return false;
}
private static CompilationUnitInfo getCompilationUnitForMethod(IDocument document, int offset, String partitioning) {
try {
JavaHeuristicScanner scanner= new JavaHeuristicScanner(document);
IRegion sourceRange= scanner.findSurroundingBlock(offset);
if (sourceRange == null)
return null;
String source= document.get(sourceRange.getOffset(), sourceRange.getLength());
StringBuffer contents= new StringBuffer();
contents.append("class ____C{void ____m()"); //$NON-NLS-1$
final int methodOffset= contents.length();
contents.append(source);
contents.append('}');
char[] buffer= contents.toString().toCharArray();
return new CompilationUnitInfo(buffer, sourceRange.getOffset() - methodOffset);
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
return null;
}
private static boolean areBlocksConsistent(IDocument document, int offset, String partitioning) {
if (offset < 1 || offset >= document.getLength())
return false;
int begin= offset;
int end= offset - 1;
JavaHeuristicScanner scanner= new JavaHeuristicScanner(document);
while (true) {
begin= scanner.findOpeningPeer(begin - 1, '{', '}');
end= scanner.findClosingPeer(end + 1, '{', '}');
if (begin == -1 && end == -1)
return true;
if (begin == -1 || end == -1)
return false;
}
}
private static IRegion createRegion(ASTNode node, int delta) {
return node == null ? null : new Region(node.getStartPosition() + delta, node.getLength());
}
private static IRegion getToken(IDocument document, IRegion scanRegion, int tokenId) {
try {
final String source= document.get(scanRegion.getOffset(), scanRegion.getLength());
IScanner scanner= ToolFactory.createScanner(false, false, false, false);
scanner.setSource(source.toCharArray());
int id= scanner.getNextToken();
while (id != ITerminalSymbols.TokenNameEOF && id != tokenId)
id= scanner.getNextToken();
if (id == ITerminalSymbols.TokenNameEOF)
return null;
int tokenOffset= scanner.getCurrentTokenStartPosition();
int tokenLength= scanner.getCurrentTokenEndPosition() + 1 - tokenOffset; // inclusive end
return new Region(tokenOffset + scanRegion.getOffset(), tokenLength);
} catch (InvalidInputException x) {
return null;
} catch (BadLocationException x) {
return null;
}
}
}
|
49,655 |
Bug 49655 StringIndexOutOfBoundsException on test failure [JUnit]
|
While testing the move to Ant 1.6.0 I was adjusting the org.eclipse.ant.core test suite (it had failures). I was reliably getting the following exception when test failures occurred: java.lang.StringIndexOutOfBoundsException: String index out of range: -1 at java.lang.String.substring(String.java:1444) at org.eclipse.jdt.internal.junit.ui.TestRunnerViewPart.testFailed (TestRunnerViewPart.java:524) at org.eclipse.jdt.internal.junit.ui.RemoteTestRunnerClient$7.run (RemoteTestRunnerClient.java:477) at org.eclipse.core.internal.runtime.InternalPlatform.run (InternalPlatform.java:813) at org.eclipse.core.runtime.Platform.run(Platform.java:457) at org.eclipse.jdt.internal.junit.ui.RemoteTestRunnerClient.notifyTestFailed (RemoteTestRunnerClient.java:474) at org.eclipse.jdt.internal.junit.ui.RemoteTestRunnerClient.access$16 (RemoteTestRunnerClient.java:471) at org.eclipse.jdt.internal.junit.ui.RemoteTestRunnerClient$TraceProcessingState.r eadMessage(RemoteTestRunnerClient.java:125) at org.eclipse.jdt.internal.junit.ui.RemoteTestRunnerClient.receiveMessage (RemoteTestRunnerClient.java:309) at org.eclipse.jdt.internal.junit.ui.RemoteTestRunnerClient.access$30 (RemoteTestRunnerClient.java:308) at org.eclipse.jdt.internal.junit.ui.RemoteTestRunnerClient$ServerConnection.run (RemoteTestRunnerClient.java:235)
|
resolved fixed
|
fd62ecd
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-07T23:31:04Z | 2004-01-07T21:13:20Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/TestRunnerViewPart.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Julien Ruaux: [email protected] see bug 25324 Ability to know when tests are finished [junit]
* Vincent Massol: [email protected] 25324 Ability to know when tests are finished [junit]
* Sebastian Davids: [email protected] 35762 JUnit View wasting a lot of screen space [JUnit]
******************************************************************************/
package org.eclipse.jdt.internal.junit.ui;
import java.net.MalformedURLException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.debug.ui.DebugUITools;
import org.eclipse.jdt.core.ElementChangedEvent;
import org.eclipse.jdt.core.IElementChangedListener;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaElementDelta;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.internal.junit.launcher.JUnitBaseLaunchConfiguration;
import org.eclipse.jdt.junit.ITestRunListener;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.ViewForm;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorActionBarContributor;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.EditorActionBarContributor;
import org.eclipse.ui.part.ViewPart;
/**
* A ViewPart that shows the results of a test run.
*/
public class TestRunnerViewPart extends ViewPart implements ITestRunListener3, IPropertyChangeListener {
public static final String NAME= "org.eclipse.jdt.junit.ResultView"; //$NON-NLS-1$
/**
* Number of executed tests during a test run
*/
protected int fExecutedTests;
/**
* Number of errors during this test run
*/
protected int fErrorCount;
/**
* Number of failures during this test run
*/
protected int fFailureCount;
/**
* Number of tests run
*/
private int fTestCount;
/**
* Whether the output scrolls and reveals tests as they are executed.
*/
private boolean fAutoScroll = true;
/**
* The current orientation; either <code>VIEW_ORIENTATION_HORIZONTAL</code>
* or <code>VIEW_ORIENTATION_VERTICAL</code>.
*/
private int fCurrentOrientation;
/**
* Map storing TestInfos for each executed test keyed by
* the test name.
*/
private Map fTestInfos= new HashMap();
/**
* The first failure of a test run. Used to reveal the
* first failed tests at the end of a run.
*/
private List fFailures= new ArrayList();
private JUnitProgressBar fProgressBar;
private ProgressImages fProgressImages;
private Image fViewImage;
private CounterPanel fCounterPanel;
private boolean fShowOnErrorOnly= false;
private Clipboard fClipboard;
/**
* The view that shows the stack trace of a failure
*/
private FailureTraceView fFailureView;
/**
* The collection of ITestRunViews
*/
private Vector fTestRunViews = new Vector();
/**
* The currently active run view
*/
private ITestRunView fActiveRunView;
/**
* Is the UI disposed
*/
private boolean fIsDisposed= false;
/**
* The launched project
*/
private IJavaProject fTestProject;
/**
* The launcher that has started the test
*/
private String fLaunchMode;
private ILaunch fLastLaunch;
/**
* Actions
*/
private Action fRerunLastTestAction;
private ScrollLockAction fScrollLockAction;
private ToggleOrientationAction[] fToggleOrientationActions;
/**
* The client side of the remote test runner
*/
private RemoteTestRunnerClient fTestRunnerClient;
final Image fStackViewIcon= TestRunnerViewPart.createImage("cview16/stackframe.gif");//$NON-NLS-1$
final Image fTestRunOKIcon= TestRunnerViewPart.createImage("cview16/junitsucc.gif"); //$NON-NLS-1$
final Image fTestRunFailIcon= TestRunnerViewPart.createImage("cview16/juniterr.gif"); //$NON-NLS-1$
final Image fTestRunOKDirtyIcon= TestRunnerViewPart.createImage("cview16/junitsuccq.gif"); //$NON-NLS-1$
final Image fTestRunFailDirtyIcon= TestRunnerViewPart.createImage("cview16/juniterrq.gif"); //$NON-NLS-1$
// Persistance tags.
static final String TAG_PAGE= "page"; //$NON-NLS-1$
static final String TAG_RATIO= "ratio"; //$NON-NLS-1$
static final String TAG_TRACEFILTER= "tracefilter"; //$NON-NLS-1$
static final String VIEWORIENTATION= "orientation"; //$NON-NLS-1$
//orientations
static final int VIEW_ORIENTATION_VERTICAL= 0;
static final int VIEW_ORIENTATION_HORIZONTAL= 1;
private IMemento fMemento;
Image fOriginalViewImage;
IElementChangedListener fDirtyListener;
private CTabFolder fTabFolder;
private SashForm fSashForm;
private Action fNextAction;
private Action fPreviousAction;
private Composite fCounterComposite;
private Composite fParent;
private class StopAction extends Action {
public StopAction() {
setText(JUnitMessages.getString("TestRunnerViewPart.stopaction.text"));//$NON-NLS-1$
setToolTipText(JUnitMessages.getString("TestRunnerViewPart.stopaction.tooltip"));//$NON-NLS-1$
setDisabledImageDescriptor(JUnitPlugin.getImageDescriptor("dlcl16/stop.gif")); //$NON-NLS-1$
setHoverImageDescriptor(JUnitPlugin.getImageDescriptor("clcl16/stop.gif")); //$NON-NLS-1$
setImageDescriptor(JUnitPlugin.getImageDescriptor("elcl16/stop.gif")); //$NON-NLS-1$
}
public void run() {
stopTest();
}
}
private class RerunLastAction extends Action {
public RerunLastAction() {
setText(JUnitMessages.getString("TestRunnerViewPart.rerunaction.label")); //$NON-NLS-1$
setToolTipText(JUnitMessages.getString("TestRunnerViewPart.rerunaction.tooltip")); //$NON-NLS-1$
setDisabledImageDescriptor(JUnitPlugin.getImageDescriptor("dlcl16/relaunch.gif")); //$NON-NLS-1$
setHoverImageDescriptor(JUnitPlugin.getImageDescriptor("clcl16/relaunch.gif")); //$NON-NLS-1$
setImageDescriptor(JUnitPlugin.getImageDescriptor("elcl16/relaunch.gif")); //$NON-NLS-1$
}
public void run(){
rerunTestRun();
}
}
private class ToggleOrientationAction extends Action {
private final int fOrientation;
public ToggleOrientationAction(TestRunnerViewPart v, int orientation) {
super("", AS_RADIO_BUTTON); //$NON-NLS-1$
if (orientation == TestRunnerViewPart.VIEW_ORIENTATION_HORIZONTAL) {
setText(JUnitMessages.getString("TestRunnerViewPart.toggle.horizontal.label")); //$NON-NLS-1$
setDisabledImageDescriptor(JUnitPlugin.getImageDescriptor("dlcl16/th_horizontal.gif")); //$NON-NLS-1$
setHoverImageDescriptor(JUnitPlugin.getImageDescriptor("clcl16/th_horizontal.gif")); //$NON-NLS-1$
setImageDescriptor(JUnitPlugin.getImageDescriptor("elcl16/th_horizontal.gif")); //$NON-NLS-1$
} else if (orientation == TestRunnerViewPart.VIEW_ORIENTATION_VERTICAL) {
setText(JUnitMessages.getString("TestRunnerViewPart.toggle.vertical.label")); //$NON-NLS-1$
setDisabledImageDescriptor(JUnitPlugin.getImageDescriptor("dlcl16/th_vertical.gif")); //$NON-NLS-1$
setHoverImageDescriptor(JUnitPlugin.getImageDescriptor("clcl16/th_vertical.gif")); //$NON-NLS-1$
setImageDescriptor(JUnitPlugin.getImageDescriptor("elcl16/th_vertical.gif")); //$NON-NLS-1$
}
fOrientation= orientation;
WorkbenchHelp.setHelp(this, IJUnitHelpContextIds.RESULTS_VIEW_TOGGLE_ORIENTATION_ACTION);
}
public int getOrientation() {
return fOrientation;
}
public void run() {
if (fCurrentOrientation == fOrientation)
return;
setOrientation(fOrientation);
}
}
/**
* Listen for for modifications to Java elements
*/
private class DirtyListener implements IElementChangedListener {
public void elementChanged(ElementChangedEvent event) {
processDelta(event.getDelta());
}
private boolean processDelta(IJavaElementDelta delta) {
int kind= delta.getKind();
int details= delta.getFlags();
int type= delta.getElement().getElementType();
switch (type) {
// Consider containers for class files.
case IJavaElement.JAVA_MODEL:
case IJavaElement.JAVA_PROJECT:
case IJavaElement.PACKAGE_FRAGMENT_ROOT:
case IJavaElement.PACKAGE_FRAGMENT:
// If we did some different than changing a child we flush the the undo / redo stack.
if (kind != IJavaElementDelta.CHANGED || details != IJavaElementDelta.F_CHILDREN) {
codeHasChanged();
return false;
}
break;
case IJavaElement.COMPILATION_UNIT:
// if we have changed a primary working copy (e.g created, removed, ...)
// then we do nothing.
if ((details & IJavaElementDelta.F_PRIMARY_WORKING_COPY) != 0)
return true;
codeHasChanged();
return false;
case IJavaElement.CLASS_FILE:
// Don't examine children of a class file but keep on examining siblings.
return true;
default:
codeHasChanged();
return false;
}
IJavaElementDelta[] affectedChildren= delta.getAffectedChildren();
if (affectedChildren == null)
return true;
for (int i= 0; i < affectedChildren.length; i++) {
if (!processDelta(affectedChildren[i]))
return false;
}
return true;
}
}
public void init(IViewSite site, IMemento memento) throws PartInitException {
super.init(site, memento);
fMemento= memento;
}
private void restoreLayoutState(IMemento memento) {
Integer page= memento.getInteger(TAG_PAGE);
if (page != null) {
int p= page.intValue();
fTabFolder.setSelection(p);
fActiveRunView= (ITestRunView)fTestRunViews.get(p);
}
Integer ratio= memento.getInteger(TAG_RATIO);
if (ratio != null)
fSashForm.setWeights(new int[] { ratio.intValue(), 1000 - ratio.intValue()} );
Integer orientation= memento.getInteger(VIEWORIENTATION);
if (orientation != null)
setOrientation(orientation.intValue());
}
/**
* Stops the currently running test and shuts down the RemoteTestRunner
*/
public void stopTest() {
if (fTestRunnerClient != null)
fTestRunnerClient.stopTest();
}
/**
* Stops the currently running test and shuts down the RemoteTestRunner
*/
public void rerunTestRun() {
if (fLastLaunch != null && fLastLaunch.getLaunchConfiguration() != null) {
try {
DebugUITools.saveAndBuildBeforeLaunch();
fLastLaunch.getLaunchConfiguration().launch(fLastLaunch.getLaunchMode(), null);
} catch (CoreException e) {
ErrorDialog.openError(getSite().getShell(),
JUnitMessages.getString("TestRunnerViewPart.error.cannotrerun"), e.getMessage(), e.getStatus() //$NON-NLS-1$
);
}
}
}
public void setAutoScroll(boolean scroll) {
fAutoScroll = scroll;
}
public boolean isAutoScroll() {
return fAutoScroll;
}
/*
* @see ITestRunListener#testRunStarted(testCount)
*/
public void testRunStarted(final int testCount){
reset(testCount);
fShowOnErrorOnly= JUnitPreferencePage.getShowOnErrorOnly();
fExecutedTests++;
}
public void selectNextFailure() {
fActiveRunView.selectNext();
}
public void selectPreviousFailure() {
fActiveRunView.selectPrevious();
}
public void showTest(TestRunInfo test) {
fActiveRunView.setSelectedTest(test.getTestId());
handleTestSelected(test.getTestId());
new OpenTestAction(this, test.getClassName(), test.getTestMethodName()).run();
}
public void reset(){
reset(0);
setViewPartTitle(null);
clearStatus();
resetViewIcon();
}
/*
* @see ITestRunListener#testRunEnded
*/
public void testRunEnded(long elapsedTime){
fExecutedTests--;
String[] keys= {elapsedTimeAsString(elapsedTime), String.valueOf(fErrorCount), String.valueOf(fFailureCount)};
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.finish", keys); //$NON-NLS-1$
if (hasErrorsOrFailures())
postError(msg);
else
postInfo(msg);
postSyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
if (fFailures.size() > 0) {
selectFirstFailure();
}
updateViewIcon();
if (fDirtyListener == null) {
fDirtyListener= new DirtyListener();
JavaCore.addElementChangedListener(fDirtyListener);
}
}
});
}
protected void selectFirstFailure() {
TestRunInfo firstFailure= (TestRunInfo)fFailures.get(0);
if (firstFailure != null && fAutoScroll) {
fActiveRunView.setSelectedTest(firstFailure.getTestId());
handleTestSelected(firstFailure.getTestId());
}
}
private void updateViewIcon() {
if (hasErrorsOrFailures())
fViewImage= fTestRunFailIcon;
else
fViewImage= fTestRunOKIcon;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
private boolean hasErrorsOrFailures() {
return fErrorCount+fFailureCount > 0;
}
private String elapsedTimeAsString(long runTime) {
return NumberFormat.getInstance().format((double)runTime/1000);
}
/*
* @see ITestRunListener#testRunStopped
*/
public void testRunStopped(final long elapsedTime) {
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.stopped", elapsedTimeAsString(elapsedTime)); //$NON-NLS-1$
postInfo(msg);
postSyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
resetViewIcon();
}
});
}
private void resetViewIcon() {
fViewImage= fOriginalViewImage;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
/*
* @see ITestRunListener#testRunTerminated
*/
public void testRunTerminated() {
String msg= JUnitMessages.getString("TestRunnerViewPart.message.terminated"); //$NON-NLS-1$
showMessage(msg);
}
private void showMessage(String msg) {
showInformation(msg);
postError(msg);
}
/*
* @see ITestRunListener#testStarted
*/
public void testStarted(String testId, String testName) {
postStartTest(testId, testName);
// reveal the part when the first test starts
if (!fShowOnErrorOnly && fExecutedTests == 1)
postShowTestResultsView();
TestRunInfo testInfo= getTestInfo(testId);
if (testInfo == null) {
testInfo= new TestRunInfo(testId, testName);
fTestInfos.put(testId, testInfo);
}
String className= testInfo.getClassName();
String method= testInfo.getTestMethodName();
String status= JUnitMessages.getFormattedString("TestRunnerViewPart.message.started", new String[] { className, method }); //$NON-NLS-1$
postInfo(status);
}
/*
* @see ITestRunListener#testEnded
*/
public void testEnded(String testId, String testName){
postEndTest(testId, testName);
fExecutedTests++;
}
/*
* @see ITestRunListener#testFailed
*/
public void testFailed(int status, String testId, String testName, String trace){
testFailed(status, testId, testName, trace, null, null);
}
/*
* @see ITestRunListener#testFailed
*/
public void testFailed(int status, String testId, String testName, String trace, String expected, String actual){
TestRunInfo testInfo= getTestInfo(testId);
if (testInfo == null) {
testInfo= new TestRunInfo(testId, testName);
fTestInfos.put(testName, testInfo);
}
testInfo.setTrace(trace);
testInfo.setStatus(status);
if (expected != null)
testInfo.setExpected(expected.substring(0, expected.length()-1));
if (actual != null)
testInfo.setActual(actual.substring(0, actual.length()-1));
if (status == ITestRunListener.STATUS_ERROR)
fErrorCount++;
else
fFailureCount++;
fFailures.add(testInfo);
// show the view on the first error only
if (fShowOnErrorOnly && (fErrorCount + fFailureCount == 1))
postShowTestResultsView();
}
/*
* @see ITestRunListener#testReran
*/
public void testReran(String testId, String className, String testName, int status, String trace) {
if (status == ITestRunListener.STATUS_ERROR) {
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.error", new String[]{testName, className}); //$NON-NLS-1$
postError(msg);
} else if (status == ITestRunListener.STATUS_FAILURE) {
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.failure", new String[]{testName, className}); //$NON-NLS-1$
postError(msg);
} else {
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.success", new String[]{testName, className}); //$NON-NLS-1$
postInfo(msg);
}
TestRunInfo info= getTestInfo(testId);
updateTest(info, status);
if (info.getTrace() == null || !info.getTrace().equals(trace)) {
info.setTrace(trace);
showFailure(info);
}
}
private void updateTest(TestRunInfo info, final int status) {
if (status == info.getStatus())
return;
if (info.getStatus() == ITestRunListener.STATUS_OK) {
if (status == ITestRunListener.STATUS_FAILURE)
fFailureCount++;
else if (status == ITestRunListener.STATUS_ERROR)
fErrorCount++;
} else if (info.getStatus() == ITestRunListener.STATUS_ERROR) {
if (status == ITestRunListener.STATUS_OK)
fErrorCount--;
else if (status == ITestRunListener.STATUS_FAILURE) {
fErrorCount--;
fFailureCount++;
}
} else if (info.getStatus() == ITestRunListener.STATUS_FAILURE) {
if (status == ITestRunListener.STATUS_OK)
fFailureCount--;
else if (status == ITestRunListener.STATUS_ERROR) {
fFailureCount--;
fErrorCount++;
}
}
info.setStatus(status);
final TestRunInfo finalInfo= info;
postSyncRunnable(new Runnable() {
public void run() {
refreshCounters();
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.testStatusChanged(finalInfo);
}
}
});
}
/*
* @see ITestRunListener#testTreeEntry
*/
public void testTreeEntry(final String treeEntry){
postSyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.newTreeEntry(treeEntry);
}
}
});
}
public void startTestRunListening(IJavaElement type, int port, ILaunch launch) {
fTestProject= type.getJavaProject();
fLaunchMode= launch.getLaunchMode();
aboutToLaunch();
if (fTestRunnerClient != null) {
stopTest();
}
fTestRunnerClient= new RemoteTestRunnerClient();
// add the TestRunnerViewPart to the list of registered listeners
List listeners= JUnitPlugin.getDefault().getTestRunListeners();
ITestRunListener[] listenerArray= new ITestRunListener[listeners.size()+1];
listeners.toArray(listenerArray);
System.arraycopy(listenerArray, 0, listenerArray, 1, listenerArray.length-1);
listenerArray[0]= this;
fTestRunnerClient.startListening(listenerArray, port);
fLastLaunch= launch;
setViewPartTitle(type);
if (type instanceof IType)
setTitleToolTip(((IType)type).getFullyQualifiedName());
else
setTitleToolTip(type.getElementName());
}
private void setViewPartTitle(IJavaElement type) {
String title;
if (type == null)
title= JUnitMessages.getString("TestRunnerViewPart.title_no_type"); //$NON-NLS-1$
else
title= JUnitMessages.getFormattedString("TestRunnerViewPart.title", type.getElementName()); //$NON-NLS-1$
setTitle(title);
}
private void aboutToLaunch() {
String msg= JUnitMessages.getString("TestRunnerViewPart.message.launching"); //$NON-NLS-1$
showInformation(msg);
postInfo(msg);
fViewImage= fOriginalViewImage;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
public synchronized void dispose(){
fIsDisposed= true;
stopTest();
if (fProgressImages != null)
fProgressImages.dispose();
JUnitPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(this);
fTestRunOKIcon.dispose();
fTestRunFailIcon.dispose();
fStackViewIcon.dispose();
fTestRunOKDirtyIcon.dispose();
fTestRunFailDirtyIcon.dispose();
if (fClipboard != null)
fClipboard.dispose();
}
private void start(final int total) {
resetProgressBar(total);
fCounterPanel.setTotal(total);
fCounterPanel.setRunValue(0);
}
private void resetProgressBar(final int total) {
fProgressBar.reset();
fProgressBar.setMaximum(total);
}
private void postSyncRunnable(Runnable r) {
if (!isDisposed())
getDisplay().syncExec(r);
}
private void aboutToStart() {
postSyncRunnable(new Runnable() {
public void run() {
if (!isDisposed()) {
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.aboutToStart();
}
fNextAction.setEnabled(false);
fPreviousAction.setEnabled(false);
}
}
});
}
private void postEndTest(final String testId, final String testName) {
postSyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
handleEndTest();
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.endTest(testId);
}
if (fFailureCount + fErrorCount > 0) {
fNextAction.setEnabled(true);
fPreviousAction.setEnabled(true);
}
}
});
}
private void postStartTest(final String testId, final String testName) {
postSyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.startTest(testId);
}
}
});
}
private void handleEndTest() {
refreshCounters();
fProgressBar.step(fFailureCount+fErrorCount);
if (fShowOnErrorOnly) {
Image progress= fProgressImages.getImage(fExecutedTests, fTestCount, fErrorCount, fFailureCount);
if (progress != fViewImage) {
fViewImage= progress;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
}
}
private void refreshCounters() {
fCounterPanel.setErrorValue(fErrorCount);
fCounterPanel.setFailureValue(fFailureCount);
fCounterPanel.setRunValue(fExecutedTests);
fProgressBar.refresh(fErrorCount+fFailureCount> 0);
}
protected void postShowTestResultsView() {
postSyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
showTestResultsView();
}
});
}
public void showTestResultsView() {
IWorkbenchWindow window= getSite().getWorkbenchWindow();
IWorkbenchPage page= window.getActivePage();
TestRunnerViewPart testRunner= null;
if (page != null) {
try { // show the result view
testRunner= (TestRunnerViewPart)page.findView(TestRunnerViewPart.NAME);
if(testRunner == null) {
IWorkbenchPart activePart= page.getActivePart();
testRunner= (TestRunnerViewPart)page.showView(TestRunnerViewPart.NAME);
//restore focus stolen by the creation of the console
page.activate(activePart);
} else {
page.bringToTop(testRunner);
}
} catch (PartInitException pie) {
JUnitPlugin.log(pie);
}
}
}
protected void postInfo(final String message) {
postSyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
getStatusLine().setErrorMessage(null);
getStatusLine().setMessage(message);
}
});
}
protected void postError(final String message) {
postSyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
getStatusLine().setMessage(null);
getStatusLine().setErrorMessage(message);
}
});
}
protected void showInformation(final String info){
postSyncRunnable(new Runnable() {
public void run() {
if (!isDisposed())
fFailureView.setInformation(info);
}
});
}
private CTabFolder createTestRunViews(Composite parent) {
CTabFolder tabFolder= new CTabFolder(parent, SWT.TOP);
tabFolder.setLayoutData(new GridData(GridData.FILL_BOTH | GridData.GRAB_VERTICAL));
ITestRunView failureRunView= new FailureRunView(tabFolder, fClipboard, this);
ITestRunView testHierarchyRunView= new HierarchyRunView(tabFolder, this);
fTestRunViews.addElement(failureRunView);
fTestRunViews.addElement(testHierarchyRunView);
tabFolder.setSelection(0);
fActiveRunView= (ITestRunView)fTestRunViews.firstElement();
tabFolder.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
testViewChanged(event);
}
});
return tabFolder;
}
private void testViewChanged(SelectionEvent event) {
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
if (((CTabFolder) event.widget).getSelection().getText() == v.getName()){
v.setSelectedTest(fActiveRunView.getSelectedTestId());
fActiveRunView= v;
fActiveRunView.activate();
}
}
}
private SashForm createSashForm(Composite parent) {
fSashForm= new SashForm(parent, SWT.VERTICAL);
ViewForm top= new ViewForm(fSashForm, SWT.NONE);
fTabFolder= createTestRunViews(top);
fTabFolder.setLayoutData(new TabFolderLayout());
top.setContent(fTabFolder);
ViewForm bottom= new ViewForm(fSashForm, SWT.NONE);
CLabel label= new CLabel(bottom, SWT.NONE);
label.setText(JUnitMessages.getString("TestRunnerViewPart.label.failure")); //$NON-NLS-1$
label.setImage(fStackViewIcon);
bottom.setTopLeft(label);
ToolBar failureToolBar= new ToolBar(bottom, SWT.FLAT | SWT.WRAP);
bottom.setTopCenter(failureToolBar);
fFailureView= new FailureTraceView(bottom, fClipboard, this, failureToolBar);
bottom.setContent(fFailureView.getComposite());
fSashForm.setWeights(new int[]{50, 50});
return fSashForm;
}
private void reset(final int testCount) {
postSyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
fCounterPanel.reset();
fFailureView.clear();
fProgressBar.reset();
clearStatus();
start(testCount);
}
});
fExecutedTests= 0;
fFailureCount= 0;
fErrorCount= 0;
fTestCount= testCount;
aboutToStart();
fTestInfos.clear();
fFailures= new ArrayList();
}
private void clearStatus() {
getStatusLine().setMessage(null);
getStatusLine().setErrorMessage(null);
}
public void setFocus() {
if (fActiveRunView != null)
fActiveRunView.setFocus();
}
public void createPartControl(Composite parent) {
fParent= parent;
fClipboard= new Clipboard(parent.getDisplay());
GridLayout gridLayout= new GridLayout();
gridLayout.marginWidth= 0;
gridLayout.marginHeight= 0;
parent.setLayout(gridLayout);
configureToolBar();
fCounterComposite= createProgressCountPanel(parent);
fCounterComposite.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL));
SashForm sashForm= createSashForm(parent);
sashForm.setLayoutData(new GridData(GridData.FILL_BOTH));
IActionBars actionBars= getViewSite().getActionBars();
actionBars.setGlobalActionHandler(
ActionFactory.COPY.getId(),
new CopyTraceAction(fFailureView, fClipboard));
JUnitPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(this);
fOriginalViewImage= getTitleImage();
fProgressImages= new ProgressImages();
WorkbenchHelp.setHelp(parent, IJUnitHelpContextIds.RESULTS_VIEW);
if (fMemento != null)
restoreLayoutState(fMemento);
fMemento= null;
}
public void saveState(IMemento memento) {
if (fSashForm == null) {
// part has not been created
if (fMemento != null) //Keep the old state;
memento.putMemento(fMemento);
return;
}
int activePage= fTabFolder.getSelectionIndex();
memento.putInteger(TAG_PAGE, activePage);
int weigths[]= fSashForm.getWeights();
int ratio= (weigths[0] * 1000) / (weigths[0] + weigths[1]);
memento.putInteger(TAG_RATIO, ratio);
memento.putInteger(VIEWORIENTATION, fCurrentOrientation);
}
private void configureToolBar() {
IActionBars actionBars= getViewSite().getActionBars();
IToolBarManager toolBar= actionBars.getToolBarManager();
IMenuManager viewMenu = actionBars.getMenuManager();
fRerunLastTestAction= new RerunLastAction();
fScrollLockAction= new ScrollLockAction(this);
fToggleOrientationActions =
new ToggleOrientationAction[] {
new ToggleOrientationAction(this, VIEW_ORIENTATION_VERTICAL),
new ToggleOrientationAction(this, VIEW_ORIENTATION_HORIZONTAL)};
fNextAction= new ShowNextFailureAction(this);
fPreviousAction= new ShowPreviousFailureAction(this);
fNextAction.setEnabled(false);
fPreviousAction.setEnabled(false);
actionBars.setGlobalActionHandler(ActionFactory.NEXT.getId(), fNextAction);
actionBars.setGlobalActionHandler(ActionFactory.PREVIOUS.getId(), fPreviousAction);
toolBar.add(fNextAction);
toolBar.add(fPreviousAction);
toolBar.add(new StopAction());
toolBar.add(new Separator());
toolBar.add(fRerunLastTestAction);
toolBar.add(fScrollLockAction);
for (int i = 0; i < fToggleOrientationActions.length; ++i)
viewMenu.add(fToggleOrientationActions[i]);
fScrollLockAction.setChecked(!fAutoScroll);
actionBars.updateActionBars();
}
private IStatusLineManager getStatusLine() {
// we want to show messages globally hence we
// have to go throgh the active part
IViewSite site= getViewSite();
IWorkbenchPage page= site.getPage();
IWorkbenchPart activePart= page.getActivePart();
if (activePart instanceof IViewPart) {
IViewPart activeViewPart= (IViewPart)activePart;
IViewSite activeViewSite= activeViewPart.getViewSite();
return activeViewSite.getActionBars().getStatusLineManager();
}
if (activePart instanceof IEditorPart) {
IEditorPart activeEditorPart= (IEditorPart)activePart;
IEditorActionBarContributor contributor= activeEditorPart.getEditorSite().getActionBarContributor();
if (contributor instanceof EditorActionBarContributor)
return ((EditorActionBarContributor) contributor).getActionBars().getStatusLineManager();
}
// no active part
return getViewSite().getActionBars().getStatusLineManager();
}
private Composite createProgressCountPanel(Composite parent) {
Composite composite= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
composite.setLayout(layout);
setCounterColumns(layout);
fCounterPanel = new CounterPanel(composite);
fCounterPanel.setLayoutData(
new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL));
fProgressBar = new JUnitProgressBar(composite);
fProgressBar.setLayoutData(
new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL));
return composite;
}
public TestRunInfo getTestInfo(String testId) {
if (testId == null)
return null;
return (TestRunInfo) fTestInfos.get(testId);
}
public void handleTestSelected(String testId) {
TestRunInfo testInfo= getTestInfo(testId);
if (testInfo == null) {
showFailure(null); //$NON-NLS-1$
} else {
showFailure(testInfo);
}
}
private void showFailure(final TestRunInfo failure) {
postSyncRunnable(new Runnable() {
public void run() {
if (!isDisposed())
fFailureView.showFailure(failure);
}
});
}
public IJavaProject getLaunchedProject() {
return fTestProject;
}
public ILaunch getLastLaunch() {
return fLastLaunch;
}
protected static Image createImage(String path) {
try {
ImageDescriptor id= ImageDescriptor.createFromURL(JUnitPlugin.makeIconFileURL(path));
return id.createImage();
} catch (MalformedURLException e) {
// fall through
}
return null;
}
private boolean isDisposed() {
return fIsDisposed || fCounterPanel.isDisposed();
}
private Display getDisplay() {
return getViewSite().getShell().getDisplay();
}
/**
* @see IWorkbenchPart#getTitleImage()
*/
public Image getTitleImage() {
if (fOriginalViewImage == null)
fOriginalViewImage= super.getTitleImage();
if (fViewImage == null)
return super.getTitleImage();
return fViewImage;
}
public void propertyChange(PropertyChangeEvent event) {
if (isDisposed())
return;
if (IJUnitPreferencesConstants.SHOW_ON_ERROR_ONLY.equals(event.getProperty())) {
if (!JUnitPreferencePage.getShowOnErrorOnly()) {
fViewImage= fOriginalViewImage;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
}
}
void codeHasChanged() {
postSyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
if (fDirtyListener != null) {
JavaCore.removeElementChangedListener(fDirtyListener);
fDirtyListener= null;
}
if (fViewImage == fTestRunOKIcon)
fViewImage= fTestRunOKDirtyIcon;
else if (fViewImage == fTestRunFailIcon)
fViewImage= fTestRunFailDirtyIcon;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
});
}
boolean isCreated() {
return fCounterPanel != null;
}
public void rerunTest(String testId, String className, String testName) {
DebugUITools.saveAndBuildBeforeLaunch();
if (fTestRunnerClient != null && fTestRunnerClient.isRunning() && ILaunchManager.DEBUG_MODE.equals(fLaunchMode))
fTestRunnerClient.rerunTest(testId, className, testName);
else if (fLastLaunch != null) {
// run the selected test using the previous launch configuration
ILaunchConfiguration launchConfiguration= fLastLaunch.getLaunchConfiguration();
if (launchConfiguration != null) {
try {
ILaunchConfigurationWorkingCopy tmp= launchConfiguration.copy("Rerun "+testName); //$NON-NLS-1$
tmp.setAttribute(JUnitBaseLaunchConfiguration.TESTNAME_ATTR, testName);
tmp.launch(fLastLaunch.getLaunchMode(), null);
return;
} catch (CoreException e) {
ErrorDialog.openError(getSite().getShell(),
JUnitMessages.getString("TestRunnerViewPart.error.cannotrerun"), e.getMessage(), e.getStatus() //$NON-NLS-1$
);
}
}
MessageDialog.openInformation(getSite().getShell(),
JUnitMessages.getString("TestRunnerViewPart.cannotrerun.title"), //$NON-NLS-1$
JUnitMessages.getString("TestRunnerViewPart.cannotrerurn.message") //$NON-NLS-1$
);
}
}
private void setOrientation(int orientation) {
if ((fSashForm == null) || fSashForm.isDisposed())
return;
boolean horizontal = orientation == VIEW_ORIENTATION_HORIZONTAL;
fSashForm.setOrientation(horizontal ? SWT.HORIZONTAL : SWT.VERTICAL);
for (int i = 0; i < fToggleOrientationActions.length; ++i)
fToggleOrientationActions[i].setChecked(orientation == fToggleOrientationActions[i].getOrientation());
fCurrentOrientation = orientation;
GridLayout layout= (GridLayout) fCounterComposite.getLayout();
setCounterColumns(layout);
fParent.layout();
}
private void setCounterColumns(GridLayout layout) {
if (fCurrentOrientation == VIEW_ORIENTATION_HORIZONTAL)
layout.numColumns= 2;
else
layout.numColumns= 1;
}
}
|
49,708 |
Bug 49708 Deadlock saving compilation unit
|
It appears there is contention for the lock on the changed compilation unit resulting in the deadlock. The JUnit thread has the lock on the CU and attempts a synchExec. The UI thread is waiting for the lock on the CU. Full thread dump Java HotSpot(TM) Client VM (1.4.2-b28 mixed mode): "Worker-254" prio=5 tid=0x0511c210 nid=0xd08 in Object.wait() [497f000..497fd94] at java.lang.Object.wait(Native Method) at org.eclipse.core.internal.jobs.WorkerPool.sleep(WorkerPool.java:184) - locked <0x124fbd70> (a org.eclipse.core.internal.jobs.WorkerPool) at org.eclipse.core.internal.jobs.WorkerPool.startJob (WorkerPool.java:21 0) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55) "org.eclipse.jdt.internal.ui.text.JavaReconciler" daemon prio=2 tid=0x040d0188 n id=0xe48 in Object.wait() [617f000..617fd94] at java.lang.Object.wait(Native Method) at java.lang.Object.wait(Object.java:429) at org.eclipse.swt.widgets.Synchronizer.syncExec(Synchronizer.java:149) - locked <0x109711f8> (a org.eclipse.swt.widgets.RunnableLock) at org.eclipse.ui.internal.UISynchronizer.syncExec (UISynchronizer.java:2 5) at org.eclipse.swt.widgets.Display.syncExec(Display.java:2628) at org.eclipse.jdt.internal.junit.ui.TestRunnerViewPart.postSyncRunnable (TestRunnerViewPart.java:685) at org.eclipse.jdt.internal.junit.ui.TestRunnerViewPart.codeHasChanged (T estRunnerViewPart.java:1094) at org.eclipse.jdt.internal.junit.ui.TestRunnerViewPart$DirtyListener.pr ocessDelta(TestRunnerViewPart.java:285) at org.eclipse.jdt.internal.junit.ui.TestRunnerViewPart$DirtyListener.el ementChanged(TestRunnerViewPart.java:260) at org.eclipse.jdt.internal.core.DeltaProcessor$2.run (DeltaProcessor.jav a:1388) at org.eclipse.core.internal.runtime.InternalPlatform.run (InternalPlatfo rm.java:813) at org.eclipse.core.runtime.Platform.run(Platform.java:457) at org.eclipse.jdt.internal.core.DeltaProcessor.notifyListeners (DeltaPro cessor.java:1383) at org.eclipse.jdt.internal.core.DeltaProcessor.fireReconcileDelta (Delta Processor.java:1245) at org.eclipse.jdt.internal.core.DeltaProcessor.fire (DeltaProcessor.java :1203) at org.eclipse.jdt.internal.core.JavaModelOperation.run (JavaModelOperati on.java:723) at org.eclipse.jdt.internal.core.JavaElement.runOperation (JavaElement.ja va:524) at org.eclipse.jdt.internal.core.CompilationUnit.reconcile (CompilationUn it.java:1050) at org.eclipse.jdt.internal.core.CompilationUnit.reconcile (CompilationUn it.java:1022) at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconci le(JavaReconcilingStrategy.java:72) - locked <0x177f7f50> (a org.eclipse.jdt.internal.core.CompilationUnit) at org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy.reconci le(JavaReconcilingStrategy.java:99) at org.eclipse.jface.text.reconciler.MonoReconciler.process (MonoReconcil er.java:76) at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread .run(AbstractReconciler.java:189) "Worker-224" prio=5 tid=0x04058e28 nid=0x818 waiting on condition [60ff000..60ff d94] at java.lang.Thread.sleep(Native Method) at org.eclipse.ui.internal.progress.AnimationManager.animateLoop (Animati onManager.java:321) at org.eclipse.ui.internal.progress.AnimationManager$3.run (AnimationMana ger.java:471) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:62) "Java indexing" daemon prio=4 tid=0x00a2fd10 nid=0x1d4 in Object.wait() [387f000 ..387fd94] at java.lang.Object.wait(Native Method) - waiting on <0x126d3d70> (a org.eclipse.jdt.internal.core.search.indexi ng.IndexManager) at java.lang.Object.wait(Object.java:429) at org.eclipse.jdt.internal.core.search.processing.JobManager.run (JobMan ager.java:327) - locked <0x126d3d70> (a org.eclipse.jdt.internal.core.search.indexing.I ndexManager) at java.lang.Thread.run(Thread.java:534) "Start Level Event Dispatcher" daemon prio=5 tid=0x00a478c0 nid=0xae4 in Object. wait() [307f000..307fd94] at java.lang.Object.wait(Native Method) - waiting on <0x124f0128> (a org.eclipse.osgi.framework.eventmgr.EventTh read) at java.lang.Object.wait(Object.java:429) at org.eclipse.osgi.framework.eventmgr.EventThread.getNextEvent (EventThr ead.java:169) - locked <0x124f0128> (a org.eclipse.osgi.framework.eventmgr.EventThread ) at org.eclipse.osgi.framework.eventmgr.EventThread.run (EventThread.java: 120) "Framework Event Dispatcher" daemon prio=5 tid=0x00a4ce78 nid=0x938 in Object.wa it() [303f000..303fd94] at java.lang.Object.wait(Native Method) - waiting on <0x124f0178> (a org.eclipse.osgi.framework.eventmgr.EventTh read) at java.lang.Object.wait(Object.java:429) at org.eclipse.osgi.framework.eventmgr.EventThread.getNextEvent (EventThr ead.java:169) - locked <0x124f0178> (a org.eclipse.osgi.framework.eventmgr.EventThread ) at org.eclipse.osgi.framework.eventmgr.EventThread.run (EventThread.java: 120) "Signal Dispatcher" daemon prio=10 tid=0x0003d408 nid=0x91c waiting on condition [0..0] "Finalizer" daemon prio=9 tid=0x009c0120 nid=0xa68 in Object.wait() [2ccf000..2c cfd94] at java.lang.Object.wait(Native Method) at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:111) - locked <0x124f02a0> (a java.lang.ref.ReferenceQueue$Lock) at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:127) at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:159) "Reference Handler" daemon prio=10 tid=0x009becf0 nid=0x7a8 in Object.wait() [2c 8f000..2c8fd94] at java.lang.Object.wait(Native Method) at java.lang.Object.wait(Object.java:429) at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:115) - locked <0x124f0308> (a java.lang.ref.Reference$Lock) "main" prio=7 tid=0x00035260 nid=0x348 waiting for monitor entry [7f000..7fc3c] at org.eclipse.jdt.internal.ui.javaeditor.JavaEditor$MouseClickListener. getCurrentTextRegion(JavaEditor.java:544) - waiting to lock <0x177f7f50> (a org.eclipse.jdt.internal.core.Compilat ionUnit) at org.eclipse.jdt.internal.ui.javaeditor.JavaEditor$MouseClickListener. mouseMove(JavaEditor.java:771) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java: 144) 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:2311) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1992) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1506) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1482) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench (Workbench.jav a:246) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run (IDEApplication.java:47 ) at org.eclipse.core.internal.runtime.PlatformActivator$1.run (PlatformAct ivator.java:226) at org.eclipse.core.runtime.adaptor.EclipseStarter.run (EclipseStarter.ja va:85) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl. java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAcces sorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:279) at org.eclipse.core.launcher.Main.run(Main.java:742) at org.eclipse.core.launcher.Main.main(Main.java:581) "VM Thread" prio=5 tid=0x009fb6e8 nid=0xad8 runnable "VM Periodic Task Thread" prio=10 tid=0x0003fb58 nid=0xb40 waiting on condition "Suspend Checker Thread" prio=10 tid=0x009c2590 nid=0x924 runnable
|
resolved fixed
|
164e445
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-08T18:38:22Z | 2004-01-08T16:40:00Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/TestRunnerViewPart.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Julien Ruaux: [email protected] see bug 25324 Ability to know when tests are finished [junit]
* Vincent Massol: [email protected] 25324 Ability to know when tests are finished [junit]
* Sebastian Davids: [email protected] 35762 JUnit View wasting a lot of screen space [JUnit]
******************************************************************************/
package org.eclipse.jdt.internal.junit.ui;
import java.net.MalformedURLException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.debug.ui.DebugUITools;
import org.eclipse.jdt.core.ElementChangedEvent;
import org.eclipse.jdt.core.IElementChangedListener;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaElementDelta;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.internal.junit.launcher.JUnitBaseLaunchConfiguration;
import org.eclipse.jdt.junit.ITestRunListener;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.ViewForm;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorActionBarContributor;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.EditorActionBarContributor;
import org.eclipse.ui.part.ViewPart;
/**
* A ViewPart that shows the results of a test run.
*/
public class TestRunnerViewPart extends ViewPart implements ITestRunListener3, IPropertyChangeListener {
public static final String NAME= "org.eclipse.jdt.junit.ResultView"; //$NON-NLS-1$
/**
* Number of executed tests during a test run
*/
protected int fExecutedTests;
/**
* Number of errors during this test run
*/
protected int fErrorCount;
/**
* Number of failures during this test run
*/
protected int fFailureCount;
/**
* Number of tests run
*/
private int fTestCount;
/**
* Whether the output scrolls and reveals tests as they are executed.
*/
private boolean fAutoScroll = true;
/**
* The current orientation; either <code>VIEW_ORIENTATION_HORIZONTAL</code>
* or <code>VIEW_ORIENTATION_VERTICAL</code>.
*/
private int fCurrentOrientation;
/**
* Map storing TestInfos for each executed test keyed by
* the test name.
*/
private Map fTestInfos= new HashMap();
/**
* The first failure of a test run. Used to reveal the
* first failed tests at the end of a run.
*/
private List fFailures= new ArrayList();
private JUnitProgressBar fProgressBar;
private ProgressImages fProgressImages;
private Image fViewImage;
private CounterPanel fCounterPanel;
private boolean fShowOnErrorOnly= false;
private Clipboard fClipboard;
/**
* The view that shows the stack trace of a failure
*/
private FailureTraceView fFailureView;
/**
* The collection of ITestRunViews
*/
private Vector fTestRunViews = new Vector();
/**
* The currently active run view
*/
private ITestRunView fActiveRunView;
/**
* Is the UI disposed
*/
private boolean fIsDisposed= false;
/**
* The launched project
*/
private IJavaProject fTestProject;
/**
* The launcher that has started the test
*/
private String fLaunchMode;
private ILaunch fLastLaunch;
/**
* Actions
*/
private Action fRerunLastTestAction;
private ScrollLockAction fScrollLockAction;
private ToggleOrientationAction[] fToggleOrientationActions;
/**
* The client side of the remote test runner
*/
private RemoteTestRunnerClient fTestRunnerClient;
final Image fStackViewIcon= TestRunnerViewPart.createImage("cview16/stackframe.gif");//$NON-NLS-1$
final Image fTestRunOKIcon= TestRunnerViewPart.createImage("cview16/junitsucc.gif"); //$NON-NLS-1$
final Image fTestRunFailIcon= TestRunnerViewPart.createImage("cview16/juniterr.gif"); //$NON-NLS-1$
final Image fTestRunOKDirtyIcon= TestRunnerViewPart.createImage("cview16/junitsuccq.gif"); //$NON-NLS-1$
final Image fTestRunFailDirtyIcon= TestRunnerViewPart.createImage("cview16/juniterrq.gif"); //$NON-NLS-1$
// Persistance tags.
static final String TAG_PAGE= "page"; //$NON-NLS-1$
static final String TAG_RATIO= "ratio"; //$NON-NLS-1$
static final String TAG_TRACEFILTER= "tracefilter"; //$NON-NLS-1$
static final String TAG_ORIENTATION= "orientation"; //$NON-NLS-1$
static final String TAG_SCROLL= "scroll"; //$NON-NLS-1$
//orientations
static final int VIEW_ORIENTATION_VERTICAL= 0;
static final int VIEW_ORIENTATION_HORIZONTAL= 1;
private IMemento fMemento;
Image fOriginalViewImage;
IElementChangedListener fDirtyListener;
private CTabFolder fTabFolder;
private SashForm fSashForm;
private Action fNextAction;
private Action fPreviousAction;
private Composite fCounterComposite;
private Composite fParent;
private class StopAction extends Action {
public StopAction() {
setText(JUnitMessages.getString("TestRunnerViewPart.stopaction.text"));//$NON-NLS-1$
setToolTipText(JUnitMessages.getString("TestRunnerViewPart.stopaction.tooltip"));//$NON-NLS-1$
setDisabledImageDescriptor(JUnitPlugin.getImageDescriptor("dlcl16/stop.gif")); //$NON-NLS-1$
setHoverImageDescriptor(JUnitPlugin.getImageDescriptor("clcl16/stop.gif")); //$NON-NLS-1$
setImageDescriptor(JUnitPlugin.getImageDescriptor("elcl16/stop.gif")); //$NON-NLS-1$
}
public void run() {
stopTest();
}
}
private class RerunLastAction extends Action {
public RerunLastAction() {
setText(JUnitMessages.getString("TestRunnerViewPart.rerunaction.label")); //$NON-NLS-1$
setToolTipText(JUnitMessages.getString("TestRunnerViewPart.rerunaction.tooltip")); //$NON-NLS-1$
setDisabledImageDescriptor(JUnitPlugin.getImageDescriptor("dlcl16/relaunch.gif")); //$NON-NLS-1$
setHoverImageDescriptor(JUnitPlugin.getImageDescriptor("clcl16/relaunch.gif")); //$NON-NLS-1$
setImageDescriptor(JUnitPlugin.getImageDescriptor("elcl16/relaunch.gif")); //$NON-NLS-1$
}
public void run(){
rerunTestRun();
}
}
private class ToggleOrientationAction extends Action {
private final int fOrientation;
public ToggleOrientationAction(TestRunnerViewPart v, int orientation) {
super("", AS_RADIO_BUTTON); //$NON-NLS-1$
if (orientation == TestRunnerViewPart.VIEW_ORIENTATION_HORIZONTAL) {
setText(JUnitMessages.getString("TestRunnerViewPart.toggle.horizontal.label")); //$NON-NLS-1$
setDisabledImageDescriptor(JUnitPlugin.getImageDescriptor("dlcl16/th_horizontal.gif")); //$NON-NLS-1$
setHoverImageDescriptor(JUnitPlugin.getImageDescriptor("clcl16/th_horizontal.gif")); //$NON-NLS-1$
setImageDescriptor(JUnitPlugin.getImageDescriptor("elcl16/th_horizontal.gif")); //$NON-NLS-1$
} else if (orientation == TestRunnerViewPart.VIEW_ORIENTATION_VERTICAL) {
setText(JUnitMessages.getString("TestRunnerViewPart.toggle.vertical.label")); //$NON-NLS-1$
setDisabledImageDescriptor(JUnitPlugin.getImageDescriptor("dlcl16/th_vertical.gif")); //$NON-NLS-1$
setHoverImageDescriptor(JUnitPlugin.getImageDescriptor("clcl16/th_vertical.gif")); //$NON-NLS-1$
setImageDescriptor(JUnitPlugin.getImageDescriptor("elcl16/th_vertical.gif")); //$NON-NLS-1$
}
fOrientation= orientation;
WorkbenchHelp.setHelp(this, IJUnitHelpContextIds.RESULTS_VIEW_TOGGLE_ORIENTATION_ACTION);
}
public int getOrientation() {
return fOrientation;
}
public void run() {
if (fCurrentOrientation == fOrientation)
return;
setOrientation(fOrientation);
}
}
/**
* Listen for for modifications to Java elements
*/
private class DirtyListener implements IElementChangedListener {
public void elementChanged(ElementChangedEvent event) {
processDelta(event.getDelta());
}
private boolean processDelta(IJavaElementDelta delta) {
int kind= delta.getKind();
int details= delta.getFlags();
int type= delta.getElement().getElementType();
switch (type) {
// Consider containers for class files.
case IJavaElement.JAVA_MODEL:
case IJavaElement.JAVA_PROJECT:
case IJavaElement.PACKAGE_FRAGMENT_ROOT:
case IJavaElement.PACKAGE_FRAGMENT:
// If we did some different than changing a child we flush the the undo / redo stack.
if (kind != IJavaElementDelta.CHANGED || details != IJavaElementDelta.F_CHILDREN) {
codeHasChanged();
return false;
}
break;
case IJavaElement.COMPILATION_UNIT:
// if we have changed a primary working copy (e.g created, removed, ...)
// then we do nothing.
if ((details & IJavaElementDelta.F_PRIMARY_WORKING_COPY) != 0)
return true;
codeHasChanged();
return false;
case IJavaElement.CLASS_FILE:
// Don't examine children of a class file but keep on examining siblings.
return true;
default:
codeHasChanged();
return false;
}
IJavaElementDelta[] affectedChildren= delta.getAffectedChildren();
if (affectedChildren == null)
return true;
for (int i= 0; i < affectedChildren.length; i++) {
if (!processDelta(affectedChildren[i]))
return false;
}
return true;
}
}
public void init(IViewSite site, IMemento memento) throws PartInitException {
super.init(site, memento);
fMemento= memento;
}
private void restoreLayoutState(IMemento memento) {
Integer page= memento.getInteger(TAG_PAGE);
if (page != null) {
int p= page.intValue();
fTabFolder.setSelection(p);
fActiveRunView= (ITestRunView)fTestRunViews.get(p);
}
Integer ratio= memento.getInteger(TAG_RATIO);
if (ratio != null)
fSashForm.setWeights(new int[] { ratio.intValue(), 1000 - ratio.intValue()} );
Integer orientation= memento.getInteger(TAG_ORIENTATION);
if (orientation != null)
setOrientation(orientation.intValue());
String scrollLock= memento.getString(TAG_SCROLL);
if (scrollLock != null)
fScrollLockAction.setChecked(scrollLock.equals("true"));
}
/**
* Stops the currently running test and shuts down the RemoteTestRunner
*/
public void stopTest() {
if (fTestRunnerClient != null)
fTestRunnerClient.stopTest();
}
/**
* Stops the currently running test and shuts down the RemoteTestRunner
*/
public void rerunTestRun() {
if (fLastLaunch != null && fLastLaunch.getLaunchConfiguration() != null) {
try {
DebugUITools.saveAndBuildBeforeLaunch();
fLastLaunch.getLaunchConfiguration().launch(fLastLaunch.getLaunchMode(), null);
} catch (CoreException e) {
ErrorDialog.openError(getSite().getShell(),
JUnitMessages.getString("TestRunnerViewPart.error.cannotrerun"), e.getMessage(), e.getStatus() //$NON-NLS-1$
);
}
}
}
public void setAutoScroll(boolean scroll) {
fAutoScroll = scroll;
}
public boolean isAutoScroll() {
return fAutoScroll;
}
/*
* @see ITestRunListener#testRunStarted(testCount)
*/
public void testRunStarted(final int testCount){
reset(testCount);
fShowOnErrorOnly= JUnitPreferencePage.getShowOnErrorOnly();
fExecutedTests++;
}
public void selectNextFailure() {
fActiveRunView.selectNext();
}
public void selectPreviousFailure() {
fActiveRunView.selectPrevious();
}
public void showTest(TestRunInfo test) {
fActiveRunView.setSelectedTest(test.getTestId());
handleTestSelected(test.getTestId());
new OpenTestAction(this, test.getClassName(), test.getTestMethodName()).run();
}
public void reset(){
reset(0);
setViewPartTitle(null);
clearStatus();
resetViewIcon();
}
/*
* @see ITestRunListener#testRunEnded
*/
public void testRunEnded(long elapsedTime){
fExecutedTests--;
String[] keys= {elapsedTimeAsString(elapsedTime), String.valueOf(fErrorCount), String.valueOf(fFailureCount)};
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.finish", keys); //$NON-NLS-1$
if (hasErrorsOrFailures())
postError(msg);
else
postInfo(msg);
postSyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
if (fFailures.size() > 0) {
selectFirstFailure();
}
updateViewIcon();
if (fDirtyListener == null) {
fDirtyListener= new DirtyListener();
JavaCore.addElementChangedListener(fDirtyListener);
}
}
});
}
protected void selectFirstFailure() {
TestRunInfo firstFailure= (TestRunInfo)fFailures.get(0);
if (firstFailure != null && fAutoScroll) {
fActiveRunView.setSelectedTest(firstFailure.getTestId());
handleTestSelected(firstFailure.getTestId());
}
}
private void updateViewIcon() {
if (hasErrorsOrFailures())
fViewImage= fTestRunFailIcon;
else
fViewImage= fTestRunOKIcon;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
private boolean hasErrorsOrFailures() {
return fErrorCount+fFailureCount > 0;
}
private String elapsedTimeAsString(long runTime) {
return NumberFormat.getInstance().format((double)runTime/1000);
}
/*
* @see ITestRunListener#testRunStopped
*/
public void testRunStopped(final long elapsedTime) {
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.stopped", elapsedTimeAsString(elapsedTime)); //$NON-NLS-1$
postInfo(msg);
postSyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
resetViewIcon();
}
});
}
private void resetViewIcon() {
fViewImage= fOriginalViewImage;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
/*
* @see ITestRunListener#testRunTerminated
*/
public void testRunTerminated() {
String msg= JUnitMessages.getString("TestRunnerViewPart.message.terminated"); //$NON-NLS-1$
showMessage(msg);
}
private void showMessage(String msg) {
showInformation(msg);
postError(msg);
}
/*
* @see ITestRunListener#testStarted
*/
public void testStarted(String testId, String testName) {
postStartTest(testId, testName);
// reveal the part when the first test starts
if (!fShowOnErrorOnly && fExecutedTests == 1)
postShowTestResultsView();
TestRunInfo testInfo= getTestInfo(testId);
if (testInfo == null) {
testInfo= new TestRunInfo(testId, testName);
fTestInfos.put(testId, testInfo);
}
String className= testInfo.getClassName();
String method= testInfo.getTestMethodName();
String status= JUnitMessages.getFormattedString("TestRunnerViewPart.message.started", new String[] { className, method }); //$NON-NLS-1$
postInfo(status);
}
/*
* @see ITestRunListener#testEnded
*/
public void testEnded(String testId, String testName){
postEndTest(testId, testName);
fExecutedTests++;
}
/*
* @see ITestRunListener#testFailed
*/
public void testFailed(int status, String testId, String testName, String trace){
testFailed(status, testId, testName, trace, null, null);
}
/*
* @see ITestRunListener#testFailed
*/
public void testFailed(int status, String testId, String testName, String trace, String expected, String actual){
TestRunInfo testInfo= getTestInfo(testId);
if (testInfo == null) {
testInfo= new TestRunInfo(testId, testName);
fTestInfos.put(testName, testInfo);
}
testInfo.setTrace(trace);
testInfo.setStatus(status);
if (expected != null && expected.length() > 0) {
testInfo.setExpected(expected.substring(0, expected.length()-1));
}
if (actual != null && actual.length() > 0)
testInfo.setActual(actual.substring(0, actual.length()-1));
if (status == ITestRunListener.STATUS_ERROR)
fErrorCount++;
else
fFailureCount++;
fFailures.add(testInfo);
// show the view on the first error only
if (fShowOnErrorOnly && (fErrorCount + fFailureCount == 1))
postShowTestResultsView();
}
/*
* @see ITestRunListener#testReran
*/
public void testReran(String testId, String className, String testName, int status, String trace) {
if (status == ITestRunListener.STATUS_ERROR) {
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.error", new String[]{testName, className}); //$NON-NLS-1$
postError(msg);
} else if (status == ITestRunListener.STATUS_FAILURE) {
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.failure", new String[]{testName, className}); //$NON-NLS-1$
postError(msg);
} else {
String msg= JUnitMessages.getFormattedString("TestRunnerViewPart.message.success", new String[]{testName, className}); //$NON-NLS-1$
postInfo(msg);
}
TestRunInfo info= getTestInfo(testId);
updateTest(info, status);
if (info.getTrace() == null || !info.getTrace().equals(trace)) {
info.setTrace(trace);
showFailure(info);
}
}
private void updateTest(TestRunInfo info, final int status) {
if (status == info.getStatus())
return;
if (info.getStatus() == ITestRunListener.STATUS_OK) {
if (status == ITestRunListener.STATUS_FAILURE)
fFailureCount++;
else if (status == ITestRunListener.STATUS_ERROR)
fErrorCount++;
} else if (info.getStatus() == ITestRunListener.STATUS_ERROR) {
if (status == ITestRunListener.STATUS_OK)
fErrorCount--;
else if (status == ITestRunListener.STATUS_FAILURE) {
fErrorCount--;
fFailureCount++;
}
} else if (info.getStatus() == ITestRunListener.STATUS_FAILURE) {
if (status == ITestRunListener.STATUS_OK)
fFailureCount--;
else if (status == ITestRunListener.STATUS_ERROR) {
fFailureCount--;
fErrorCount++;
}
}
info.setStatus(status);
final TestRunInfo finalInfo= info;
postSyncRunnable(new Runnable() {
public void run() {
refreshCounters();
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.testStatusChanged(finalInfo);
}
}
});
}
/*
* @see ITestRunListener#testTreeEntry
*/
public void testTreeEntry(final String treeEntry){
postSyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.newTreeEntry(treeEntry);
}
}
});
}
public void startTestRunListening(IJavaElement type, int port, ILaunch launch) {
fTestProject= type.getJavaProject();
fLaunchMode= launch.getLaunchMode();
aboutToLaunch();
if (fTestRunnerClient != null) {
stopTest();
}
fTestRunnerClient= new RemoteTestRunnerClient();
// add the TestRunnerViewPart to the list of registered listeners
List listeners= JUnitPlugin.getDefault().getTestRunListeners();
ITestRunListener[] listenerArray= new ITestRunListener[listeners.size()+1];
listeners.toArray(listenerArray);
System.arraycopy(listenerArray, 0, listenerArray, 1, listenerArray.length-1);
listenerArray[0]= this;
fTestRunnerClient.startListening(listenerArray, port);
fLastLaunch= launch;
setViewPartTitle(type);
if (type instanceof IType)
setTitleToolTip(((IType)type).getFullyQualifiedName());
else
setTitleToolTip(type.getElementName());
}
private void setViewPartTitle(IJavaElement type) {
String title;
if (type == null)
title= JUnitMessages.getString("TestRunnerViewPart.title_no_type"); //$NON-NLS-1$
else
title= JUnitMessages.getFormattedString("TestRunnerViewPart.title", type.getElementName()); //$NON-NLS-1$
setTitle(title);
}
private void aboutToLaunch() {
String msg= JUnitMessages.getString("TestRunnerViewPart.message.launching"); //$NON-NLS-1$
showInformation(msg);
postInfo(msg);
fViewImage= fOriginalViewImage;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
public synchronized void dispose(){
fIsDisposed= true;
stopTest();
if (fProgressImages != null)
fProgressImages.dispose();
JUnitPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(this);
fTestRunOKIcon.dispose();
fTestRunFailIcon.dispose();
fStackViewIcon.dispose();
fTestRunOKDirtyIcon.dispose();
fTestRunFailDirtyIcon.dispose();
if (fClipboard != null)
fClipboard.dispose();
}
private void start(final int total) {
resetProgressBar(total);
fCounterPanel.setTotal(total);
fCounterPanel.setRunValue(0);
}
private void resetProgressBar(final int total) {
fProgressBar.reset();
fProgressBar.setMaximum(total);
}
private void postSyncRunnable(Runnable r) {
if (!isDisposed())
getDisplay().syncExec(r);
}
private void aboutToStart() {
postSyncRunnable(new Runnable() {
public void run() {
if (!isDisposed()) {
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.aboutToStart();
}
fNextAction.setEnabled(false);
fPreviousAction.setEnabled(false);
}
}
});
}
private void postEndTest(final String testId, final String testName) {
postSyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
handleEndTest();
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.endTest(testId);
}
if (fFailureCount + fErrorCount > 0) {
fNextAction.setEnabled(true);
fPreviousAction.setEnabled(true);
}
}
});
}
private void postStartTest(final String testId, final String testName) {
postSyncRunnable(new Runnable() {
public void run() {
if(isDisposed())
return;
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
v.startTest(testId);
}
}
});
}
private void handleEndTest() {
refreshCounters();
fProgressBar.step(fFailureCount+fErrorCount);
if (fShowOnErrorOnly) {
Image progress= fProgressImages.getImage(fExecutedTests, fTestCount, fErrorCount, fFailureCount);
if (progress != fViewImage) {
fViewImage= progress;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
}
}
private void refreshCounters() {
fCounterPanel.setErrorValue(fErrorCount);
fCounterPanel.setFailureValue(fFailureCount);
fCounterPanel.setRunValue(fExecutedTests);
fProgressBar.refresh(fErrorCount+fFailureCount> 0);
}
protected void postShowTestResultsView() {
postSyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
showTestResultsView();
}
});
}
public void showTestResultsView() {
IWorkbenchWindow window= getSite().getWorkbenchWindow();
IWorkbenchPage page= window.getActivePage();
TestRunnerViewPart testRunner= null;
if (page != null) {
try { // show the result view
testRunner= (TestRunnerViewPart)page.findView(TestRunnerViewPart.NAME);
if(testRunner == null) {
IWorkbenchPart activePart= page.getActivePart();
testRunner= (TestRunnerViewPart)page.showView(TestRunnerViewPart.NAME);
//restore focus stolen by the creation of the console
page.activate(activePart);
} else {
page.bringToTop(testRunner);
}
} catch (PartInitException pie) {
JUnitPlugin.log(pie);
}
}
}
protected void postInfo(final String message) {
postSyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
getStatusLine().setErrorMessage(null);
getStatusLine().setMessage(message);
}
});
}
protected void postError(final String message) {
postSyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
getStatusLine().setMessage(null);
getStatusLine().setErrorMessage(message);
}
});
}
protected void showInformation(final String info){
postSyncRunnable(new Runnable() {
public void run() {
if (!isDisposed())
fFailureView.setInformation(info);
}
});
}
private CTabFolder createTestRunViews(Composite parent) {
CTabFolder tabFolder= new CTabFolder(parent, SWT.TOP);
tabFolder.setLayoutData(new GridData(GridData.FILL_BOTH | GridData.GRAB_VERTICAL));
ITestRunView failureRunView= new FailureRunView(tabFolder, fClipboard, this);
ITestRunView testHierarchyRunView= new HierarchyRunView(tabFolder, this);
fTestRunViews.addElement(failureRunView);
fTestRunViews.addElement(testHierarchyRunView);
tabFolder.setSelection(0);
fActiveRunView= (ITestRunView)fTestRunViews.firstElement();
tabFolder.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
testViewChanged(event);
}
});
return tabFolder;
}
private void testViewChanged(SelectionEvent event) {
for (Enumeration e= fTestRunViews.elements(); e.hasMoreElements();) {
ITestRunView v= (ITestRunView) e.nextElement();
if (((CTabFolder) event.widget).getSelection().getText() == v.getName()){
v.setSelectedTest(fActiveRunView.getSelectedTestId());
fActiveRunView= v;
fActiveRunView.activate();
}
}
}
private SashForm createSashForm(Composite parent) {
fSashForm= new SashForm(parent, SWT.VERTICAL);
ViewForm top= new ViewForm(fSashForm, SWT.NONE);
fTabFolder= createTestRunViews(top);
fTabFolder.setLayoutData(new TabFolderLayout());
top.setContent(fTabFolder);
ViewForm bottom= new ViewForm(fSashForm, SWT.NONE);
CLabel label= new CLabel(bottom, SWT.NONE);
label.setText(JUnitMessages.getString("TestRunnerViewPart.label.failure")); //$NON-NLS-1$
label.setImage(fStackViewIcon);
bottom.setTopLeft(label);
ToolBar failureToolBar= new ToolBar(bottom, SWT.FLAT | SWT.WRAP);
bottom.setTopCenter(failureToolBar);
fFailureView= new FailureTraceView(bottom, fClipboard, this, failureToolBar);
bottom.setContent(fFailureView.getComposite());
fSashForm.setWeights(new int[]{50, 50});
return fSashForm;
}
private void reset(final int testCount) {
postSyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
fCounterPanel.reset();
fFailureView.clear();
fProgressBar.reset();
clearStatus();
start(testCount);
}
});
fExecutedTests= 0;
fFailureCount= 0;
fErrorCount= 0;
fTestCount= testCount;
aboutToStart();
fTestInfos.clear();
fFailures= new ArrayList();
}
private void clearStatus() {
getStatusLine().setMessage(null);
getStatusLine().setErrorMessage(null);
}
public void setFocus() {
if (fActiveRunView != null)
fActiveRunView.setFocus();
}
public void createPartControl(Composite parent) {
fParent= parent;
fClipboard= new Clipboard(parent.getDisplay());
GridLayout gridLayout= new GridLayout();
gridLayout.marginWidth= 0;
gridLayout.marginHeight= 0;
parent.setLayout(gridLayout);
configureToolBar();
fCounterComposite= createProgressCountPanel(parent);
fCounterComposite.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL));
SashForm sashForm= createSashForm(parent);
sashForm.setLayoutData(new GridData(GridData.FILL_BOTH));
IActionBars actionBars= getViewSite().getActionBars();
actionBars.setGlobalActionHandler(
ActionFactory.COPY.getId(),
new CopyTraceAction(fFailureView, fClipboard));
JUnitPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(this);
fOriginalViewImage= getTitleImage();
fProgressImages= new ProgressImages();
WorkbenchHelp.setHelp(parent, IJUnitHelpContextIds.RESULTS_VIEW);
if (fMemento != null) {
restoreLayoutState(fMemento);
}
fMemento= null;
}
public void saveState(IMemento memento) {
if (fSashForm == null) {
// part has not been created
if (fMemento != null) //Keep the old state;
memento.putMemento(fMemento);
return;
}
int activePage= fTabFolder.getSelectionIndex();
memento.putInteger(TAG_PAGE, activePage);
memento.putString(TAG_SCROLL, fScrollLockAction.isChecked() ? "true" : "false");
int weigths[]= fSashForm.getWeights();
int ratio= (weigths[0] * 1000) / (weigths[0] + weigths[1]);
memento.putInteger(TAG_RATIO, ratio);
memento.putInteger(TAG_ORIENTATION, fCurrentOrientation);
}
private void configureToolBar() {
IActionBars actionBars= getViewSite().getActionBars();
IToolBarManager toolBar= actionBars.getToolBarManager();
IMenuManager viewMenu = actionBars.getMenuManager();
fRerunLastTestAction= new RerunLastAction();
fScrollLockAction= new ScrollLockAction(this);
fToggleOrientationActions =
new ToggleOrientationAction[] {
new ToggleOrientationAction(this, VIEW_ORIENTATION_VERTICAL),
new ToggleOrientationAction(this, VIEW_ORIENTATION_HORIZONTAL)};
fNextAction= new ShowNextFailureAction(this);
fPreviousAction= new ShowPreviousFailureAction(this);
fNextAction.setEnabled(false);
fPreviousAction.setEnabled(false);
actionBars.setGlobalActionHandler(ActionFactory.NEXT.getId(), fNextAction);
actionBars.setGlobalActionHandler(ActionFactory.PREVIOUS.getId(), fPreviousAction);
toolBar.add(fNextAction);
toolBar.add(fPreviousAction);
toolBar.add(new StopAction());
toolBar.add(new Separator());
toolBar.add(fRerunLastTestAction);
toolBar.add(fScrollLockAction);
for (int i = 0; i < fToggleOrientationActions.length; ++i)
viewMenu.add(fToggleOrientationActions[i]);
fScrollLockAction.setChecked(!fAutoScroll);
actionBars.updateActionBars();
}
private IStatusLineManager getStatusLine() {
// we want to show messages globally hence we
// have to go throgh the active part
IViewSite site= getViewSite();
IWorkbenchPage page= site.getPage();
IWorkbenchPart activePart= page.getActivePart();
if (activePart instanceof IViewPart) {
IViewPart activeViewPart= (IViewPart)activePart;
IViewSite activeViewSite= activeViewPart.getViewSite();
return activeViewSite.getActionBars().getStatusLineManager();
}
if (activePart instanceof IEditorPart) {
IEditorPart activeEditorPart= (IEditorPart)activePart;
IEditorActionBarContributor contributor= activeEditorPart.getEditorSite().getActionBarContributor();
if (contributor instanceof EditorActionBarContributor)
return ((EditorActionBarContributor) contributor).getActionBars().getStatusLineManager();
}
// no active part
return getViewSite().getActionBars().getStatusLineManager();
}
private Composite createProgressCountPanel(Composite parent) {
Composite composite= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
composite.setLayout(layout);
setCounterColumns(layout);
fCounterPanel = new CounterPanel(composite);
fCounterPanel.setLayoutData(
new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL));
fProgressBar = new JUnitProgressBar(composite);
fProgressBar.setLayoutData(
new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL));
return composite;
}
public TestRunInfo getTestInfo(String testId) {
if (testId == null)
return null;
return (TestRunInfo) fTestInfos.get(testId);
}
public void handleTestSelected(String testId) {
TestRunInfo testInfo= getTestInfo(testId);
if (testInfo == null) {
showFailure(null); //$NON-NLS-1$
} else {
showFailure(testInfo);
}
}
private void showFailure(final TestRunInfo failure) {
postSyncRunnable(new Runnable() {
public void run() {
if (!isDisposed())
fFailureView.showFailure(failure);
}
});
}
public IJavaProject getLaunchedProject() {
return fTestProject;
}
public ILaunch getLastLaunch() {
return fLastLaunch;
}
protected static Image createImage(String path) {
try {
ImageDescriptor id= ImageDescriptor.createFromURL(JUnitPlugin.makeIconFileURL(path));
return id.createImage();
} catch (MalformedURLException e) {
// fall through
}
return null;
}
private boolean isDisposed() {
return fIsDisposed || fCounterPanel.isDisposed();
}
private Display getDisplay() {
return getViewSite().getShell().getDisplay();
}
/**
* @see IWorkbenchPart#getTitleImage()
*/
public Image getTitleImage() {
if (fOriginalViewImage == null)
fOriginalViewImage= super.getTitleImage();
if (fViewImage == null)
return super.getTitleImage();
return fViewImage;
}
public void propertyChange(PropertyChangeEvent event) {
if (isDisposed())
return;
if (IJUnitPreferencesConstants.SHOW_ON_ERROR_ONLY.equals(event.getProperty())) {
if (!JUnitPreferencePage.getShowOnErrorOnly()) {
fViewImage= fOriginalViewImage;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
}
}
void codeHasChanged() {
postSyncRunnable(new Runnable() {
public void run() {
if (isDisposed())
return;
if (fDirtyListener != null) {
JavaCore.removeElementChangedListener(fDirtyListener);
fDirtyListener= null;
}
if (fViewImage == fTestRunOKIcon)
fViewImage= fTestRunOKDirtyIcon;
else if (fViewImage == fTestRunFailIcon)
fViewImage= fTestRunFailDirtyIcon;
firePropertyChange(IWorkbenchPart.PROP_TITLE);
}
});
}
boolean isCreated() {
return fCounterPanel != null;
}
public void rerunTest(String testId, String className, String testName) {
DebugUITools.saveAndBuildBeforeLaunch();
if (fTestRunnerClient != null && fTestRunnerClient.isRunning() && ILaunchManager.DEBUG_MODE.equals(fLaunchMode))
fTestRunnerClient.rerunTest(testId, className, testName);
else if (fLastLaunch != null) {
// run the selected test using the previous launch configuration
ILaunchConfiguration launchConfiguration= fLastLaunch.getLaunchConfiguration();
if (launchConfiguration != null) {
try {
ILaunchConfigurationWorkingCopy tmp= launchConfiguration.copy("Rerun "+testName); //$NON-NLS-1$
tmp.setAttribute(JUnitBaseLaunchConfiguration.TESTNAME_ATTR, testName);
tmp.launch(fLastLaunch.getLaunchMode(), null);
return;
} catch (CoreException e) {
ErrorDialog.openError(getSite().getShell(),
JUnitMessages.getString("TestRunnerViewPart.error.cannotrerun"), e.getMessage(), e.getStatus() //$NON-NLS-1$
);
}
}
MessageDialog.openInformation(getSite().getShell(),
JUnitMessages.getString("TestRunnerViewPart.cannotrerun.title"), //$NON-NLS-1$
JUnitMessages.getString("TestRunnerViewPart.cannotrerurn.message") //$NON-NLS-1$
);
}
}
private void setOrientation(int orientation) {
if ((fSashForm == null) || fSashForm.isDisposed())
return;
boolean horizontal = orientation == VIEW_ORIENTATION_HORIZONTAL;
fSashForm.setOrientation(horizontal ? SWT.HORIZONTAL : SWT.VERTICAL);
for (int i = 0; i < fToggleOrientationActions.length; ++i)
fToggleOrientationActions[i].setChecked(orientation == fToggleOrientationActions[i].getOrientation());
fCurrentOrientation = orientation;
GridLayout layout= (GridLayout) fCounterComposite.getLayout();
setCounterColumns(layout);
fParent.layout();
}
private void setCounterColumns(GridLayout layout) {
if (fCurrentOrientation == VIEW_ORIENTATION_HORIZONTAL)
layout.numColumns= 2;
else
layout.numColumns= 1;
}
}
|
47,208 |
Bug 47208 Generate Javadoc dialog lays out too wide [javadoc]
|
If one uses a custom doclet and sets the doclet class path to a long path (e.g. with many JAR files on it), the "Generate Javadoc" dialog lays out to try and fit the full doclet class path on the screen; this results in a very wide dialog.
|
resolved fixed
|
40faefa
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-09T11:59:07Z | 2003-11-21T13:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javadocexport/JavadocTreeWizardPage.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.javadocexport;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.StringTokenizer;
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.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.preference.IPreferenceNode;
import org.eclipse.jface.preference.IPreferencePage;
import org.eclipse.jface.preference.PreferenceDialog;
import org.eclipse.jface.preference.PreferenceManager;
import org.eclipse.jface.preference.PreferenceNode;
import org.eclipse.jface.viewers.CheckStateChangedEvent;
import org.eclipse.jface.viewers.ICheckStateListener;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.window.Window;
import org.eclipse.ui.help.WorkbenchHelp;
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.JavaConventions;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.launching.JavaRuntime;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.dialogs.StatusUtil;
import org.eclipse.jdt.internal.ui.jarpackager.CheckboxTreeAndListGroup;
import org.eclipse.jdt.internal.ui.preferences.JavadocPreferencePage;
import org.eclipse.jdt.internal.ui.util.SWTUtil;
public class JavadocTreeWizardPage extends JavadocWizardPage {
private CheckboxTreeAndListGroup fInputGroup;
protected IWorkspaceRoot fRoot;
protected String fWorkspace;
//private JavadocTreeViewerFilter fFilter;
protected Text fDestinationText;
protected Text fJavadocCommandText;
protected Text fDocletText;
protected Text fDocletTypeText;
protected Button fStandardButton;
protected Button fDestinationBrowserButton;
protected Button fCustomButton;
protected Button fPrivateVisibility;
protected Button fProtectedVisibility;
protected Button fPackageVisibility;
protected Button fPublicVisibility;
private Label fDocletLabel;
private Label fDocletTypeLabel;
private Label fDestinationLabel;
private CLabel fDescriptionLabel;
protected String fVisibilitySelection;
protected boolean fDocletSelected;
private JavadocOptionsManager fStore;
private JavadocWizard fWizard;
protected StatusInfo fJavadocStatus;
protected StatusInfo fDestinationStatus;
protected StatusInfo fDocletStatus;
protected StatusInfo fTreeStatus;
protected StatusInfo fPreferenceStatus;
protected StatusInfo fWizardStatus;
private final int PREFERENCESTATUS= 0;
private final int CUSTOMSTATUS= 1;
private final int STANDARDSTATUS= 2;
private final int TREESTATUS= 3;
private final int JAVADOCSTATUS= 4;
/**
* Constructor for JavadocTreeWizardPage.
* @param pageName
*/
protected JavadocTreeWizardPage(String pageName, JavadocOptionsManager store) {
super(pageName);
setDescription(JavadocExportMessages.getString("JavadocTreeWizardPage.javadoctreewizardpage.description")); //$NON-NLS-1$
fStore= store;
// Status variables
fJavadocStatus= new StatusInfo();
fDestinationStatus= new StatusInfo();
fDocletStatus= new StatusInfo();
fTreeStatus= new StatusInfo();
fPreferenceStatus= new StatusInfo();
fWizardStatus= store.getWizardStatus();
}
/*
* @see IDialogPage#createControl(Composite)
*/
public void createControl(Composite parent) {
initializeDialogUnits(parent);
fWizard= (JavadocWizard) this.getWizard();
Composite composite= new Composite(parent, SWT.NONE);
GridLayout compositeGridLayout= new GridLayout();
composite.setLayoutData(createGridData(GridData.FILL_BOTH, 0, 0));
compositeGridLayout.numColumns= 6;
composite.setLayout(compositeGridLayout);
createJavadocCommandSet(composite);
createInputGroup(composite);
createVisibilitySet(composite);
createOptionsSet(composite);
setControl(composite);
Dialog.applyDialogFont(composite);
WorkbenchHelp.setHelp(composite, IJavaHelpContextIds.JAVADOC_TREE_PAGE);
}
protected void createJavadocCommandSet(Composite composite) {
GridLayout commandSetLayout= createGridLayout(2);
commandSetLayout.marginHeight= 0;
commandSetLayout.marginWidth= 0;
Composite c = new Composite(composite, SWT.NONE);
c.setLayoutData(createGridData(GridData.FILL_BOTH, 6, 0));
c.setLayout(commandSetLayout);
createLabel(c, SWT.NONE, JavadocExportMessages.getString("JavadocTreeWizardPage.javadoccommand.label"), createGridData(GridData.HORIZONTAL_ALIGN_BEGINNING, 2, 0)); //$NON-NLS-1$
fJavadocCommandText= createText(c, SWT.READ_ONLY | SWT.SINGLE | SWT.BORDER, null, createGridData(GridData.FILL_HORIZONTAL, 1, 0));
((GridData) fJavadocCommandText.getLayoutData()).widthHint= 200;
fJavadocCommandText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
doValidation(JAVADOCSTATUS);
}
});
Button javadocCommandBrowserButton= createButton(c, SWT.PUSH, JavadocExportMessages.getString("JavadocTreeWizardPage.javadoccommand.button.label"), createGridData(GridData.HORIZONTAL_ALIGN_FILL, 1, 0)); //$NON-NLS-1$
SWTUtil.setButtonDimensionHint(javadocCommandBrowserButton);
javadocCommandBrowserButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
JavadocPreferencePage page= new JavadocPreferencePage();
showPreferencePage(JavadocPreferencePage.ID, page); //$NON-NLS-1$
fJavadocCommandText.setText(JavadocPreferencePage.getJavaDocCommand());
}
});
}
protected void createInputGroup(Composite composite) {
createLabel(composite, SWT.NONE, JavadocExportMessages.getString("JavadocTreeWizardPage.checkboxtreeandlistgroup.label"), createGridData(6)); //$NON-NLS-1$
Composite c= new Composite(composite, SWT.NONE);
GridLayout layout= new GridLayout();
layout.numColumns= 1;
layout.makeColumnsEqualWidth= true;
layout.marginWidth= 0;
layout.marginHeight= 0;
c.setLayout(layout);
c.setLayoutData(createGridData(GridData.FILL_BOTH, 6, 0));
ITreeContentProvider treeContentProvider= new JavadocProjectContentProvider();
ITreeContentProvider listContentProvider= new JavadocMemberContentProvider();
fInputGroup= new CheckboxTreeAndListGroup(c, fStore.getRoot(), treeContentProvider, new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT), listContentProvider, new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT), SWT.NONE, convertWidthInCharsToPixels(60), convertHeightInCharsToPixels(10));
fInputGroup.addCheckStateListener(new ICheckStateListener() {
public void checkStateChanged(CheckStateChangedEvent e) {
doValidation(TREESTATUS);
fWizard.removeAllProjects();
setProjects();
}
});
//the store will contain at least one project in it's list so long as
//the workspace is not empty.
if (!fStore.getJavaProjects().isEmpty())
setTreeChecked(fStore.getSelectedElements(), (IJavaProject) fStore.getJavaProjects().get(0));
fInputGroup.aboutToOpen();
}
private void createVisibilitySet(Composite composite) {
GridLayout visibilityLayout= createGridLayout(4);
visibilityLayout.marginHeight= 0;
visibilityLayout.marginWidth= 0;
Composite visibilityGroup= new Composite(composite, SWT.NONE);
visibilityGroup.setLayoutData(createGridData(GridData.FILL_HORIZONTAL, 6, 0));
visibilityGroup.setLayout(visibilityLayout);
createLabel(visibilityGroup, SWT.NONE, JavadocExportMessages.getString("JavadocTreeWizardPage.visibilitygroup.label"), createGridData(GridData.FILL_HORIZONTAL, 4, 0)); //$NON-NLS-1$
fPrivateVisibility= createButton(visibilityGroup, SWT.RADIO, JavadocExportMessages.getString("JavadocTreeWizardPage.privatebutton.label"), createGridData(GridData.FILL_HORIZONTAL, 1, 0)); //$NON-NLS-1$
fPackageVisibility= createButton(visibilityGroup, SWT.RADIO, JavadocExportMessages.getString("JavadocTreeWizardPage.packagebutton.label"), createGridData(GridData.FILL_HORIZONTAL, 1, 0)); //$NON-NLS-1$
fProtectedVisibility= createButton(visibilityGroup, SWT.RADIO, JavadocExportMessages.getString("JavadocTreeWizardPage.protectedbutton.label"), createGridData(GridData.FILL_HORIZONTAL, 1, 0)); //$NON-NLS-1$
fPublicVisibility= createButton(visibilityGroup, SWT.RADIO, JavadocExportMessages.getString("JavadocTreeWizardPage.publicbutton.label"), createGridData(GridData.FILL_HORIZONTAL, 1, 0)); //$NON-NLS-1$
fDescriptionLabel= new CLabel(visibilityGroup, SWT.LEFT);
fDescriptionLabel.setLayoutData(createGridData(GridData.FILL_HORIZONTAL, 4, convertWidthInCharsToPixels(3) - 3)); // INDENT of CLabel
fPrivateVisibility.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if (((Button) e.widget).getSelection()) {
fVisibilitySelection= fStore.PRIVATE;
fDescriptionLabel.setText(JavadocExportMessages.getString("JavadocTreeWizardPage.privatevisibilitydescription.label")); //$NON-NLS-1$
}
}
});
fPackageVisibility.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if (((Button) e.widget).getSelection()) {
fVisibilitySelection= fStore.PACKAGE;
fDescriptionLabel.setText(JavadocExportMessages.getString("JavadocTreeWizardPage.packagevisibledescription.label")); //$NON-NLS-1$
}
}
});
fProtectedVisibility.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if (((Button) e.widget).getSelection()) {
fVisibilitySelection= fStore.PROTECTED;
fDescriptionLabel.setText(JavadocExportMessages.getString("JavadocTreeWizardPage.protectedvisibilitydescription.label")); //$NON-NLS-1$
}
}
});
fPublicVisibility.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
if (((Button) e.widget).getSelection()) {
fVisibilitySelection= fStore.PUBLIC;
fDescriptionLabel.setText(JavadocExportMessages.getString("JavadocTreeWizardPage.publicvisibilitydescription.label")); //$NON-NLS-1$
}
}
});
setVisibilitySettings();
}
protected void setVisibilitySettings() {
fVisibilitySelection= fStore.getAccess();
fPrivateVisibility.setSelection(fVisibilitySelection.equals(fStore.PRIVATE));
if (fPrivateVisibility.getSelection())
fDescriptionLabel.setText(JavadocExportMessages.getString("JavadocTreeWizardPage.privatevisibilitydescription.label")); //$NON-NLS-1$
//$NON-NLS-1$
fProtectedVisibility.setSelection(fVisibilitySelection.equals(fStore.PROTECTED));
if (fProtectedVisibility.getSelection())
fDescriptionLabel.setText(JavadocExportMessages.getString("JavadocTreeWizardPage.protectedvisibilitydescription.label")); //$NON-NLS-1$
//$NON-NLS-1$
fPackageVisibility.setSelection(fVisibilitySelection.equals(fStore.PACKAGE));
if (fPackageVisibility.getSelection())
fDescriptionLabel.setText(JavadocExportMessages.getString("JavadocTreeWizardPage.packagevisibledescription.label")); //$NON-NLS-1$
//$NON-NLS-1$
fPublicVisibility.setSelection(fVisibilitySelection.equals(fStore.PUBLIC));
if (fPublicVisibility.getSelection())
fDescriptionLabel.setText(JavadocExportMessages.getString("JavadocTreeWizardPage.publicvisibilitydescription.label")); //$NON-NLS-1$
//$NON-NLS-1$
}
private void createOptionsSet(Composite composite) {
GridLayout optionSetLayout= createGridLayout(3);
optionSetLayout.marginHeight= 0;
optionSetLayout.marginWidth= 0;
Composite optionSetGroup= new Composite(composite, SWT.NONE);
optionSetGroup.setLayoutData(createGridData(GridData.FILL_BOTH, 6, 0));
optionSetGroup.setLayout(optionSetLayout);
fStandardButton= createButton(optionSetGroup, SWT.RADIO, JavadocExportMessages.getString("JavadocTreeWizardPage.standarddocletbutton.label"), createGridData(GridData.HORIZONTAL_ALIGN_FILL, 3, 0)); //$NON-NLS-1$
GridData gd= new GridData();
gd.horizontalSpan= 1;
fDestinationLabel= createLabel(optionSetGroup, SWT.NONE, JavadocExportMessages.getString("JavadocTreeWizardPage.destinationfield.label"), createGridData(GridData.HORIZONTAL_ALIGN_BEGINNING, 1, convertWidthInCharsToPixels(3))); //$NON-NLS-1$
fDestinationText= createText(optionSetGroup, SWT.SINGLE | SWT.BORDER, null, createGridData(GridData.FILL_HORIZONTAL, 1, 0));
//there really aught to be a way to specify this
((GridData) fDestinationText.getLayoutData()).widthHint= 200;
fDestinationText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
doValidation(STANDARDSTATUS);
}
});
fDestinationBrowserButton= createButton(optionSetGroup, SWT.PUSH, JavadocExportMessages.getString("JavadocTreeWizardPage.destinationbrowse.label"), createGridData(GridData.HORIZONTAL_ALIGN_FILL, 1, 0)); //$NON-NLS-1$
SWTUtil.setButtonDimensionHint(fDestinationBrowserButton);
//Option to use custom doclet
fCustomButton= createButton(optionSetGroup, SWT.RADIO, JavadocExportMessages.getString("JavadocTreeWizardPage.customdocletbutton.label"), createGridData(3)); //$NON-NLS-1$
//For Entering location of custom doclet
fDocletTypeLabel= createLabel(optionSetGroup, SWT.NONE, JavadocExportMessages.getString("JavadocTreeWizardPage.docletnamefield.label"), createGridData(GridData.HORIZONTAL_ALIGN_FILL, 1, convertWidthInCharsToPixels(3))); //$NON-NLS-1$
fDocletTypeText= createText(optionSetGroup, SWT.SINGLE | SWT.BORDER, null, createGridData(GridData.HORIZONTAL_ALIGN_FILL, 2, 0));
fDocletTypeText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
doValidation(CUSTOMSTATUS);
}
});
fDocletLabel= createLabel(optionSetGroup, SWT.NONE, JavadocExportMessages.getString("JavadocTreeWizardPage.docletpathfield.label"), createGridData(GridData.HORIZONTAL_ALIGN_FILL, 1, convertWidthInCharsToPixels(3))); //$NON-NLS-1$
fDocletText= createText(optionSetGroup, SWT.SINGLE | SWT.BORDER, null, createGridData(GridData.HORIZONTAL_ALIGN_FILL, 2, 0));
fDocletText.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
doValidation(CUSTOMSTATUS);
}
});
//Add Listeners
fCustomButton.addSelectionListener(new EnableSelectionAdapter(new Control[] { fDocletLabel, fDocletText, fDocletTypeLabel, fDocletTypeText }, new Control[] { fDestinationLabel, fDestinationText, fDestinationBrowserButton }));
fCustomButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
doValidation(CUSTOMSTATUS);
}
});
fStandardButton.addSelectionListener(new EnableSelectionAdapter(new Control[] { fDestinationLabel, fDestinationText, fDestinationBrowserButton }, new Control[] { fDocletLabel, fDocletText, fDocletTypeLabel, fDocletTypeText }));
fStandardButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
doValidation(STANDARDSTATUS);
}
});
fDestinationBrowserButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
String text= handleFolderBrowseButtonPressed(fDestinationText.getText(), fDestinationText.getShell(), JavadocExportMessages.getString("JavadocTreeWizardPage.destinationbrowsedialog.title"), //$NON-NLS-1$
JavadocExportMessages.getString("JavadocTreeWizardPage.destinationbrowsedialog.label")); //$NON-NLS-1$
fDestinationText.setText(text);
}
});
setOptionSetSettings();
}
public boolean getCustom() {
return fCustomButton.getSelection();
}
private void setOptionSetSettings() {
if (!fStore.fromStandard()) {
fCustomButton.setSelection(true);
fDocletText.setText(fStore.getDocletPath());
fDocletTypeText.setText(fStore.getDocletName());
//take the destination as the destination of the first project
fDestinationText.setText(fStore.getDestination((IJavaProject) fWizard.getSelectedProjects().iterator().next()));
fDestinationText.setEnabled(false);
fDestinationBrowserButton.setEnabled(false);
fDestinationLabel.setEnabled(false);
} else {
fStandardButton.setSelection(true);
if (fWizard.getSelectedProjects().size() == 1)
fDestinationText.setText(fStore.getDestination((IJavaProject) fWizard.getSelectedProjects().iterator().next()));
else
fDestinationText.setText(fStore.getDestination());
fDocletText.setText(fStore.getDocletPath());
fDocletTypeText.setText(fStore.getDocletName());
fDocletText.setEnabled(false);
fDocletLabel.setEnabled(false);
fDocletTypeText.setEnabled(false);
fDocletTypeLabel.setEnabled(false);
}
String javadocCommand = JavadocPreferencePage.getJavaDocCommand();
fJavadocCommandText.setText(javadocCommand);
fJavadocCommandText.setToolTipText(javadocCommand);
}
/**
* Receives of list of elements selected by the user and passes them
* to the CheckedTree. List can contain multiple projects and elements from
* different projects. If the list of seletected elements is empty a default
* project is selected.
*/
protected void setTreeChecked(IJavaElement[] sourceElements, IJavaProject project) {
if (sourceElements.length < 1)
fInputGroup.initialCheckTreeItem(project);
else {
for (int i= 0; i < sourceElements.length; i++) {
IJavaElement curr= sourceElements[i];
if (curr instanceof ICompilationUnit) {
fInputGroup.initialCheckListItem(curr);
} else if (curr instanceof IPackageFragment) {
fInputGroup.initialCheckTreeItem(curr);
} else if (curr instanceof IJavaProject) {
fInputGroup.initialCheckTreeItem(curr);
} else if (curr instanceof IPackageFragmentRoot) {
IPackageFragmentRoot root= (IPackageFragmentRoot) curr;
if (!root.isArchive())
fInputGroup.initialCheckTreeItem(curr);
}
}
}
}
private IPath[] getSourcePath(IJavaProject[] projects) {
ArrayList res= new ArrayList();
//loops through all projects and gets a list if of thier sourpaths
for (int k= 0; k < projects.length; k++) {
IJavaProject iJavaProject= projects[k];
try {
IPackageFragmentRoot[] roots= iJavaProject.getPackageFragmentRoots();
for (int i= 0; i < roots.length; i++) {
IPackageFragmentRoot curr= roots[i];
if (curr.getKind() == IPackageFragmentRoot.K_SOURCE) {
IResource resource= curr.getResource();
if (resource != null) {
IPath p= resource.getLocation();
if (p != null) {
res.add(p);
}
}
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
return (IPath[]) res.toArray(new IPath[res.size()]);
}
private IPath[] getClassPath(IJavaProject[] javaProjects) {
ArrayList res= new ArrayList();
for (int j= 0; j < javaProjects.length; j++) {
IJavaProject iJavaProject= javaProjects[j];
try {
IPath p= iJavaProject.getProject().getLocation();
if (p == null)
continue;
IPath outputLocation= p.append(iJavaProject.getOutputLocation());
String[] classPath= JavaRuntime.computeDefaultRuntimeClassPath(iJavaProject);
for (int i= 0; i < classPath.length; i++) {
String curr= classPath[i];
IPath path= new Path(curr);
if (!outputLocation.equals(path)) {
res.add(path);
}
}
} catch (CoreException e) {
JavaPlugin.log(e);
}
}
return (IPath[]) res.toArray(new IPath[res.size()]);
}
/**
* Gets a list of elements to generated javadoc for from each project.
* Javadoc can be generated for either a IPackageFragmentRoot or a ICompilationUnit.
*/
private IJavaElement[] getSourceElements(IJavaProject[] projects) {
ArrayList res= new ArrayList();
try {
Set allChecked= fInputGroup.getAllCheckedTreeItems();
Set incompletePackages= new HashSet();
for (int h= 0; h < projects.length; h++) {
IJavaProject iJavaProject= projects[h];
IPackageFragmentRoot[] roots= iJavaProject.getPackageFragmentRoots();
for (int i= 0; i < roots.length; i++) {
IPackageFragmentRoot root= roots[i];
if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
IJavaElement[] packs= root.getChildren();
for (int k= 0; k < packs.length; k++) {
IJavaElement curr= packs[k];
if (curr.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
// default packages are always incomplete
if (curr.getElementName().length() == 0 || !allChecked.contains(curr) || fInputGroup.isTreeItemGreyChecked(curr)) {
incompletePackages.add(curr.getElementName());
}
}
}
}
}
}
Iterator checkedElements= fInputGroup.getAllCheckedListItems();
while (checkedElements.hasNext()) {
Object element= checkedElements.next();
if (element instanceof ICompilationUnit) {
ICompilationUnit unit= (ICompilationUnit) element;
if (incompletePackages.contains(unit.getParent().getElementName())) {
res.add(unit);
}
}
}
Set addedPackages= new HashSet();
checkedElements= allChecked.iterator();
while (checkedElements.hasNext()) {
Object element= checkedElements.next();
if (element instanceof IPackageFragment) {
IPackageFragment fragment= (IPackageFragment) element;
String name= fragment.getElementName();
if (!incompletePackages.contains(name) && !addedPackages.contains(name)) {
res.add(fragment);
addedPackages.add(name);
}
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
return (IJavaElement[]) res.toArray(new IJavaElement[res.size()]);
}
protected void finish() {
if (fCustomButton.getSelection()) {
fStore.setDocletName(fDocletTypeText.getText());
fStore.setDocletPath(fDocletText.getText());
fStore.setFromStandard(false);
}
if (fStandardButton.getSelection()) {
fStore.setFromStandard(true);
//in case of a single project selection the personal destination is updated for
//storage in the dialog settings
if (fWizard.getSelectedProjects().size() == 1) {
fStore.setDestination((IJavaProject) fWizard.getSelectedProjects().iterator().next(), fDestinationText.getText());
}
//the destination used in javadoc generation
fStore.setDestination(fDestinationText.getText());
}
IJavaProject[] projects= (IJavaProject[]) fWizard.getSelectedProjects().toArray(new IJavaProject[fWizard.getSelectedProjects().size()]);
fStore.setProjects(projects, true);
fStore.setSourcepath(getSourcePath(projects));
fStore.setClasspath(getClassPath(projects));
fStore.setAccess(fVisibilitySelection);
fStore.setSourceElements(getSourceElements(projects));
}
protected void setProjects() {
TreeItem[] treeItems= fInputGroup.getTree().getItems();
for (int i= 0; i < treeItems.length; i++) {
if (treeItems[i].getChecked())
fWizard.addSelectedProject((IJavaProject) treeItems[i].getData());
}
}
private void doValidation(int validate) {
switch (validate) {
case PREFERENCESTATUS :
fPreferenceStatus= new StatusInfo();
fDocletStatus= new StatusInfo();
updateStatus(findMostSevereStatus());
break;
case CUSTOMSTATUS :
if (fCustomButton.getSelection()) {
fDestinationStatus= new StatusInfo();
fDocletStatus= new StatusInfo();
String doclet= fDocletTypeText.getText();
String docletPath= fDocletText.getText();
if (doclet.length() == 0) {
fDocletStatus.setError(JavadocExportMessages.getString("JavadocTreeWizardPage.nodocletname.error")); //$NON-NLS-1$
} else if (JavaConventions.validateJavaTypeName(doclet).matches(IStatus.ERROR)) {
fDocletStatus.setError(JavadocExportMessages.getString("JavadocTreeWizardPage.invaliddocletname.error")); //$NON-NLS-1$
} else if ((docletPath.length() == 0) || !validDocletPath(docletPath)) {
fDocletStatus.setError(JavadocExportMessages.getString("JavadocTreeWizardPage.invaliddocletpath.error")); //$NON-NLS-1$
}
updateStatus(findMostSevereStatus());
}
break;
case STANDARDSTATUS :
if (fStandardButton.getSelection()) {
fDestinationStatus= new StatusInfo();
fDocletStatus= new StatusInfo();
IPath path= new Path(fDestinationText.getText());
if (Path.ROOT.equals(path) || Path.EMPTY.equals(path)) {
fDestinationStatus.setError(JavadocExportMessages.getString("JavadocTreeWizardPage.nodestination.error")); //$NON-NLS-1$
}
File file= new File(path.toOSString());
if (!path.isValidPath(path.toOSString()) || file.isFile()) {
fDestinationStatus.setError(JavadocExportMessages.getString("JavadocTreeWizardPage.invaliddestination.error")); //$NON-NLS-1$
}
if ((path.append("package-list").toFile().exists()) || (path.append("index.html").toFile().exists())) //$NON-NLS-1$//$NON-NLS-2$
fDestinationStatus.setWarning(JavadocExportMessages.getString("JavadocTreeWizardPage.warning.mayoverwritefiles")); //$NON-NLS-1$
updateStatus(findMostSevereStatus());
}
break;
case TREESTATUS :
fTreeStatus= new StatusInfo();
if (fInputGroup.getAllCheckedTreeItems().size() == 0)
fTreeStatus.setError(JavadocExportMessages.getString("JavadocTreeWizardPage.invalidtreeselection.error")); //$NON-NLS-1$
updateStatus(findMostSevereStatus());
break;
case JAVADOCSTATUS:
fJavadocStatus= new StatusInfo();
IPath path= new Path(fJavadocCommandText.getText());
if (!path.toFile().isFile()) {
fJavadocStatus.setError(JavadocExportMessages.getString("JavadocTreeWizardPage.javadoccommandfile.error")); //$NON-NLS-1$
}
updateStatus(findMostSevereStatus());
break;
} //end switch
}
private boolean validDocletPath(String docletPath) {
StringTokenizer tokens= new StringTokenizer(docletPath, ";"); //$NON-NLS-1$
while (tokens.hasMoreTokens()) {
File file= new File(tokens.nextToken());
if (!file.exists())
return false;
}
return true;
}
private boolean showPreferencePage(String id, IPreferencePage page) {
final IPreferenceNode targetNode = new PreferenceNode(id, page);
PreferenceManager manager = new PreferenceManager();
manager.addToRoot(targetNode);
final PreferenceDialog dialog = new PreferenceDialog(getShell(), manager);
final boolean [] result = new boolean[] { false };
BusyIndicator.showWhile(getShell().getDisplay(), new Runnable() {
public void run() {
dialog.create();
dialog.setMessage(targetNode.getLabelText());
result[0]= (dialog.open() == Window.OK);
}
});
return result[0];
}
/**
* Finds the most severe error (if there is one)
*/
private IStatus findMostSevereStatus() {
return StatusUtil.getMostSevere(new IStatus[] { fJavadocStatus, fPreferenceStatus, fDestinationStatus, fDocletStatus, fTreeStatus, fWizardStatus });
}
public void init() {
updateStatus(new StatusInfo());
}
public void setVisible(boolean visible) {
super.setVisible(visible);
if (visible) {
doValidation(JAVADOCSTATUS);
doValidation(STANDARDSTATUS);
doValidation(CUSTOMSTATUS);
doValidation(TREESTATUS);
doValidation(PREFERENCESTATUS);
}
}
public IPath getDestination() {
if (fStandardButton.getSelection()) {
return new Path(fDestinationText.getText());
}
return null;
}
}
|
47,208 |
Bug 47208 Generate Javadoc dialog lays out too wide [javadoc]
|
If one uses a custom doclet and sets the doclet class path to a long path (e.g. with many JAR files on it), the "Generate Javadoc" dialog lays out to try and fit the full doclet class path on the screen; this results in a very wide dialog.
|
resolved fixed
|
40faefa
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-09T11:59:07Z | 2003-11-21T13:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javadocexport/JavadocWizardPage.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.javadocexport;
import java.io.File;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.jdt.ui.wizards.NewElementWizardPage;
public abstract class JavadocWizardPage extends NewElementWizardPage {
protected JavadocWizardPage(String pageName) {
super(pageName);
setTitle(JavadocExportMessages.getString("JavadocWizardPage.javadocwizardpage.description")); //$NON-NLS-1$
}
protected Button createButton(Composite composite, int style, String message, GridData gd) {
Button button= new Button(composite, style);
button.setText(message);
button.setLayoutData(gd);
return button;
}
protected GridLayout createGridLayout(int columns) {
GridLayout gl= new GridLayout();
gl.numColumns= columns;
return gl;
}
protected GridData createGridData(int flag, int hspan, int vspan, int indent) {
GridData gd= new GridData(flag);
gd.horizontalIndent= indent;
gd.horizontalSpan= hspan;
gd.verticalSpan= vspan;
return gd;
}
protected GridData createGridData(int flag, int hspan, int indent) {
GridData gd= new GridData(flag);
gd.horizontalIndent= indent;
gd.horizontalSpan= hspan;
return gd;
}
protected GridData createGridData(int hspan) {
GridData gd= new GridData();
gd.horizontalSpan= hspan;
return gd;
}
protected Label createLabel(Composite composite, int style, String message, GridData gd) {
Label label= new Label(composite, style);
label.setText(message);
label.setLayoutData(gd);
return label;
}
protected Text createText(Composite composite, int style, String message, GridData gd) {
Text text= new Text(composite, style);
if (message != null)
text.setText(message);
text.setLayoutData(gd);
return text;
}
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);
}
protected String handleFolderBrowseButtonPressed(String text, Shell shell, String title, String message) {
DirectoryDialog dialog= new DirectoryDialog(shell);
dialog.setFilterPath(text);
dialog.setText(title);
dialog.setMessage(message);
String res= dialog.open();
if (res != null) {
File file= new File(res);
if (file.exists() && file.isDirectory())
return res;
}
return text;
}
protected static class EnableSelectionAdapter extends SelectionAdapter {
private Control[] fEnable;
private Control[] fDisable;
protected EnableSelectionAdapter(Control[] enable, Control[] disable) {
super();
fEnable= enable;
fDisable= disable;
}
public void widgetSelected(SelectionEvent e) {
for (int i= 0; i < fEnable.length; i++) {
fEnable[i].setEnabled(true);
}
for (int i= 0; i < fDisable.length; i++) {
fDisable[i].setEnabled(false);
}
validate();
}
//copied from WizardNewProjectCreationPage
public void validate() {
}
} //end class EnableSelectionAdapter
protected static class ToggleSelectionAdapter extends SelectionAdapter {
Control[] controls;
protected ToggleSelectionAdapter(Control[] controls) {
this.controls= controls;
}
public void widgetSelected(SelectionEvent e) {
for (int i= 0; i < controls.length; i++) {
Control control= controls[i];
control.setEnabled(!control.getEnabled());
}
validate();
}
public void validate() {
}
} //end class ToggleSelection Adapter
}
|
45,585 |
Bug 45585 [syntax highlighting] Task Tags parsing bug
|
1) Add "BUG" to your Task Tags 2) Comment the following code case Level.DEBUG_INT : it will recognize "BUG" in "DEBUG" as a Task Tag.
|
resolved fixed
|
3900959
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-09T17:20:07Z | 2003-10-27T10:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/JavaCommentScanner.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 java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import org.eclipse.core.runtime.Preferences;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.ui.text.IColorManager;
import org.eclipse.jdt.ui.text.IJavaColorConstants;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.rules.IToken;
import org.eclipse.jface.text.rules.IWordDetector;
import org.eclipse.jface.text.rules.Token;
import org.eclipse.jface.text.rules.WordRule;
import org.eclipse.jface.util.PropertyChangeEvent;
/**
* AbstractJavaCommentScanner.java
*/
public class JavaCommentScanner extends AbstractJavaScanner{
private static class TaskTagDetector implements IWordDetector {
public boolean isWordStart(char c) {
return Character.isLetter(c);
}
public boolean isWordPart(char c) {
return Character.isLetter(c);
}
}
private class TaskTagRule extends WordRule {
private IToken fToken;
public TaskTagRule(IToken token) {
super(new TaskTagDetector(), Token.UNDEFINED);
fToken= token;
}
public void clearTaskTags() {
fWords.clear();
}
public void addTaskTags(String value) {
String[] tasks= split(value, ","); //$NON-NLS-1$
for (int i= 0; i < tasks.length; i++) {
if (tasks[i].length() > 0) {
addWord(tasks[i], fToken);
}
}
}
private String[] split(String value, String delimiters) {
StringTokenizer tokenizer= new StringTokenizer(value, delimiters);
int size= tokenizer.countTokens();
String[] tokens= new String[size];
int i= 0;
while (i < size)
tokens[i++]= tokenizer.nextToken();
return tokens;
}
}
private static final String COMPILER_TASK_TAGS= JavaCore.COMPILER_TASK_TAGS;
protected static final String TASK_TAG= IJavaColorConstants.TASK_TAG;
private TaskTagRule fTaskTagRule;
private Preferences fCorePreferenceStore;
private String fDefaultTokenProperty;
private String[] fTokenProperties;
public JavaCommentScanner(IColorManager manager, IPreferenceStore store, Preferences coreStore, String defaultTokenProperty) {
this(manager, store, coreStore, defaultTokenProperty, new String[] { defaultTokenProperty, TASK_TAG });
}
public JavaCommentScanner(IColorManager manager, IPreferenceStore store, Preferences coreStore, String defaultTokenProperty, String[] tokenProperties) {
super(manager, store);
fCorePreferenceStore= coreStore;
fDefaultTokenProperty= defaultTokenProperty;
fTokenProperties= tokenProperties;
initialize();
}
/*
* @see AbstractJavaScanner#createRules()
*/
protected List createRules() {
List list= new ArrayList();
if (fCorePreferenceStore != null) {
// Add rule for Task Tags.
fTaskTagRule= new TaskTagRule(getToken(TASK_TAG));
String tasks= fCorePreferenceStore.getString(COMPILER_TASK_TAGS);
fTaskTagRule.addTaskTags(tasks);
list.add(fTaskTagRule);
}
setDefaultReturnToken(getToken(fDefaultTokenProperty));
return list;
}
/*
* @see org.eclipse.jdt.internal.ui.text.AbstractJavaScanner#affectsBehavior(org.eclipse.jface.util.PropertyChangeEvent)
*/
public boolean affectsBehavior(PropertyChangeEvent event) {
return event.getProperty().equals(COMPILER_TASK_TAGS) || super.affectsBehavior(event);
}
/*
* @see org.eclipse.jdt.internal.ui.text.AbstractJavaScanner#adaptToPreferenceChange(org.eclipse.jface.util.PropertyChangeEvent)
*/
public void adaptToPreferenceChange(PropertyChangeEvent event) {
if (fTaskTagRule != null && event.getProperty().equals(COMPILER_TASK_TAGS)) {
Object value= event.getNewValue();
if (value instanceof String) {
fTaskTagRule.clearTaskTags();
fTaskTagRule.addTaskTags((String) value);
}
} else if (super.affectsBehavior(event)) {
super.adaptToPreferenceChange(event);
}
}
/*
* @see org.eclipse.jdt.internal.ui.text.AbstractJavaScanner#getTokenProperties()
*/
protected String[] getTokenProperties() {
return fTokenProperties;
}
}
|
49,802 |
Bug 49802 comparing with local history leaks an Image
|
M6 - open a java file - make a change to it and save it - in the open editor right-click -> Local History > Compare With... - Close the subsequent dialog This leaks the image from the "Java Source Compare" title bar each time it's invoked. Here's the creation trace: at org.eclipse.swt.graphics.Device.new_Object(Device.java:648) at org.eclipse.swt.graphics.Image.<init>(Image.java:629) at org.eclipse.jface.resource.ImageDescriptor.createImage (ImageDescriptor.java:135) at org.eclipse.jface.resource.ImageDescriptor.createImage (ImageDescriptor.java:94) at org.eclipse.jface.resource.ImageDescriptor.createImage (ImageDescriptor.java:83) at org.eclipse.jdt.internal.ui.compare.JavaCompareUtilities.getImage (JavaCompareUtilities.java:230) at org.eclipse.jdt.internal.ui.compare.JavaCompareWithEditionAction.run (JavaCompareWithEditionAction.java:76) at org.eclipse.jdt.internal.ui.compare.JavaHistoryAction.run (JavaHistoryAction.java:341) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:509) at org.eclipse.jface.action.ActionContributionItem.access$2 (ActionContributionItem.java:461) at org.eclipse.jface.action.ActionContributionItem$5.handleEvent (ActionContributionItem.java:408) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:833) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2318) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1999) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1506) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1482) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:246) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:47) at org.eclipse.core.internal.runtime.PlatformActivator$1.run (PlatformActivator.java:226) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:85) 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:279) at org.eclipse.core.launcher.Main.run(Main.java:742) at org.eclipse.core.launcher.Main.main(Main.java:581)
|
resolved fixed
|
159696c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-12T11:11:46Z | 2004-01-09T23:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/compare/JavaCompareWithEditionAction.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.compare;
import java.util.ResourceBundle;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.internal.corext.textmanipulation.TextBuffer;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.compare.*;
/**
* Provides "Replace from local history" for Java elements.
*/
public class JavaCompareWithEditionAction extends JavaHistoryAction {
private static final String BUNDLE_NAME= "org.eclipse.jdt.internal.ui.compare.CompareWithEditionAction"; //$NON-NLS-1$
public JavaCompareWithEditionAction() {
super(false);
}
public void run(ISelection selection) {
String errorTitle= CompareMessages.getString("CompareWithHistory.title"); //$NON-NLS-1$
String errorMessage= CompareMessages.getString("CompareWithHistory.internalErrorMessage"); //$NON-NLS-1$
IMember input= getEditionElement(selection);
if (input == null) {
String invalidSelectionMessage= CompareMessages.getString("CompareWithHistory.invalidSelectionMessage"); //$NON-NLS-1$
MessageDialog.openInformation(getShell(), errorTitle, invalidSelectionMessage);
return;
}
IFile file= getFile(input);
if (file == null) {
MessageDialog.openError(getShell(), errorTitle, errorMessage);
return;
}
boolean inEditor= beingEdited(file);
if (inEditor)
input= (IMember) getWorkingCopy(input);
// get a TextBuffer
TextBuffer buffer= null;
try {
buffer= TextBuffer.acquire(file);
ITypedElement target= new JavaTextBufferNode(buffer, inEditor);
ITypedElement[] editions= buildEditions(target, file);
ResourceBundle bundle= ResourceBundle.getBundle(BUNDLE_NAME);
EditionSelectionDialog d= new EditionSelectionDialog(getShell(), bundle);
d.setHelpContextId(IJavaHelpContextIds.COMPARE_ELEMENT_WITH_HISTORY_DIALOG);
d.setCompareMode(true);
d.setEditionTitleImage(JavaCompareUtilities.getImage(input));
d.selectEdition(target, editions, input);
} catch(CoreException ex) {
ExceptionHandler.handle(ex, getShell(), errorTitle, errorMessage);
} finally {
if (buffer != null)
TextBuffer.release(buffer);
}
}
}
|
49,719 |
Bug 49719 wrong-sounding phrase in string externalization dialog [refactoring] [nls]
|
M6, this is a bit picky - select a java project in the Package Explorer, right-click, invoke Source -> Find Strings to Externalize... - the text on the next dialog should say "X non-externalized string(s) found."
|
resolved fixed
|
6d73a50
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-12T11:47:29Z | 2004-01-08T19:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/FindStringsToExternalizeAction.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.ui.actions;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
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.graphics.Point;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.help.WorkbenchHelp;
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.JavaModelException;
import org.eclipse.jdt.core.compiler.InvalidInputException;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.internal.corext.refactoring.nls.NLSElement;
import org.eclipse.jdt.internal.corext.refactoring.nls.NLSLine;
import org.eclipse.jdt.internal.corext.refactoring.nls.NLSScanner;
import org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgUtils;
import org.eclipse.jdt.internal.corext.refactoring.util.ResourceUtil;
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.refactoring.actions.ListDialog;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.viewsupport.ListContentProvider;
/**
* Find all Strings in a package or project that are not externalized yet.
* <p>
* The action is applicable to selections containing projects or packages.
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 2.0
*/
public class FindStringsToExternalizeAction extends SelectionDispatchAction {
private NonNLSElement[] fElements;
/**
* Creates a new <code>FindStringsToExternalizeAction</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 FindStringsToExternalizeAction(IWorkbenchSite site) {
super(site);
setText(ActionMessages.getString("FindStringsToExternalizeAction.label")); //$NON-NLS-1$
fElements= new NonNLSElement[0];
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.FIND_STRINGS_TO_EXTERNALIZE_ACTION);
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
public void selectionChanged(IStructuredSelection selection) {
try {
setEnabled(computeEnablementState(selection));
} catch (JavaModelException e) {
JavaPlugin.log(e);
setEnabled(false);//no ui - happens on selection changes
}
}
private boolean computeEnablementState(IStructuredSelection selection) throws JavaModelException {
if (selection.isEmpty())
return false;
for (Iterator iter= selection.iterator(); iter.hasNext();) {
Object element= iter.next();
if (!(element instanceof IJavaElement))
return false;
IJavaElement javaElement= (IJavaElement)element;
if (! javaElement.exists() || javaElement.isReadOnly())
return false;
int elementType= javaElement.getElementType();
if (elementType != IJavaElement.PACKAGE_FRAGMENT &&
elementType != IJavaElement.PACKAGE_FRAGMENT_ROOT &&
elementType != IJavaElement.JAVA_PROJECT)
return false;
if (elementType == IJavaElement.PACKAGE_FRAGMENT_ROOT){
IPackageFragmentRoot root= (IPackageFragmentRoot)javaElement;
if (root.isExternal() || ReorgUtils.isClassFolder(root))
return false;
}
}
return true;
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
public void run(final IStructuredSelection selection) {
try {
PlatformUI.getWorkbench().getActiveWorkbenchWindow().run(true, true, createRunnable(selection));
} catch(InvocationTargetException e) {
ExceptionHandler.handle(e, getShell(),
ActionMessages.getString("FindStringsToExternalizeAction.dialog.title"), //$NON-NLS-1$
ActionMessages.getString("FindStringsToExternalizeAction.error.message")); //$NON-NLS-1$
return;
} catch(InterruptedException e) {
//ok
return;
}
showResults();
}
private IRunnableWithProgress createRunnable(final IStructuredSelection selection) {
return new IRunnableWithProgress() {
public void run(IProgressMonitor pm) {
fElements= doRun(selection, pm);
}
};
}
private NonNLSElement[] doRun(IStructuredSelection selection, IProgressMonitor pm) {
List elements= getSelectedElementList(selection);
if (elements == null || elements.isEmpty())
return new NonNLSElement[0];
pm.beginTask(ActionMessages.getString("FindStringsToExternalizeAction.find_strings"), elements.size()); //$NON-NLS-1$
try{
List l= new ArrayList();
for (Iterator iter= elements.iterator(); iter.hasNext();) {
IJavaElement element= (IJavaElement) iter.next();
if (element.getElementType() == IJavaElement.PACKAGE_FRAGMENT)
l.addAll(analyze((IPackageFragment) element, new SubProgressMonitor(pm, 1)));
else if (element.getElementType() == IJavaElement.PACKAGE_FRAGMENT_ROOT)
l.addAll(analyze((IPackageFragmentRoot) element, new SubProgressMonitor(pm, 1)));
if (element.getElementType() == IJavaElement.JAVA_PROJECT)
l.addAll(analyze((IJavaProject) element, new SubProgressMonitor(pm, 1)));
}
return (NonNLSElement[]) l.toArray(new NonNLSElement[l.size()]);
} catch(JavaModelException e) {
ExceptionHandler.handle(e,
getDialogTitle(),
ActionMessages.getString("FindStringsToExternalizeAction.error.message")); //$NON-NLS-1$
return new NonNLSElement[0];
} finally{
pm.done();
}
}
private void showResults() {
if (noStrings())
MessageDialog.openInformation(getShell(),
getDialogTitle(),
ActionMessages.getString("FindStringsToExternalizeAction.noStrings")); //$NON-NLS-1$
else
new NonNLSListDialog(getShell(), fElements, countStrings()).open();
}
private boolean noStrings() {
for (int i = 0; i < fElements.length; i++) {
if (fElements[i].count != 0)
return false;
}
return true;
}
/*
* returns List of Strings
*/
private List analyze(IPackageFragment pack, IProgressMonitor pm) throws JavaModelException{
try{
if (pack == null)
return new ArrayList(0);
ICompilationUnit[] cus= pack.getCompilationUnits();
pm.beginTask("", cus.length); //$NON-NLS-1$
pm.setTaskName(pack.getElementName());
List l= new ArrayList(cus.length);
for (int i= 0; i < cus.length; i++){
pm.subTask(cus[i].getElementName());
NonNLSElement element = analyze(cus[i]);
if (element != null)
l.add(element);
pm.worked(1);
if (pm.isCanceled())
throw new OperationCanceledException();
}
return l;
} finally {
pm.done();
}
}
/*
* returns List of Strings
*/
private List analyze(IPackageFragmentRoot sourceFolder, IProgressMonitor pm) throws JavaModelException{
try{
IJavaElement[] children= sourceFolder.getChildren();
pm.beginTask("", children.length); //$NON-NLS-1$
pm.setTaskName(sourceFolder.getElementName());
List result= new ArrayList();
for (int i= 0; i < children.length; i++) {
IJavaElement iJavaElement= children[i];
if (iJavaElement.getElementType() == IJavaElement.PACKAGE_FRAGMENT){
IPackageFragment pack= (IPackageFragment)iJavaElement;
if (! pack.isReadOnly())
result.addAll(analyze(pack, new SubProgressMonitor(pm, 1)));
else
pm.worked(1);
} else
pm.worked(1);
}
return result;
} finally{
pm.done();
}
}
/*
* returns List of Strings
*/
private List analyze(IJavaProject project, IProgressMonitor pm) throws JavaModelException{
try{
IPackageFragment[] packs= project.getPackageFragments();
pm.beginTask("", packs.length); //$NON-NLS-1$
List result= new ArrayList();
for (int i= 0; i < packs.length; i++) {
if (! packs[i].isReadOnly())
result.addAll(analyze(packs[i], new SubProgressMonitor(pm, 1)));
else
pm.worked(1);
}
return result;
} finally{
pm.done();
}
}
private int countStrings(){
int found= 0;
for (int i= 0; i < fElements.length; i++)
found += fElements[i].count;
return found;
}
private NonNLSElement analyze(ICompilationUnit cu) throws JavaModelException{
int count = countNotExternalizedStrings(cu);
if (count == 0)
return null;
else
return new NonNLSElement(cu, count);
}
private int countNotExternalizedStrings(ICompilationUnit cu){
try{
NLSLine[] lines= NLSScanner.scan(cu);
int result= 0;
for (int i= 0; i < lines.length; i++) {
result += countNotExternalizedStrings(lines[i]);
}
return result;
}catch(JavaModelException e) {
ExceptionHandler.handle(e,
getDialogTitle(),
ActionMessages.getString("FindStringsToExternalizeAction.error.message")); //$NON-NLS-1$
return 0;
}catch(InvalidInputException iie) {
JavaPlugin.log(iie);
return 0;
}
}
private int countNotExternalizedStrings(NLSLine line){
int result= 0;
NLSElement[] elements= line.getElements();
for (int i= 0; i < elements.length; i++){
if (! elements[i].hasTag())
result++;
}
return result;
}
/**
* returns <code>List</code> of <code>IPackageFragments</code>, <code>IPackageFragmentRoots</code> or
* <code>IJavaProjects</code> (all entries are of the same kind)
*/
private static List getSelectedElementList(IStructuredSelection selection) {
if (selection == null)
return null;
return selection.toList();
}
//-------private classes --------------
private static class NonNLSListDialog extends ListDialog {
private static final int OPEN_BUTTON_ID= IDialogConstants.CLIENT_ID + 1;
private Button fOpenButton;
NonNLSListDialog(Shell parent, NonNLSElement[] input, int count) {
super(parent);
setInput(Arrays.asList(input));
setTitle(ActionMessages.getString("FindStringsToExternalizeAction.dialog.title")); //$NON-NLS-1$
setMessage(ActionMessages.getFormattedString("FindStringsToExternalizeAction.not_externalized", new Object[] {new Integer(count)} )); //$NON-NLS-1$
setContentProvider(new ListContentProvider());
setLabelProvider(createLabelProvider());
}
public void create() {
setShellStyle(SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MIN);
super.create();
}
protected Point getInitialSize() {
return getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
}
protected Control createDialogArea(Composite parent) {
Composite result= (Composite)super.createDialogArea(parent);
getTableViewer().addSelectionChangedListener(new ISelectionChangedListener(){
public void selectionChanged(SelectionChangedEvent event){
if (fOpenButton != null){
fOpenButton.setEnabled(! getTableViewer().getSelection().isEmpty());
}
}
});
getTableViewer().getTable().addSelectionListener(new SelectionAdapter(){
public void widgetDefaultSelected(SelectionEvent e) {
NonNLSElement element= (NonNLSElement)e.item.getData();
openWizard(element.cu);
}
});
getTableViewer().getTable().setFocus();
applyDialogFont(result);
return result;
}
protected void createButtonsForButtonBar(Composite parent) {
fOpenButton= createButton(parent, OPEN_BUTTON_ID, ActionMessages.getString("FindStringsToExternalizeAction.button.label"), true); //$NON-NLS-1$
fOpenButton.setEnabled(false);
//looks like a 'close' but it a 'cancel'
createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CLOSE_LABEL, false);
}
protected void buttonPressed(int buttonId) {
if (buttonId != OPEN_BUTTON_ID){
super.buttonPressed(buttonId);
return;
}
ISelection s= getTableViewer().getSelection();
if (s instanceof IStructuredSelection){
IStructuredSelection ss= (IStructuredSelection)s;
if (ss.getFirstElement() instanceof NonNLSElement)
openWizard(((NonNLSElement)ss.getFirstElement()).cu);
}
}
private void openWizard(ICompilationUnit unit) {
try {
ExternalizeStringsAction.openExternalizeStringsWizard(getShell(), unit);
} catch (JavaModelException e) {
ExceptionHandler.handle(e,
ActionMessages.getString("FindStringsToExternalizeAction.dialog.title"), //$NON-NLS-1$
ActionMessages.getString("FindStringsToExternalizeAction.error.message")); //$NON-NLS-1$
}
}
private static LabelProvider createLabelProvider() {
return new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT){
public String getText(Object element) {
NonNLSElement nlsel= (NonNLSElement)element;
String elementName= ResourceUtil.getResource(nlsel.cu).getFullPath().toString();
return ActionMessages.getFormattedString(
"FindStringsToExternalizeAction.foundStrings", //$NON-NLS-1$
new Object[] {new Integer(nlsel.count), elementName} );
}
public Image getImage(Object element) {
return super.getImage(((NonNLSElement)element).cu);
}
};
}
/*
* @see org.eclipse.jface.window.Window#configureShell(Shell)
*/
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
WorkbenchHelp.setHelp(newShell, IJavaHelpContextIds.NONNLS_DIALOG);
}
}
private static class NonNLSElement{
ICompilationUnit cu;
int count;
NonNLSElement(ICompilationUnit cu, int count){
this.cu= cu;
this.count= count;
}
}
private String getDialogTitle() {
return ActionMessages.getString("FindStringsToExternalizeAction.dialog.title"); //$NON-NLS-1$
}
}
|
38,513 |
Bug 38513 JavaModel not updated when creating an "empty" IClasspathContainer [package explorer]
|
I have implemented IClasspathContainer. When I add my container to a java project via Project Properties > JavaBuild Path > Libraries > Add Library wizard, the Package Explorer view is not updated if my container resolves to an empty classpath and the container does not appear in the view. If I then close and then reopen the java project the container appears in the Package Explorer view correctly, even if the container resolves to an empty classpath. This problem can be reproduced in Eclipse 2.1 as follows: 1. Open the Java Perspective, Package Explorer view. 2. Create a new Java Project. 3. Right-click the project and select Properties > Java Build Path > Libraries (tab). 4. Note the default JRE System Libraries container should appear in the list. 5. Select the Add Library button and then select the Required Plug-ins container from the Add Library page. 6. Then select Next and then Finish to return to the Properties page. 7. In the Properties page select OK to return to the Package Explorer view. 8. Note the Package Explorer view has not updated and the Required Plug-ins container is not displayed. 9. Right-click on the java project and select Close Project form the menu. 10. Then right-click on the java project and select Open Project form the menu. 11. Note the Package Explorer view has now updated and the Required Plug-ins container is now displayed. I believe the JavaModel is not being updated if a newly added container resolves to an empty classpath. This is probably incorrect or lacking functionality in the special case of an "empty" IClasspathContainer and therefore some notification to update the JavaModel, under these circumstances, may be required. This problem was recreated under Windows 2000 SP1, Eclipse 2.1 Build 200303272130, and Sun Java 2 SDK Standard Edition v1.3.1. Regards, Joss Wright
|
resolved fixed
|
0abbaef
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-12T17:07:07Z | 2003-06-05T13:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/packageview/PackageExplorerContentProvider.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.packageview;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.widgets.Control;
import org.eclipse.jface.viewers.IBasicPropertyConstants;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jdt.core.*;
import org.eclipse.jdt.ui.StandardJavaElementContentProvider;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
/**
* Content provider for the PackageExplorer.
*
* <p>
* Since 2.1 this content provider can provide the children for flat or hierarchical
* layout. The hierarchical layout is done by delegating to the <code>PackageFragmentProvider</code>.
* </p>
*
* @see org.eclipse.jdt.ui.StandardJavaElementContentProvider
* @see org.eclipse.jdt.internal.ui.packageview.PackageFragmentProvider
*/
class PackageExplorerContentProvider extends StandardJavaElementContentProvider implements ITreeContentProvider, IElementChangedListener {
private TreeViewer fViewer;
private Object fInput;
private boolean fIsFlatLayout;
private PackageFragmentProvider fPackageFragmentProvider= new PackageFragmentProvider();
private int fPendingChanges;
private PackageExplorerPart fPart;
/**
* Creates a new content provider for Java elements.
*/
public PackageExplorerContentProvider(PackageExplorerPart part, boolean provideMembers, boolean provideWorkingCopy) {
super(provideMembers, provideWorkingCopy);
fPart= part;
}
/* (non-Javadoc)
* Method declared on IElementChangedListener.
*/
public void elementChanged(final ElementChangedEvent event) {
try {
processDelta(event.getDelta());
} catch(JavaModelException e) {
JavaPlugin.log(e);
}
}
/* (non-Javadoc)
* Method declared on IContentProvider.
*/
public void dispose() {
super.dispose();
JavaCore.removeElementChangedListener(this);
fPackageFragmentProvider.dispose();
}
// ------ Code which delegates to PackageFragmentProvider ------
private boolean needsToDelegateGetChildren(Object element) {
int type= -1;
if (element instanceof IJavaElement)
type= ((IJavaElement)element).getElementType();
return (!fIsFlatLayout && (type == IJavaElement.PACKAGE_FRAGMENT || type == IJavaElement.PACKAGE_FRAGMENT_ROOT || type == IJavaElement.JAVA_PROJECT));
}
public Object[] getChildren(Object parentElement) {
Object[] children= NO_CHILDREN;
try {
if (parentElement instanceof IJavaModel)
return concatenate(getJavaProjects((IJavaModel)parentElement), getNonJavaProjects((IJavaModel)parentElement));
if (parentElement instanceof ClassPathContainer)
return getContainerPackageFragmentRoots((ClassPathContainer)parentElement);
if (parentElement instanceof IProject)
return ((IProject)parentElement).members();
if (needsToDelegateGetChildren(parentElement)) {
Object[] packageFragments= fPackageFragmentProvider.getChildren(parentElement);
children= getWithParentsResources(packageFragments, parentElement);
} else {
children= super.getChildren(parentElement);
}
if (parentElement instanceof IJavaProject) {
IJavaProject project= (IJavaProject)parentElement;
return rootsAndContainers(project, children);
}
else
return children;
} catch (CoreException e) {
return NO_CHILDREN;
}
}
private Object[] rootsAndContainers(IJavaProject project, Object[] roots) throws JavaModelException {
List result= new ArrayList(roots.length);
Set containers= new HashSet(roots.length);
Set containedRoots= new HashSet(roots.length);
IClasspathEntry[] entries= project.getRawClasspath();
for (int i= 0; i < entries.length; i++) {
IClasspathEntry entry= entries[i];
if (entry != null && entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
IPackageFragmentRoot[] roots1= project.findPackageFragmentRoots(entry);
if (roots1.length > 0) {
containedRoots.addAll(Arrays.asList(roots1));
containers.add(entry);
}
}
}
for (int i= 0; i < roots.length; i++) {
if (roots[i] instanceof IPackageFragmentRoot) {
if (!containedRoots.contains(roots[i])) {
result.add(roots[i]);
}
} else {
result.add(roots[i]);
}
}
for (Iterator each= containers.iterator(); each.hasNext();) {
IClasspathEntry element= (IClasspathEntry) each.next();
result.add(new ClassPathContainer(project, element));
}
return result.toArray();
}
private Object[] getContainerPackageFragmentRoots(ClassPathContainer container) {
return container.getPackageFragmentRoots();
}
private Object[] getNonJavaProjects(IJavaModel model) throws JavaModelException {
return model.getNonJavaResources();
}
public Object getParent(Object child) {
if (needsToDelegateGetParent(child)) {
return fPackageFragmentProvider.getParent(child);
} else
return super.getParent(child);
}
protected Object internalGetParent(Object element) {
// since we insert logical package containers we have to fix
// up the parent for package fragment roots so that they refer
// to the container and containers refere to the project
//
if (element instanceof IPackageFragmentRoot) {
IPackageFragmentRoot root= (IPackageFragmentRoot)element;
IJavaProject project= root.getJavaProject();
try {
IClasspathEntry[] entries= project.getRawClasspath();
for (int i= 0; i < entries.length; i++) {
IClasspathEntry entry= entries[i];
if (entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
if (ClassPathContainer.contains(project, entry, root))
return new ClassPathContainer(project, entry);
}
}
} catch (JavaModelException e) {
// fall through
}
}
if (element instanceof ClassPathContainer) {
return ((ClassPathContainer)element).getJavaProject();
}
return super.internalGetParent(element);
}
private boolean needsToDelegateGetParent(Object element) {
int type= -1;
if (element instanceof IJavaElement)
type= ((IJavaElement)element).getElementType();
return (!fIsFlatLayout && type == IJavaElement.PACKAGE_FRAGMENT);
}
/**
* Returns the given objects with the resources of the parent.
*/
private Object[] getWithParentsResources(Object[] existingObject, Object parent) {
Object[] objects= super.getChildren(parent);
List list= new ArrayList();
// Add everything that is not a PackageFragment
for (int i= 0; i < objects.length; i++) {
Object object= objects[i];
if (!(object instanceof IPackageFragment)) {
list.add(object);
}
}
if (existingObject != null)
list.addAll(Arrays.asList(existingObject));
return list.toArray();
}
/* (non-Javadoc)
* Method declared on IContentProvider.
*/
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
super.inputChanged(viewer, oldInput, newInput);
fPackageFragmentProvider.inputChanged(viewer, oldInput, newInput);
fViewer= (TreeViewer)viewer;
if (oldInput == null && newInput != null) {
JavaCore.addElementChangedListener(this);
} else if (oldInput != null && newInput == null) {
JavaCore.removeElementChangedListener(this);
}
fInput= newInput;
}
// ------ delta processing ------
/**
* Processes a delta recursively. When more than two children are affected the
* tree is fully refreshed starting at this node. The delta is processed in the
* current thread but the viewer updates are posted to the UI thread.
*/
private void processDelta(IJavaElementDelta delta) throws JavaModelException {
int kind= delta.getKind();
int flags= delta.getFlags();
IJavaElement element= delta.getElement();
int elementType= element.getElementType();
if (elementType != IJavaElement.JAVA_MODEL && elementType != IJavaElement.JAVA_PROJECT) {
IJavaProject proj= element.getJavaProject();
if (proj == null || !proj.getProject().isOpen()) // TODO: Not needed if parent already did the 'open' check!
return;
}
if (!fIsFlatLayout && elementType == IJavaElement.PACKAGE_FRAGMENT) {
fPackageFragmentProvider.processDelta(delta);
if (processResourceDeltas(delta.getResourceDeltas(), element))
return;
IJavaElementDelta[] affectedChildren= delta.getAffectedChildren();
processAffectedChildren(affectedChildren);
return;
}
if (elementType == IJavaElement.COMPILATION_UNIT) {
ICompilationUnit cu= (ICompilationUnit) element;
if (!JavaModelUtil.isPrimary(cu)) {
return;
}
if (!getProvideWorkingCopy() && cu.isWorkingCopy()) {
return;
}
if ((kind == IJavaElementDelta.CHANGED) && !isStructuralCUChange(flags)) {
return; // test moved ahead
}
if (!isOnClassPath(cu)) { // TODO: isOnClassPath expensive! Should be put after all cheap tests
return;
}
if (!JavaPlugin.USE_WORKING_COPY_OWNERS && cu.isWorkingCopy()) {
if (kind == IJavaElementDelta.REMOVED || kind == IJavaElementDelta.ADDED) {
// switch between original and working copy or vice versa
postRefresh(JavaModelUtil.toOriginal(cu), false);
return;
}
}
}
if (elementType == IJavaElement.JAVA_PROJECT) {
// handle open and closing of a project
if ((flags & (IJavaElementDelta.F_CLOSED | IJavaElementDelta.F_OPENED)) != 0) {
postRefresh(element);
return;
}
}
if (kind == IJavaElementDelta.REMOVED) {
Object parent= internalGetParent(element);
postRemove(element);
if (parent instanceof IPackageFragment)
postUpdateIcon((IPackageFragment)parent);
// we are filtering out empty subpackages, so we
// a package becomes empty we remove it from the viewer.
if (isPackageFragmentEmpty(element.getParent())) {
if (fViewer.testFindItem(parent) != null)
postRefresh(internalGetParent(parent));
}
return;
}
if (kind == IJavaElementDelta.ADDED) {
Object parent= internalGetParent(element);
// we are filtering out empty subpackages, so we
// have to handle additions to them specially.
if (parent instanceof IPackageFragment) {
Object grandparent= internalGetParent(parent);
// 1GE8SI6: ITPJUI:WIN98 - Rename is not shown in Packages View
// avoid posting a refresh to an unvisible parent
if (parent.equals(fInput)) {
postRefresh(parent);
} else {
// refresh from grandparent if parent isn't visible yet
if (fViewer.testFindItem(parent) == null)
postRefresh(grandparent);
else {
postRefresh(parent);
}
}
return;
} else {
postAdd(parent, element);
}
}
if (elementType == IJavaElement.COMPILATION_UNIT) {
if (kind == IJavaElementDelta.CHANGED) {
// isStructuralCUChange already performed above
element= JavaModelUtil.toOriginal((ICompilationUnit) element);
postRefresh(element);
updateSelection(delta);
}
return;
}
// no changes possible in class files
if (elementType == IJavaElement.CLASS_FILE)
return;
if (elementType == IJavaElement.PACKAGE_FRAGMENT_ROOT) {
// the contents of an external JAR has changed
if ((flags & IJavaElementDelta.F_ARCHIVE_CONTENT_CHANGED) != 0) {
postRefresh(element);
return;
}
// the source attachment of a JAR has changed
if ((flags & (IJavaElementDelta.F_SOURCEATTACHED | IJavaElementDelta.F_SOURCEDETACHED)) != 0)
postUpdateIcon(element);
if (isClassPathChange(delta)) {
// throw the towel and do a full refresh of the affected java project.
postRefresh(element.getJavaProject());
return;
}
}
if (processResourceDeltas(delta.getResourceDeltas(), element))
return;
handleAffectedChildren(delta, element);
}
private static boolean isStructuralCUChange(int flags) {
// No refresh on working copy creation (F_PRIMARY_WORKING_COPY)
return ((flags & IJavaElementDelta.F_CHILDREN) != 0) || ((flags & (IJavaElementDelta.F_CONTENT | IJavaElementDelta.F_FINE_GRAINED)) == IJavaElementDelta.F_CONTENT);
}
private void handleAffectedChildren(IJavaElementDelta delta, IJavaElement element) throws JavaModelException {
IJavaElementDelta[] affectedChildren= delta.getAffectedChildren();
if (affectedChildren.length > 1) {
// a package fragment might become non empty refresh from the parent
if (element instanceof IPackageFragment) {
IJavaElement parent= (IJavaElement)internalGetParent(element);
// 1GE8SI6: ITPJUI:WIN98 - Rename is not shown in Packages View
// avoid posting a refresh to an unvisible parent
if (element.equals(fInput)) {
postRefresh(element);
} else {
postRefresh(parent);
}
return;
}
// more than one child changed, refresh from here downwards
if (element instanceof IPackageFragmentRoot)
postRefresh(skipProjectPackageFragmentRoot((IPackageFragmentRoot)element));
else
postRefresh(element);
return;
}
processAffectedChildren(affectedChildren);
}
protected void processAffectedChildren(IJavaElementDelta[] affectedChildren) throws JavaModelException {
for (int i= 0; i < affectedChildren.length; i++) {
processDelta(affectedChildren[i]);
}
}
private boolean isOnClassPath(ICompilationUnit element) {
IJavaProject project= element.getJavaProject();
if (project == null || !project.exists())
return false;
return project.isOnClasspath(element);
}
/**
* Updates the selection. It finds newly added elements
* and selects them.
*/
private void updateSelection(IJavaElementDelta delta) {
final IJavaElement addedElement= findAddedElement(delta);
if (addedElement != null) {
final StructuredSelection selection= new StructuredSelection(addedElement);
postRunnable(new Runnable() {
public void run() {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
// 19431
// if the item is already visible then select it
if (fViewer.testFindItem(addedElement) != null)
fViewer.setSelection(selection);
}
}
});
}
}
private IJavaElement findAddedElement(IJavaElementDelta delta) {
if (delta.getKind() == IJavaElementDelta.ADDED)
return delta.getElement();
IJavaElementDelta[] affectedChildren= delta.getAffectedChildren();
for (int i= 0; i < affectedChildren.length; i++)
return findAddedElement(affectedChildren[i]);
return null;
}
/**
* Updates the package icon
*/
private void postUpdateIcon(final IJavaElement element) {
postRunnable(new Runnable() {
public void run() {
// 1GF87WR: ITPUI:ALL - SWTEx + NPE closing a workbench window.
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed())
fViewer.update(element, new String[]{IBasicPropertyConstants.P_IMAGE});
}
});
}
/**
1 * Process a resource delta.
*
* @return true if the parent got refreshed
*/
private boolean processResourceDelta(IResourceDelta delta, Object parent) {
int status= delta.getKind();
int flags= delta.getFlags();
IResource resource= delta.getResource();
// filter out changes affecting the output folder
if (resource == null)
return false;
// this could be optimized by handling all the added children in the parent
if ((status & IResourceDelta.REMOVED) != 0) {
if (parent instanceof IPackageFragment) {
// refresh one level above to deal with empty package filtering properly
postRefresh(internalGetParent(parent));
return true;
} else
postRemove(resource);
}
if ((status & IResourceDelta.ADDED) != 0) {
if (parent instanceof IPackageFragment) {
// refresh one level above to deal with empty package filtering properly
postRefresh(internalGetParent(parent));
return true;
} else
postAdd(parent, resource);
}
// open/close state change of a project
if ((flags & IResourceDelta.OPEN) != 0) {
postProjectStateChanged(internalGetParent(parent));
return true;
}
processResourceDeltas(delta.getAffectedChildren(), resource);
return false;
}
void setIsFlatLayout(boolean state) {
fIsFlatLayout= state;
}
/**
* Process resource deltas.
*
* @return true if the parent got refreshed
*/
private boolean processResourceDeltas(IResourceDelta[] deltas, Object parent) {
if (deltas == null)
return false;
if (deltas.length > 1) {
// more than one child changed, refresh from here downwards
postRefresh(parent);
return true;
}
for (int i= 0; i < deltas.length; i++) {
if (processResourceDelta(deltas[i], parent))
return true;
}
return false;
}
private void postRefresh(Object root) {
// JFace doesn't refresh when object isn't part of the viewer
// Therefore move the refresh start down to the viewer's input
if (isParent(root, fInput))
root= fInput;
postRefresh(root, true);
}
boolean isParent(Object root, Object child) {
Object parent= getParent(child);
if (parent == null)
return false;
if (parent.equals(root))
return true;
return isParent(root, parent);
}
private void postRefresh(final Object root, final boolean updateLabels) {
postRunnable(new Runnable() {
public void run() {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()){
fViewer.refresh(root, updateLabels);
}
}
});
}
private void postAdd(final Object parent, final Object element) {
postRunnable(new Runnable() {
public void run() {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()){
// TODO workaround for 39754 New projects being added to the TreeViewer twice
if (fViewer.testFindItem(element) == null)
fViewer.add(parent, element);
}
}
});
}
private void postRemove(final Object element) {
postRunnable(new Runnable() {
public void run() {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
fViewer.remove(element);
}
}
});
}
private void postProjectStateChanged(final Object root) {
postRunnable(new Runnable() {
public void run() {
fPart.projectStateChanged(root);
}
});
}
private void postRunnable(final Runnable r) {
Control ctrl= fViewer.getControl();
final Runnable trackedRunnable= new Runnable() {
public void run() {
try {
r.run();
} finally {
removePendingChange();
}
}
};
if (ctrl != null && !ctrl.isDisposed()) {
addPendingChange();
try {
ctrl.getDisplay().asyncExec(trackedRunnable);
} catch (RuntimeException e) {
removePendingChange();
throw e;
} catch (Error e) {
removePendingChange();
throw e;
}
}
}
// ------ Pending change management due to the use of asyncExec in postRunnable.
public synchronized boolean hasPendingChanges() {
return fPendingChanges > 0;
}
private synchronized void addPendingChange() {
fPendingChanges++;
// System.out.print(fPendingChanges);
}
private synchronized void removePendingChange() {
fPendingChanges--;
if (fPendingChanges < 0)
fPendingChanges= 0;
// System.out.print(fPendingChanges);
}
}
|
46,929 |
Bug 46929 refactoring: anonymous subclass of local type can be made nested [refactoring]
|
I20031119 (M5 testpass) 1. Have this code: public class Test { public void foobar() { class Listener2 { public int bar() { return 0; } } this.addListener(new Listener2() { public int bar() { return 1; } }); } public void addListener(Object o) { } } 2. Select the anonymous class extending the local type 3. Choose Refactor->Convert Anonymous Class to Nested -> The refactoring is possible and does the semi-expected, creating a new nested type -> This is wrong, because the Listener type is not visible outside the method
|
resolved fixed
|
3ec0f18
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-13T20:32:57Z | 2003-11-19T11:06:40Z |
org.eclipse.jdt.ui/core
| |
46,929 |
Bug 46929 refactoring: anonymous subclass of local type can be made nested [refactoring]
|
I20031119 (M5 testpass) 1. Have this code: public class Test { public void foobar() { class Listener2 { public int bar() { return 0; } } this.addListener(new Listener2() { public int bar() { return 1; } }); } public void addListener(Object o) { } } 2. Select the anonymous class extending the local type 3. Choose Refactor->Convert Anonymous Class to Nested -> The refactoring is possible and does the semi-expected, creating a new nested type -> This is wrong, because the Listener type is not visible outside the method
|
resolved fixed
|
3ec0f18
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-13T20:32:57Z | 2003-11-19T11:06:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/ConvertAnonymousToNestedRefactoring.java
| |
49,945 |
Bug 49945 Typing a brace destroys subsequent character
|
I20040106 + plugin-export 20040108_1804 Typing a brace destroys the subsequent '/' character: public class Example { public Example() { } // <- insert '{' before comment public static void main(String[] args) { } } All Preferences 'Java > Editor > Typing' have the default setting.
|
verified fixed
|
70f988b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-14T06:30:56Z | 2004-01-13T21:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/JavaAutoIndentStrategy.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Nikolay Metchev - Fixed bug 29909
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text.java;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DefaultAutoIndentStrategy;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.DocumentCommand;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.TextUtilities;
import org.eclipse.jface.text.rules.DefaultPartitioner;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.texteditor.ITextEditorExtension3;
import org.eclipse.jdt.core.ToolFactory;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.core.compiler.IScanner;
import org.eclipse.jdt.core.compiler.ITerminalSymbols;
import org.eclipse.jdt.core.compiler.InvalidInputException;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.DoStatement;
import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.ForStatement;
import org.eclipse.jdt.core.dom.IfStatement;
import org.eclipse.jdt.core.dom.Statement;
import org.eclipse.jdt.core.dom.WhileStatement;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.corext.Assert;
import org.eclipse.jdt.internal.corext.dom.NodeFinder;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.FastJavaPartitionScanner;
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.Symbols;
/**
* Auto indent strategy sensitive to brackets.
*/
public class JavaAutoIndentStrategy extends DefaultAutoIndentStrategy {
/** The line comment introducer. Value is "{@value}" */
private static final String LINE_COMMENT= "//"; //$NON-NLS-1$
private static class CompilationUnitInfo {
char[] buffer;
int delta;
CompilationUnitInfo(char[] buffer, int delta) {
this.buffer= buffer;
this.delta= delta;
}
}
private boolean fCloseBrace;
private boolean fIsSmartMode;
private String fPartitioning;
/**
* Creates a new Java auto indent strategy for the given document partitioning.
*
* @param partitioning the document partitioning
*/
public JavaAutoIndentStrategy(String partitioning) {
fPartitioning= partitioning;
}
private int getBracketCount(IDocument d, int startOffset, int endOffset, boolean ignoreCloseBrackets) throws BadLocationException {
int bracketCount= 0;
while (startOffset < endOffset) {
char curr= d.getChar(startOffset);
startOffset++;
switch (curr) {
case '/' :
if (startOffset < endOffset) {
char next= d.getChar(startOffset);
if (next == '*') {
// a comment starts, advance to the comment end
startOffset= getCommentEnd(d, startOffset + 1, endOffset);
} else if (next == '/') {
// '//'-comment: nothing to do anymore on this line
startOffset= endOffset;
}
}
break;
case '*' :
if (startOffset < endOffset) {
char next= d.getChar(startOffset);
if (next == '/') {
// we have been in a comment: forget what we read before
bracketCount= 0;
startOffset++;
}
}
break;
case '{' :
bracketCount++;
ignoreCloseBrackets= false;
break;
case '}' :
if (!ignoreCloseBrackets) {
bracketCount--;
}
break;
case '"' :
case '\'' :
startOffset= getStringEnd(d, startOffset, endOffset, curr);
break;
default :
}
}
return bracketCount;
}
// ----------- bracket counting ------------------------------------------------------
private int getCommentEnd(IDocument d, int offset, int endOffset) throws BadLocationException {
while (offset < endOffset) {
char curr= d.getChar(offset);
offset++;
if (curr == '*') {
if (offset < endOffset && d.getChar(offset) == '/') {
return offset + 1;
}
}
}
return endOffset;
}
private String getIndentOfLine(IDocument d, int line) throws BadLocationException {
if (line > -1) {
int start= d.getLineOffset(line);
int end= start + d.getLineLength(line) - 1;
int whiteEnd= findEndOfWhiteSpace(d, start, end);
return d.get(start, whiteEnd - start);
} else {
return ""; //$NON-NLS-1$
}
}
private int getStringEnd(IDocument d, int offset, int endOffset, char ch) throws BadLocationException {
while (offset < endOffset) {
char curr= d.getChar(offset);
offset++;
if (curr == '\\') {
// ignore escaped characters
offset++;
} else if (curr == ch) {
return offset;
}
}
return endOffset;
}
private void smartIndentAfterClosingBracket(IDocument d, DocumentCommand c) {
if (c.offset == -1 || d.getLength() == 0)
return;
try {
int p= (c.offset == d.getLength() ? c.offset - 1 : c.offset);
int line= d.getLineOfOffset(p);
int start= d.getLineOffset(line);
int whiteend= findEndOfWhiteSpace(d, start, c.offset);
JavaHeuristicScanner scanner= new JavaHeuristicScanner(d);
JavaIndenter indenter= new JavaIndenter(d, scanner);
// shift only when line does not contain any text up to the closing bracket
if (whiteend == c.offset) {
// evaluate the line with the opening bracket that matches out closing bracket
int reference= indenter.findReferencePosition(c.offset, false, true, false, false);
int indLine= d.getLineOfOffset(reference);
if (indLine != -1 && indLine != line) {
// take the indent of the found line
StringBuffer replaceText= new StringBuffer(getIndentOfLine(d, indLine));
// add the rest of the current line including the just added close bracket
replaceText.append(d.get(whiteend, c.offset - whiteend));
replaceText.append(c.text);
// modify document command
c.length += c.offset - start;
c.offset= start;
c.text= replaceText.toString();
}
}
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
}
private void smartIndentAfterOpeningBracket(IDocument d, DocumentCommand c) {
if (c.offset < 1 || d.getLength() == 0)
return;
JavaHeuristicScanner scanner= new JavaHeuristicScanner(d);
int p= (c.offset == d.getLength() ? c.offset - 1 : c.offset);
try {
// current line
int line= d.getLineOfOffset(p);
int lineOffset= d.getLineOffset(line);
// line of last javacode
int pos= scanner.findNonWhitespaceBackward(p, JavaHeuristicScanner.UNBOUND);
if (pos == -1)
return;
int lastLine= d.getLineOfOffset(pos);
// only shift if the last java line is further up and is a braceless block candidate
if (lastLine < line) {
JavaIndenter indenter= new JavaIndenter(d, scanner);
StringBuffer indent= indenter.computeIndentation(p, true);
if (indent != null) {
c.text= indent.append(c.text).toString();
c.length= indent.length();
c.offset= lineOffset;
}
}
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
}
private void smartIndentAfterNewLine(IDocument d, DocumentCommand c) {
JavaHeuristicScanner scanner= new JavaHeuristicScanner(d);
JavaIndenter indenter= new JavaIndenter(d, scanner);
StringBuffer indent= indenter.computeIndentation(c.offset);
if (indent == null)
indent= new StringBuffer(); //$NON-NLS-1$
int docLength= d.getLength();
if (c.offset == -1 || docLength == 0)
return;
try {
int p= (c.offset == docLength ? c.offset - 1 : c.offset);
int line= d.getLineOfOffset(p);
StringBuffer buf= new StringBuffer(c.text + indent);
IRegion reg= d.getLineInformation(line);
int lineEnd= reg.getOffset() + reg.getLength();
int contentStart= findEndOfWhiteSpace(d, c.offset, lineEnd);
c.length= Math.max(contentStart - c.offset, 0);
int start= reg.getOffset();
ITypedRegion region= TextUtilities.getPartition(d, fPartitioning, start);
if (IJavaPartitions.JAVA_DOC.equals(region.getType()))
start= d.getLineInformationOfOffset(region.getOffset()).getOffset();
if (getBracketCount(d, start, c.offset, true) > 0 && closeBrace() && !isClosed(d, c.offset, c.length)) {
c.caretOffset= c.offset + buf.length();
c.shiftsCaret= false;
// copy old content of line behind insertion point to new line
// unless we think we are inserting an anonymous type definition
if (c.offset == 0 || !(computeAnonymousPosition(d, c.offset - 1, fPartitioning, lineEnd) != -1)) {
if (lineEnd - contentStart > 0) {
c.length= lineEnd - c.offset;
buf.append(d.get(contentStart, lineEnd - contentStart).toCharArray());
}
}
buf.append(getLineDelimiter(d));
StringBuffer reference= indenter.getReferenceIndentation(c.offset);
if (reference != null)
buf.append(reference);
buf.append('}');
}
c.text= buf.toString();
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
}
/**
* Computes an insert position for an opening brace if <code>offset</code> maps to a position in
* <code>document</code> with a expression in parenthesis that will take a block after the closing parenthesis.
*
* @param document the document being modified
* @param offset the offset of the caret position, relative to the line start.
* @param partitioning the document partitioning
* @param max the max position
* @return an insert position relative to the line start if <code>line</code> contains a parenthesized expression that can be followed by a block, -1 otherwise
*/
private static int computeAnonymousPosition(IDocument document, int offset, String partitioning, int max) {
// find the opening parenthesis for every closing parenthesis on the current line after offset
// return the position behind the closing parenthesis if it looks like a method declaration
// or an expression for an if, while, for, catch statement
JavaHeuristicScanner scanner= new JavaHeuristicScanner(document);
int pos= offset;
int length= max;
int scanTo= scanner.scanForward(pos, length, '}');
if (scanTo == -1)
scanTo= length;
int closingParen= findClosingParenToLeft(scanner, pos) - 1;
while (true) {
int startScan= closingParen + 1;
closingParen= scanner.scanForward(startScan, scanTo, ')');
if (closingParen == -1)
break;
int openingParen= scanner.findOpeningPeer(closingParen - 1, '(', ')');
// no way an expression at the beginning of the document can mean anything
if (openingParen < 1)
break;
// only select insert positions for parenthesis currently embracing the caret
if (openingParen > pos)
continue;
if (looksLikeAnonymousClassDef(document, partitioning, scanner, openingParen - 1))
return closingParen + 1;
}
return -1;
}
/**
* Finds a closing parenthesis to the left of <code>position</code> in document, where that parenthesis is only
* separated by whitespace from <code>position</code>. If no such parenthesis can be found, <code>position</code> is returned.
*
* @param document the document being modified
* @param position the first character position in <code>document</code> to be considered
* @param partitioning the document partitioning
* @return the position of a closing parenthesis left to <code>position</code> separated only by whitespace, or <code>position</code> if no parenthesis can be found
*/
private static int findClosingParenToLeft(JavaHeuristicScanner scanner, int position) {
if (position < 1)
return position;
if (scanner.previousToken(position - 1, JavaHeuristicScanner.UNBOUND) == Symbols.TokenRPAREN)
return scanner.getPosition() + 1;
return position;
}
/**
* Checks whether the content of <code>document</code> in the range (<code>offset</code>, <code>length</code>)
* contains the <code>new</code> keyword.
*
* @param document the document being modified
* @param offset the first character position in <code>document</code> to be considered
* @param length the length of the character range to be considered
* @param partitioning the document partitioning
* @return <code>true</code> if the specified character range contains a <code>new</code> keyword, <code>false</code> otherwise.
*/
private static boolean isNewMatch(IDocument document, int offset, int length, String partitioning) {
Assert.isTrue(length >= 0);
Assert.isTrue(offset >= 0);
Assert.isTrue(offset + length < document.getLength() + 1);
try {
String text= document.get(offset, length);
int pos= text.indexOf("new"); //$NON-NLS-1$
while (pos != -1 && !isDefaultPartition(document, pos + offset, partitioning))
pos= text.indexOf("new", pos + 2); //$NON-NLS-1$
if (pos < 0)
return false;
if (pos != 0 && Character.isJavaIdentifierPart(text.charAt(pos - 1)))
return false;
if (pos + 3 < length && Character.isJavaIdentifierPart(text.charAt(pos + 3)))
return false;
return true;
} catch (BadLocationException e) {
}
return false;
}
/**
* Checks whether the content of <code>document</code> at <code>position</code> looks like an
* anonymous class definition. <code>position</code> must be to the left of the opening
* parenthesis of the definition's parameter list.
*
* @param document the document being modified
* @param position the first character position in <code>document</code> to be considered
* @param partitioning the document partitioning
* @return <code>true</code> if the content of <code>document</code> looks like an anonymous class definition, <code>false</code> otherwise
*/
private static boolean looksLikeAnonymousClassDef(IDocument document, String partitioning, JavaHeuristicScanner scanner, int position) {
int previousCommaOrParen= scanner.scanBackward(position - 1, JavaHeuristicScanner.UNBOUND, new char[] {',', '('});
if (previousCommaOrParen == -1 || position < previousCommaOrParen + 5) // 2 for borders, 3 for "new"
return false;
if (isNewMatch(document, previousCommaOrParen + 1, position - previousCommaOrParen - 2, partitioning))
return true;
return false;
}
/**
* Checks whether <code>position</code> resides in a default (Java) partition of <code>document</code>.
*
* @param document the document being modified
* @param position the position to be checked
* @param partitioning the document partitioning
* @return <code>true</code> if <code>position</code> is in the default partition of <code>document</code>, <code>false</code> otherwise
*/
private static boolean isDefaultPartition(IDocument document, int position, String partitioning) {
Assert.isTrue(position >= 0);
Assert.isTrue(position <= document.getLength());
try {
ITypedRegion region= TextUtilities.getPartition(document, partitioning, position);
return region.getType().equals(IDocument.DEFAULT_CONTENT_TYPE);
} catch (BadLocationException e) {
}
return false;
}
private boolean isClosed(IDocument document, int offset, int length) {
CompilationUnitInfo info= getCompilationUnitForMethod(document, offset, fPartitioning);
if (info == null)
return false;
CompilationUnit compilationUnit= null;
try {
compilationUnit= AST.parseCompilationUnit(info.buffer);
} catch (ArrayIndexOutOfBoundsException x) {
// work around for parser problem
return false;
}
IProblem[] problems= compilationUnit.getProblems();
for (int i= 0; i != problems.length; ++i) {
if (problems[i].getID() == IProblem.UnmatchedBracket)
return true;
}
final int relativeOffset= offset - info.delta;
ASTNode node= NodeFinder.perform(compilationUnit, relativeOffset, length);
if (node == null)
return false;
if (length == 0) {
while (node != null && (relativeOffset == node.getStartPosition() || relativeOffset == node.getStartPosition() + node.getLength()))
node= node.getParent();
}
switch (node.getNodeType()) {
case ASTNode.BLOCK:
return areBlocksConsistent(document, offset, fPartitioning);
case ASTNode.IF_STATEMENT:
{
IfStatement ifStatement= (IfStatement) node;
Expression expression= ifStatement.getExpression();
IRegion expressionRegion= createRegion(expression, info.delta);
Statement thenStatement= ifStatement.getThenStatement();
IRegion thenRegion= createRegion(thenStatement, info.delta);
// between expression and then statement
if (expressionRegion.getOffset() + expressionRegion.getLength() <= offset && offset + length <= thenRegion.getOffset())
return thenStatement != null;
Statement elseStatement= ifStatement.getElseStatement();
IRegion elseRegion= createRegion(elseStatement, info.delta);
IRegion elseToken= null;
if (elseStatement != null) {
int sourceOffset= thenRegion.getOffset() + thenRegion.getLength();
int sourceLength= elseRegion.getOffset() - sourceOffset;
elseToken= getToken(document, new Region(sourceOffset, sourceLength), ITerminalSymbols.TokenNameelse);
}
// between 'else' keyword and else statement
if (elseToken.getOffset() + elseToken.getLength() <= offset && offset + length < elseRegion.getOffset())
return elseStatement != null;
}
break;
case ASTNode.WHILE_STATEMENT:
case ASTNode.FOR_STATEMENT:
{
Expression expression= node.getNodeType() == ASTNode.WHILE_STATEMENT ? ((WhileStatement) node).getExpression() : ((ForStatement) node).getExpression();
IRegion expressionRegion= createRegion(expression, info.delta);
Statement body= node.getNodeType() == ASTNode.WHILE_STATEMENT ? ((WhileStatement) node).getBody() : ((ForStatement) node).getBody();
IRegion bodyRegion= createRegion(body, info.delta);
// between expression and body statement
if (expressionRegion.getOffset() + expressionRegion.getLength() <= offset && offset + length <= bodyRegion.getOffset())
return body != null;
}
break;
case ASTNode.DO_STATEMENT:
{
DoStatement doStatement= (DoStatement) node;
IRegion doRegion= createRegion(doStatement, info.delta);
Statement body= doStatement.getBody();
IRegion bodyRegion= createRegion(body, info.delta);
if (doRegion.getOffset() + doRegion.getLength() <= offset && offset + length <= bodyRegion.getOffset())
return body != null;
}
break;
}
return true;
}
private static String getLineDelimiter(IDocument document) {
try {
if (document.getNumberOfLines() > 1)
return document.getLineDelimiter(0);
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
return System.getProperty("line.separator"); //$NON-NLS-1$
}
/**
* Installs a java partitioner with <code>document</code>.
*
* @param document the document
*/
private static void installJavaStuff(Document document) {
String[] types= new String[] {
IJavaPartitions.JAVA_DOC,
IJavaPartitions.JAVA_MULTI_LINE_COMMENT,
IJavaPartitions.JAVA_SINGLE_LINE_COMMENT,
IJavaPartitions.JAVA_STRING,
IJavaPartitions.JAVA_CHARACTER,
IDocument.DEFAULT_CONTENT_TYPE
};
DefaultPartitioner partitioner= new DefaultPartitioner(new FastJavaPartitionScanner(), types);
partitioner.connect(document);
document.setDocumentPartitioner(IJavaPartitions.JAVA_PARTITIONING, partitioner);
}
private static void smartPaste(IDocument document, DocumentCommand command) {
try {
JavaHeuristicScanner scanner= new JavaHeuristicScanner(document);
JavaIndenter indenter= new JavaIndenter(document, scanner);
int offset= command.offset;
// reference position to get the indent from
int refOffset= indenter.findReferencePosition(offset);
if (refOffset == JavaHeuristicScanner.NOT_FOUND)
return;
int peerOffset= getPeerPosition(document, command);
peerOffset= indenter.findReferencePosition(peerOffset);
refOffset= Math.min(refOffset, peerOffset);
// eat any WS before the insertion to the beginning of the line
IRegion line= document.getLineInformationOfOffset(offset);
String notSelected= document.get(line.getOffset(), offset - line.getOffset());
if (notSelected.trim().length() == 0) {
command.length += notSelected.length();
command.offset= line.getOffset();
}
// prefix: the part we need for formatting but won't paste
IRegion refLine= document.getLineInformationOfOffset(refOffset);
String prefix= document.get(refLine.getOffset(), command.offset - refLine.getOffset());
// handle the indentation computation inside a temporary document
Document temp= new Document(prefix + command.text);
scanner= new JavaHeuristicScanner(temp);
indenter= new JavaIndenter(temp, scanner);
installJavaStuff(temp);
// indent the first and second line
// compute the relative indentation difference from the second line
// (as the first might be partially selected) and use the value to
// indent all other lines.
boolean isIndentDetected= false;
StringBuffer addition= new StringBuffer();
int insertLength= 0;
int first= document.computeNumberOfLines(prefix);
int lines= temp.getNumberOfLines();
for (int l= first; l < lines; l++) { // we don't change the number of lines while adding indents
IRegion r= temp.getLineInformation(l);
int lineOffset= r.getOffset();
int lineLength= r.getLength();
if (lineLength == 0) // don't modify empty lines
continue;
if (!isIndentDetected){
// indent the first pasted line
String current= getCurrentIndent(temp, l);
StringBuffer correct= indenter.computeIndentation(lineOffset);
if (correct == null)
return; // bail out
insertLength= subtractIndent(correct, current, addition);
if (l != first)
isIndentDetected= true;
}
// relatively indent all pasted lines
if (insertLength > 0)
addIndent(temp, l, addition);
else if (insertLength < 0)
cutIndent(temp, l, -insertLength);
}
// modify the command
command.text= temp.get(prefix.length(), temp.getLength() - prefix.length());
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
}
/**
* Returns the indentation of the line <code>line</code> in <code>document</code>.
* The returned string may contain pairs of leading slashes that are considered
* part of the indentation. The space before the asterix in a javadoc-like
* comment is not considered part of the indentation.
*
* @param document the document
* @param line the line
* @return the indentation of <code>line</code> in <code>document</code>
* @throws BadLocationException if the document is changed concurrently
*/
private static String getCurrentIndent(Document document, int line) throws BadLocationException {
IRegion region= document.getLineInformation(line);
int from= region.getOffset();
int endOffset= region.getOffset() + region.getLength();
// go behind line comments
int to= from;
while (to < endOffset - 2 && document.get(to, 2).equals(LINE_COMMENT))
to += 2;
while (to < endOffset) {
char ch= document.getChar(to);
if (!Character.isWhitespace(ch))
break;
to++;
}
// don't count the space before javadoc like, asterix-style comment lines
if (to > from && to < endOffset - 1 && document.get(to - 1, 2).equals(" *")) { //$NON-NLS-1$
String type= TextUtilities.getContentType(document, IJavaPartitions.JAVA_PARTITIONING, to);
if (type.equals(IJavaPartitions.JAVA_DOC) || type.equals(IJavaPartitions.JAVA_MULTI_LINE_COMMENT))
to--;
}
return document.get(from, to - from);
}
/**
* Computes the difference of two indentations and returns the difference in
* length of current and correct. If the return value is positive, <code>addition</code>
* is initialized with a substring of that length of <code>correct</code>.
*
* @param correct the correct indentation
* @param current the current indentation (migth contain non-whitespace)
* @param difference a string buffer - if the return value is positive, it will be cleared and set to the substring of <code>current</code> of that length
* @return the difference in lenght of <code>correct</code> and <code>current</code>
*/
private static int subtractIndent(CharSequence correct, CharSequence current, StringBuffer difference) {
int c1= computeVisualLength(correct);
int c2= computeVisualLength(current);
int diff= c1 - c2;
if (diff <= 0)
return diff;
difference.setLength(0);
int len= 0, i= 0;
while (len < diff) {
char c= correct.charAt(i++);
difference.append(c);
len += computeVisualLength(c);
}
return diff;
}
/**
* Indents line <code>line</code> in <code>document</code> with <code>indent</code>.
* Leaves leading comment signs alone.
*
* @param document the document
* @param line the line
* @param indent the indentation to insert
* @throws BadLocationException on concurrent document modification
*/
private static void addIndent(Document document, int line, CharSequence indent) throws BadLocationException {
IRegion region= document.getLineInformation(line);
int insert= region.getOffset();
int endOffset= region.getOffset() + region.getLength();
// go behind line comments
while (insert < endOffset - 2 && document.get(insert, 2).equals(LINE_COMMENT))
insert += 2;
// insert indent
document.replace(insert, 0, indent.toString());
}
/**
* Cuts the visual equivalent of <code>toDelete</code> characters out of the
* indentation of line <code>line</code> in <code>document</code>. Leaves
* leading comment signs alone.
*
* @param document the document
* @param line the line
* @param toDelete the number of space equivalents to delete.
* @throws BadLocationException on concurrent document modification
*/
private static void cutIndent(Document document, int line, int toDelete) throws BadLocationException {
IRegion region= document.getLineInformation(line);
int from= region.getOffset();
int endOffset= region.getOffset() + region.getLength();
// go behind line comments
while (from < endOffset - 2 && document.get(from, 2).equals(LINE_COMMENT))
from += 2;
int to= from;
while (toDelete > 0 && to < endOffset) {
char ch= document.getChar(to);
if (!Character.isWhitespace(ch))
break;
toDelete -= computeVisualLength(ch);
to++;
}
document.replace(from, to - from, null);
}
/**
* Returns the visual length of a given <code>CharSequence</code> taking into
* account the visual tabulator length.
*
* @param seq the string to measure
* @return the visual length of <code>seq</code>
*/
private static int computeVisualLength(CharSequence seq) {
int size= 0;
int tablen= getVisualTabLengthPreference();
for (int i= 0; i < seq.length(); i++) {
char ch= seq.charAt(i);
if (ch == '\t')
size += tablen - size % tablen;
else
size++;
}
return size;
}
/**
* Returns the visual length of a given character taking into
* account the visual tabulator length.
*
* @param ch the character to measure
* @return the visual length of <code>ch</code>
*/
private static int computeVisualLength(char ch) {
if (ch == '\t')
return getVisualTabLengthPreference();
else
return 1;
}
/**
* The preference setting for the visual tabulator display.
*
* @return the number of spaces displayed for a tabulator in the editor
*/
private static int getVisualTabLengthPreference() {
return JavaPlugin.getDefault().getPreferenceStore().getInt(PreferenceConstants.EDITOR_TAB_WIDTH);
}
private static int getPeerPosition(IDocument document, DocumentCommand command) {
/*
* Search for scope closers in the pasted text and find their opening peers
* in the document.
*/
Document pasted= new Document(command.text);
installJavaStuff(pasted);
int firstPeer= command.offset;
JavaHeuristicScanner pScanner= new JavaHeuristicScanner(pasted);
JavaHeuristicScanner dScanner= new JavaHeuristicScanner(document);
// add scope relevant after context to peer search
int afterToken= dScanner.nextToken(command.offset + command.length, JavaHeuristicScanner.UNBOUND);
try {
switch (afterToken) {
case Symbols.TokenRBRACE:
pasted.replace(pasted.getLength(), 0, "}"); //$NON-NLS-1$
break;
case Symbols.TokenRPAREN:
pasted.replace(pasted.getLength(), 0, ")"); //$NON-NLS-1$
break;
case Symbols.TokenRBRACKET:
pasted.replace(pasted.getLength(), 0, "]"); //$NON-NLS-1$
break;
}
} catch (BadLocationException e) {
// cannot happen
Assert.isTrue(false);
}
int pPos= 0; // paste text position (increasing from 0)
int dPos= Math.max(0, command.offset - 1); // document position (decreasing from paste offset)
while (true) {
int token= pScanner.nextToken(pPos, JavaHeuristicScanner.UNBOUND);
pPos= pScanner.getPosition();
switch (token) {
case Symbols.TokenLBRACE:
case Symbols.TokenLBRACKET:
case Symbols.TokenLPAREN:
pPos= skipScope(pScanner, pPos, token);
if (pPos == JavaHeuristicScanner.NOT_FOUND)
return firstPeer;
break; // closed scope -> keep searching
case Symbols.TokenRBRACE:
int peer= dScanner.findOpeningPeer(dPos, '{', '}');
dPos= peer - 1;
if (peer == JavaHeuristicScanner.NOT_FOUND)
return firstPeer;
firstPeer= peer;
break; // keep searching
case Symbols.TokenRBRACKET:
peer= dScanner.findOpeningPeer(dPos, '[', ']');
dPos= peer - 1;
if (peer == JavaHeuristicScanner.NOT_FOUND)
return firstPeer;
firstPeer= peer;
break; // keep searching
case Symbols.TokenRPAREN:
peer= dScanner.findOpeningPeer(dPos, '(', ')');
dPos= peer - 1;
if (peer == JavaHeuristicScanner.NOT_FOUND)
return firstPeer;
firstPeer= peer;
break; // keep searching
case Symbols.TokenCASE:
case Symbols.TokenDEFAULT:
JavaIndenter indenter= new JavaIndenter(document, dScanner);
peer= indenter.findReferencePosition(dPos, false, false, false, true);
if (peer == JavaHeuristicScanner.NOT_FOUND)
return firstPeer;
firstPeer= peer;
break; // keep searching
case Symbols.TokenEOF:
return firstPeer;
default:
// keep searching
}
}
}
/**
* Skips the scope opened by <code>token</code> in <code>document</code>,
* returns either the position of the
* @param pos
* @param token
* @return
*/
private static int skipScope(JavaHeuristicScanner scanner, int pos, int token) {
int openToken= token;
int closeToken;
switch (token) {
case Symbols.TokenLPAREN:
closeToken= Symbols.TokenRPAREN;
break;
case Symbols.TokenLBRACKET:
closeToken= Symbols.TokenRBRACKET;
break;
case Symbols.TokenLBRACE:
closeToken= Symbols.TokenRBRACE;
break;
default:
Assert.isTrue(false);
return -1; // dummy
}
int depth= 1;
int p= pos;
while (true) {
int tok= scanner.nextToken(p, JavaHeuristicScanner.UNBOUND);
p= scanner.getPosition();
if (tok == openToken) {
depth++;
} else if (tok == closeToken) {
depth--;
if (depth == 0)
return p + 1;
} else if (tok == Symbols.TokenEOF) {
return JavaHeuristicScanner.NOT_FOUND;
}
}
}
private boolean isLineDelimiter(IDocument document, String text) {
String[] delimiters= document.getLegalLineDelimiters();
if (delimiters != null)
return TextUtilities.equals(delimiters, text) > -1;
return false;
}
private void smartIndentAfterBlockDelimiter(IDocument document, DocumentCommand command) {
if (command.text.charAt(0) == '}')
smartIndentAfterClosingBracket(document, command);
else if (command.text.charAt(0) == '{')
smartIndentAfterOpeningBracket(document, command);
}
/*
* @see org.eclipse.jface.text.IAutoIndentStrategy#customizeDocumentCommand(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.DocumentCommand)
*/
public void customizeDocumentCommand(IDocument d, DocumentCommand c) {
clearCachedValues();
if (!isSmartMode() || c.doit == false)
return;
if (c.length == 0 && c.text != null && isLineDelimiter(d, c.text))
smartIndentAfterNewLine(d, c);
else if (c.text.length() == 1)
smartIndentAfterBlockDelimiter(d, c);
else if (c.text.length() > 1 && getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SMART_PASTE))
smartPaste(d, c);
}
private static IPreferenceStore getPreferenceStore() {
return JavaPlugin.getDefault().getPreferenceStore();
}
private boolean closeBrace() {
return fCloseBrace;
}
private boolean isSmartMode() {
return fIsSmartMode;
}
private void clearCachedValues() {
IPreferenceStore preferenceStore= getPreferenceStore();
fCloseBrace= preferenceStore.getBoolean(PreferenceConstants.EDITOR_CLOSE_BRACES);
fIsSmartMode= computeSmartMode();
}
private boolean computeSmartMode() {
IWorkbenchPage page= JavaPlugin.getActivePage();
if (page != null) {
IEditorPart part= page.getActiveEditor();
if (part instanceof ITextEditorExtension3) {
ITextEditorExtension3 extension= (ITextEditorExtension3) part;
return extension.getInsertMode() == ITextEditorExtension3.SMART_INSERT;
}
}
return false;
}
private static CompilationUnitInfo getCompilationUnitForMethod(IDocument document, int offset, String partitioning) {
try {
JavaHeuristicScanner scanner= new JavaHeuristicScanner(document);
IRegion sourceRange= scanner.findSurroundingBlock(offset);
if (sourceRange == null)
return null;
String source= document.get(sourceRange.getOffset(), sourceRange.getLength());
StringBuffer contents= new StringBuffer();
contents.append("class ____C{void ____m()"); //$NON-NLS-1$
final int methodOffset= contents.length();
contents.append(source);
contents.append('}');
char[] buffer= contents.toString().toCharArray();
return new CompilationUnitInfo(buffer, sourceRange.getOffset() - methodOffset);
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
return null;
}
private static boolean areBlocksConsistent(IDocument document, int offset, String partitioning) {
if (offset < 1 || offset >= document.getLength())
return false;
int begin= offset;
int end= offset - 1;
JavaHeuristicScanner scanner= new JavaHeuristicScanner(document);
while (true) {
begin= scanner.findOpeningPeer(begin - 1, '{', '}');
end= scanner.findClosingPeer(end + 1, '{', '}');
if (begin == -1 && end == -1)
return true;
if (begin == -1 || end == -1)
return false;
}
}
private static IRegion createRegion(ASTNode node, int delta) {
return node == null ? null : new Region(node.getStartPosition() + delta, node.getLength());
}
private static IRegion getToken(IDocument document, IRegion scanRegion, int tokenId) {
try {
final String source= document.get(scanRegion.getOffset(), scanRegion.getLength());
IScanner scanner= ToolFactory.createScanner(false, false, false, false);
scanner.setSource(source.toCharArray());
int id= scanner.getNextToken();
while (id != ITerminalSymbols.TokenNameEOF && id != tokenId)
id= scanner.getNextToken();
if (id == ITerminalSymbols.TokenNameEOF)
return null;
int tokenOffset= scanner.getCurrentTokenStartPosition();
int tokenLength= scanner.getCurrentTokenEndPosition() + 1 - tokenOffset; // inclusive end
return new Region(tokenOffset + scanRegion.getOffset(), tokenLength);
} catch (InvalidInputException x) {
return null;
} catch (BadLocationException x) {
return null;
}
}
}
|
44,035 |
Bug 44035 [formatting] Error in formatting parts of java code snippets in comment
|
This is for build I20030930. The Java code formatter options are set to Format java code snippets. Taking the following comment: /** * The following is a Java snipet. * * <pre> * while ((size = availableSize(stream, size)) > 0) { * System.out.println("available"); * } * </pre> */ public void test() { } And trying to format it here is what we got: /** * The following is a Java snipet. * * <pre> * while ((size = availableSize(stream, size)) > 0) { * System.out.println("available"); } * </pre> */ public void test() { }
|
resolved fixed
|
8cecdcd
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-14T07:55:00Z | 2003-10-01T20:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/comment/CommentFormattingStrategy.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.LinkedList;
import java.util.Map;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.Assert;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.TextUtilities;
import org.eclipse.jface.text.TypedPosition;
import org.eclipse.jface.text.formatter.ContentFormatter2;
import org.eclipse.jface.text.formatter.ContextBasedFormattingStrategy;
import org.eclipse.jface.text.formatter.FormattingContext;
import org.eclipse.jface.text.formatter.FormattingContextProperties;
import org.eclipse.jface.text.formatter.IFormattingContext;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.ui.text.IJavaPartitions;
/**
* Formatting strategy for general source code comments.
* <p>
* This strategy implements <code>IFormattingStrategyExtension</code>. It
* must be registered with a content formatter implementing <code>IContentFormatterExtension2<code>
* to take effect.
*
* @since 3.0
*/
public class CommentFormattingStrategy extends ContextBasedFormattingStrategy {
/**
* Returns the indentation of the line at the specified offset.
*
* @param document
* Document which owns the line
* @param region
* Comment region which owns the line
* @param offset
* Offset where to determine the indentation
* @return The indentation of the line
*/
public static String getLineIndentation(final IDocument document, final CommentRegion region, final int offset) {
String result= ""; //$NON-NLS-1$
try {
final IRegion line= document.getLineInformationOfOffset(offset);
final int begin= line.getOffset();
final int end= Math.min(offset, line.getOffset() + line.getLength());
boolean useTab= JavaCore.TAB.equals(JavaCore.getOption(JavaCore.FORMATTER_TAB_CHAR));
result= region.stringToIndent(document.get(begin, end - begin), useTab);
} catch (BadLocationException exception) {
// Ignore and return empty
}
return result;
}
/**
* Content formatter with which this formatting strategy has been
* registered
*/
private final ContentFormatter2 fFormatter;
/** Partitions to be formatted by this strategy */
private final LinkedList fPartitions= new LinkedList();
/**
* Creates a new comment formatting strategy.
*
* @param formatter
* The content formatter with which this formatting strategy has
* been registered
* @param viewer
* The source viewer where to apply the formatting strategy
*/
public CommentFormattingStrategy(final ContentFormatter2 formatter, final ISourceViewer viewer) {
super(viewer);
fFormatter= formatter;
}
/*
* @see org.eclipse.jface.text.formatter.ContextBasedFormattingStrategy#format()
*/
public void format() {
super.format();
Assert.isLegal(fPartitions.size() > 0);
final IDocument document= getViewer().getDocument();
final TypedPosition position= (TypedPosition)fPartitions.removeFirst();
try {
final ITypedRegion partition= TextUtilities.getPartition(document, fFormatter.getDocumentPartitioning(), position.getOffset());
final String type= partition.getType();
position.offset= partition.getOffset();
position.length= partition.getLength();
final Map preferences= getPreferences();
final boolean format= IPreferenceStore.TRUE.equals(preferences.get(PreferenceConstants.FORMATTER_COMMENT_FORMAT));
final boolean header= IPreferenceStore.TRUE.equals(preferences.get(PreferenceConstants.FORMATTER_COMMENT_FORMATHEADER));
if (format && (header || position.getOffset() != 0 || !type.equals(IJavaPartitions.JAVA_DOC) && !type.equals(IJavaPartitions.JAVA_MULTI_LINE_COMMENT))) {
final CommentRegion region= CommentObjectFactory.createRegion(this, position, TextUtilities.getDefaultLineDelimiter(document));
final String indentation= getLineIndentation(document, region, position.getOffset());
region.format(indentation);
}
} catch (BadLocationException exception) {
// Should not happen
}
}
/*
* @see org.eclipse.jface.text.formatter.ContextBasedFormattingStrategy#formatterStarts(org.eclipse.jface.text.formatter.IFormattingContext)
*/
public void formatterStarts(IFormattingContext context) {
super.formatterStarts(context);
final FormattingContext current= (FormattingContext)context;
fPartitions.addLast(current.getProperty(FormattingContextProperties.CONTEXT_PARTITION));
}
/*
* @see org.eclipse.jface.text.formatter.ContextBasedFormattingStrategy#formatterStops()
*/
public void formatterStops() {
super.formatterStops();
fPartitions.clear();
}
/**
* Returns the content formatter with which this formatting strategy has
* been registered.
*
* @return The content formatter
*/
public final ContentFormatter2 getFormatter() {
return fFormatter;
}
}
|
44,035 |
Bug 44035 [formatting] Error in formatting parts of java code snippets in comment
|
This is for build I20030930. The Java code formatter options are set to Format java code snippets. Taking the following comment: /** * The following is a Java snipet. * * <pre> * while ((size = availableSize(stream, size)) > 0) { * System.out.println("available"); * } * </pre> */ public void test() { } And trying to format it here is what we got: /** * The following is a Java snipet. * * <pre> * while ((size = availableSize(stream, size)) > 0) { * System.out.println("available"); } * </pre> */ public void test() { }
|
resolved fixed
|
8cecdcd
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-14T07:55:00Z | 2003-10-01T20:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/comment/CommentRange.java
|
/*****************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*****************************************************************************/
package org.eclipse.jdt.internal.ui.text.comment;
import org.eclipse.jface.text.Position;
/**
* Range in a comment region in comment region coordinates.
*
* @since 3.0
*/
public class CommentRange extends Position implements ICommentAttributes, IHtmlTagConstants {
/** The javadoc attributes of this range */
private int fAttributes= 0;
/**
* Creates a new comment range.
*
* @param position
* Offset of the range
* @param count
* Length of the range
*/
public CommentRange(final int position, final int count) {
super(position, count);
}
/**
* Is the attribute <code>attribute</code> true?
*
* @param attribute
* The attribute to get.
* @return <code>true</code> iff this attribute is <code>true</code>,
* <code>false</code> otherwise.
*/
protected final boolean hasAttribute(final int attribute) {
return (fAttributes & attribute) == attribute;
}
/**
* Is this javadoc range a closing html tag?
*
* @param token
* Token belonging to the javadoc range
* @param tag
* Html tag to find
* @return <code>true</code> iff this javadoc is a closing html tag,
* <code>false</code> otherwise
*/
protected final boolean isClosingTag(final String token, final String tag) {
boolean result= token.startsWith(HTML_CLOSE_PREFIX) && token.charAt(token.length() - 1) == HTML_TAG_POSTFIX;
if (result) {
setAttribute(COMMENT_CLOSE);
result= token.substring(HTML_CLOSE_PREFIX.length(), token.length() - 1).equals(tag);
}
return result;
}
/**
* Is this javadoc range an opening html tag?
*
* @param token
* Token belonging to the javadoc range
* @param tag
* Html tag to find
* @return <code>true</code> iff this javadoc is an opening html tag,
* <code>false</code> otherwise
*/
protected final boolean isOpeningTag(final String token, final String tag) {
boolean result= token.charAt(0) == HTML_TAG_PREFIX && !token.startsWith(HTML_CLOSE_PREFIX) && token.charAt(token.length() - 1) == HTML_TAG_POSTFIX;
if (result) {
setAttribute(COMMENT_OPEN);
result= token.startsWith(tag, 1);
}
return result;
}
/**
* Marks the comment range as having a certain html tag for line wrapping.
*
* @param tags
* Html tags which cause the wrapping of the comment range
* @param token
* Token belonging to the comment range
* @param attribute
* Attribute to set if the html tag is present
* @param open
* <code>true</code> iff opening tags should be marked, <code>false</code>
* otherwise.
* @param close
* <code>true</code> iff closing tags should be marked, <code>false</code>
* otherwise.
*/
protected final void markHtmlTag(final String[] tags, final String token, final int attribute, final boolean open, final boolean close) {
if (token.charAt(0) == HTML_TAG_PREFIX && token.charAt(token.length() - 1) == HTML_TAG_POSTFIX) {
String tag= null;
boolean isOpen= false;
boolean isClose= false;
for (int index= 0; index < tags.length; index++) {
tag= tags[index];
isOpen= isOpeningTag(token, tag);
isClose= isClosingTag(token, tag);
if ((open && isOpen) || (close && isClose)) {
setAttribute(attribute);
break;
}
}
}
}
/**
* Marks the comment range as having a certain tag for line wrapping
*
* @param tags
* Set of tags to mark for this comment range
* @param prefix
* The prefix common to all tags in the set
* @param token
* Token belonging to the comment range
* @param attribute
* Attribute to set if the html tag is present
*/
protected final void markPrefixTag(final String[] tags, final char prefix, final String token, final int attribute) {
if (token.charAt(0) == prefix) {
String tag= null;
for (int index= 0; index < tags.length; index++) {
tag= tags[index];
if (token.equals(tag)) {
setAttribute(attribute);
break;
}
}
}
}
/**
* Marks an attributed comment range with the indicated attribute.
*
* @param token
* Token belonging to the comment range
* @param tag
* The html tag which confines the attributed comment ranges
* @param level
* Hierarchical depth of layered attributed comment ranges
* @param key
* The key of the attribute to set when an attributed comment
* range has been recognized
* @param html
* <code>true</code> iff html tags in this attributed comment
* range should be attributed too, <code>false</code> otherwise
* @return The new hierarchical depth of the attributed comment ranges
*/
protected final int markRange(final String token, final String tag, int level, final int key, final boolean html) {
if (isOpeningTag(token, tag)) {
if (level++ > 0)
setAttribute(key);
} else if (isClosingTag(token, tag)) {
if (--level > 0)
setAttribute(key);
} else if (level > 0) {
if (html || !hasAttribute(COMMENT_HTML))
setAttribute(key);
}
return level;
}
/**
* Moves this comment range.
*
* @param delta
* The delta to move the range
*/
public final void move(final int delta) {
offset += delta;
}
/**
* Set the attribute <code>attribute</code> to true.
*
* @param attribute
* The attribute to set.
*/
protected final void setAttribute(final int attribute) {
fAttributes |= attribute;
}
/**
* Trims this comment range at the beginning.
*
* @param delta
* Amount to trim the range
*/
public final void trimBegin(final int delta) {
offset += delta;
length -= delta;
}
/**
* Trims this comment range at the end.
*
* @param delta
* Amount to trim the range
*/
public final void trimEnd(final int delta) {
length += delta;
}
}
|
44,035 |
Bug 44035 [formatting] Error in formatting parts of java code snippets in comment
|
This is for build I20030930. The Java code formatter options are set to Format java code snippets. Taking the following comment: /** * The following is a Java snipet. * * <pre> * while ((size = availableSize(stream, size)) > 0) { * System.out.println("available"); * } * </pre> */ public void test() { } And trying to format it here is what we got: /** * The following is a Java snipet. * * <pre> * while ((size = availableSize(stream, size)) > 0) { * System.out.println("available"); } * </pre> */ public void test() { }
|
resolved fixed
|
8cecdcd
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-14T07:55:00Z | 2003-10-01T20:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/comment/HTMLEntity2JavaReader.java
| |
44,035 |
Bug 44035 [formatting] Error in formatting parts of java code snippets in comment
|
This is for build I20030930. The Java code formatter options are set to Format java code snippets. Taking the following comment: /** * The following is a Java snipet. * * <pre> * while ((size = availableSize(stream, size)) > 0) { * System.out.println("available"); * } * </pre> */ public void test() { } And trying to format it here is what we got: /** * The following is a Java snipet. * * <pre> * while ((size = availableSize(stream, size)) > 0) { * System.out.println("available"); } * </pre> */ public void test() { }
|
resolved fixed
|
8cecdcd
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-14T07:55:00Z | 2003-10-01T20:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/comment/ICommentAttributes.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;
/**
* General comment range attributes.
*
* @since 3.0
*/
public interface ICommentAttributes {
/** Range has blank line attribute */
public static final int COMMENT_BLANKLINE= 1 << 1;
/** Range has line break attribute */
public static final int COMMENT_BREAK= 1 << 2;
/** Range has close tag attribute */
public static final int COMMENT_CLOSE= 1 << 3;
/** Range has source code attribute */
public static final int COMMENT_CODE= 1 << 4;
/** Range has html tag attribute */
public static final int COMMENT_HTML= 1 << 5;
/** Range has the immutable region attribute */
public static final int COMMENT_IMMUTABLE= 1 << 6;
/** Range has new line attribute */
public static final int COMMENT_NEWLINE= 1 << 7;
/** Range has open tag attribute */
public static final int COMMENT_OPEN= 1 << 8;
/** Range has paragraph attribute */
public static final int COMMENT_PARAGRAPH= 1 << 9;
/** Range has parameter tag attribute */
public static final int COMMENT_PARAMETER= 1 << 10;
/** Range has root tag attribute */
public static final int COMMENT_ROOT= 1 << 11;
/** Range has paragraph separator attribute */
public static final int COMMENT_SEPARATOR= 1 << 12;
}
|
44,035 |
Bug 44035 [formatting] Error in formatting parts of java code snippets in comment
|
This is for build I20030930. The Java code formatter options are set to Format java code snippets. Taking the following comment: /** * The following is a Java snipet. * * <pre> * while ((size = availableSize(stream, size)) > 0) { * System.out.println("available"); * } * </pre> */ public void test() { } And trying to format it here is what we got: /** * The following is a Java snipet. * * <pre> * while ((size = availableSize(stream, size)) > 0) { * System.out.println("available"); } * </pre> */ public void test() { }
|
resolved fixed
|
8cecdcd
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-14T07:55:00Z | 2003-10-01T20:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/comment/Java2HTMLEntityReader.java
| |
44,035 |
Bug 44035 [formatting] Error in formatting parts of java code snippets in comment
|
This is for build I20030930. The Java code formatter options are set to Format java code snippets. Taking the following comment: /** * The following is a Java snipet. * * <pre> * while ((size = availableSize(stream, size)) > 0) { * System.out.println("available"); * } * </pre> */ public void test() { } And trying to format it here is what we got: /** * The following is a Java snipet. * * <pre> * while ((size = availableSize(stream, size)) > 0) { * System.out.println("available"); } * </pre> */ public void test() { }
|
resolved fixed
|
8cecdcd
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-14T07:55:00Z | 2003-10-01T20:26:40Z |
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.ContentFormatter2;
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 IJavaDocTagConstants {
/** Position category of javadoc code ranges */
protected static final String CODE_POSITION_CATEGORY= "__javadoc_code_position"; //$NON-NLS-1$
/** Should html tags be formatted? */
private final boolean fFormatHtml;
/** Should source code regions be formatted? */
private final boolean fFormatSource;
/**
* 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= strategy.getPreferences();
fFormatSource= IPreferenceStore.TRUE.equals(preferences.get(PreferenceConstants.FORMATTER_COMMENT_FORMATSOURCE));
fFormatHtml= IPreferenceStore.TRUE.equals(preferences.get(PreferenceConstants.FORMATTER_COMMENT_FORMATHTML));
}
/*
* @see org.eclipse.jdt.internal.ui.text.comment.CommentRegion#applyRegion(java.lang.String,int)
*/
protected void applyRegion(final String indentation, final int width) {
super.applyRegion(indentation, width);
if (fFormatSource) {
final ContentFormatter2 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#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(COMMENT_CODE);
final boolean isLastCode= previous.hasAttribute(COMMENT_CODE);
try {
final int index= getOffset();
final IDocument document= getDocument();
if (!isLastCode && isCurrentCode)
document.addPosition(CODE_POSITION_CATEGORY, new Position(index + next.getOffset() + next.getLength()));
else if (isLastCode && !isCurrentCode)
document.addPosition(CODE_POSITION_CATEGORY, new Position(index + previous.getOffset()));
} catch (BadLocationException exception) {
// Should not happen
} catch (BadPositionCategoryException exception) {
// Should not happen
}
if (previous.hasAttribute(COMMENT_IMMUTABLE) && next.hasAttribute(COMMENT_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.MultiCommentRegion#markHtmlRanges()
*/
protected final void markHtmlRanges() {
markTagRanges(JAVADOC_IMMUTABLE_TAGS, COMMENT_IMMUTABLE, true);
if (fFormatSource)
markTagRanges(JAVADOC_CODE_TAGS, COMMENT_CODE, false);
}
/*
* @see org.eclipse.jdt.internal.ui.text.comment.MultiCommentRegion#markHtmlTags(org.eclipse.jdt.internal.ui.text.comment.CommentRange,java.lang.String)
*/
protected final void markHtmlTag(final CommentRange range, final String token) {
if (range.hasAttribute(COMMENT_HTML)) {
range.markHtmlTag(JAVADOC_IMMUTABLE_TAGS, token, COMMENT_IMMUTABLE, true, true);
if (fFormatHtml) {
range.markHtmlTag(JAVADOC_SEPARATOR_TAGS, token, COMMENT_SEPARATOR, true, true);
range.markHtmlTag(JAVADOC_BREAK_TAGS, token, COMMENT_BREAK, false, true);
range.markHtmlTag(JAVADOC_NEWLINE_TAGS, token, COMMENT_NEWLINE, true, false);
} else
range.markHtmlTag(JAVADOC_CODE_TAGS, token, COMMENT_SEPARATOR, true, true);
}
}
/*
* @see org.eclipse.jdt.internal.ui.text.comment.MultiCommentRegion#markJavadocTag(org.eclipse.jdt.internal.ui.text.comment.CommentRange,java.lang.String)
*/
protected final void markJavadocTag(final CommentRange range, final String token) {
range.markPrefixTag(JAVADOC_PARAM_TAGS, COMMENT_TAG_PREFIX, token, COMMENT_PARAMETER);
range.markPrefixTag(JAVADOC_ROOT_TAGS, COMMENT_TAG_PREFIX, token, COMMENT_ROOT);
}
/**
* Marks tag ranges in this javadoc region.
*
* @param tags
* The tags which confine the attributed ranges
* @param key
* The key of the attribute to set when an attributed range has
* been recognized
* @param include
* <code>true</code> iff end tags in this attributed range
* should be attributed too, <code>false</code> otherwise
*/
protected final void markTagRanges(final String[] tags, final int key, final boolean include) {
int level= 0;
int count= 0;
String token= null;
CommentRange current= null;
for (int index= 0; index < tags.length; index++) {
level= 0;
for (final Iterator iterator= getRanges().iterator(); iterator.hasNext();) {
current= (CommentRange)iterator.next();
count= current.getLength();
if (count > 0) {
token= getText(current.getOffset(), current.getLength());
level= current.markRange(token, tags[index], level, key, include);
}
}
}
}
}
|
44,035 |
Bug 44035 [formatting] Error in formatting parts of java code snippets in comment
|
This is for build I20030930. The Java code formatter options are set to Format java code snippets. Taking the following comment: /** * The following is a Java snipet. * * <pre> * while ((size = availableSize(stream, size)) > 0) { * System.out.println("available"); * } * </pre> */ public void test() { } And trying to format it here is what we got: /** * The following is a Java snipet. * * <pre> * while ((size = availableSize(stream, size)) > 0) { * System.out.println("available"); } * </pre> */ public void test() { }
|
resolved fixed
|
8cecdcd
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-14T07:55:00Z | 2003-10-01T20:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/comment/JavaSnippetFormattingStrategy.java
| |
44,035 |
Bug 44035 [formatting] Error in formatting parts of java code snippets in comment
|
This is for build I20030930. The Java code formatter options are set to Format java code snippets. Taking the following comment: /** * The following is a Java snipet. * * <pre> * while ((size = availableSize(stream, size)) > 0) { * System.out.println("available"); * } * </pre> */ public void test() { } And trying to format it here is what we got: /** * The following is a Java snipet. * * <pre> * while ((size = availableSize(stream, size)) > 0) { * System.out.println("available"); } * </pre> */ public void test() { }
|
resolved fixed
|
8cecdcd
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-14T07:55:00Z | 2003-10-01T20:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/comment/MultiCommentLine.java
|
/*****************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*****************************************************************************/
package org.eclipse.jdt.internal.ui.text.comment;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.Region;
/**
* Multi-line comment line in a comment region.
*
* @since 3.0
*/
public class MultiCommentLine extends CommentLine implements ICommentAttributes, IHtmlTagConstants, ILinkTagConstants {
/** Line prefix of multi-line comment content lines */
public static final String MULTI_COMMENT_CONTENT_PREFIX= " * "; //$NON-NLS-1$
/** Line prefix of multi-line comment end lines */
public static final String MULTI_COMMENT_END_PREFIX= " */"; //$NON-NLS-1$
/** Line prefix of multi-line comment content lines */
public static final String MULTI_COMMENT_START_PREFIX= "/* "; //$NON-NLS-1$
/** The reference indentation of this line */
private String fIndentation= ""; //$NON-NLS-1$
/**
* Creates a new multi-line comment line.
*
* @param region
* Comment region to create the line for
*/
protected MultiCommentLine(final CommentRegion region) {
super(region);
}
/*
* @see org.eclipse.jdt.internal.ui.text.comment.CommentLine#adapt(org.eclipse.jdt.internal.ui.text.comment.CommentLine)
*/
protected void adapt(final CommentLine previous) {
if (!hasAttribute(COMMENT_ROOT) && !hasAttribute(COMMENT_PARAMETER) && !previous.hasAttribute(COMMENT_BLANKLINE))
fIndentation= previous.getIndentation();
}
/*
* @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 MultiCommentRegion parent= (MultiCommentRegion)getParent();
if (range.hasAttribute(COMMENT_PARAMETER))
setAttribute(COMMENT_PARAMETER);
else if (range.hasAttribute(COMMENT_ROOT))
setAttribute(COMMENT_ROOT);
else if (range.hasAttribute(COMMENT_BLANKLINE))
setAttribute(COMMENT_BLANKLINE);
final int ranges= getSize();
if (ranges == 1) {
if (parent.isIndentRoots()) {
final CommentRange first= getFirst();
final String common= parent.getText(first.getOffset(), first.getLength()) + CommentRegion.COMMENT_RANGE_DELIMITER;
if (hasAttribute(COMMENT_ROOT))
fIndentation= common;
else if (hasAttribute(COMMENT_PARAMETER)) {
if (parent.isIndentDescriptions())
fIndentation= common + "\t"; //$NON-NLS-1$
else
fIndentation= common;
}
}
}
super.append(range);
}
/*
* @see org.eclipse.jdt.internal.ui.text.comment.CommentLine#getContentLinePrefix()
*/
protected String getContentPrefix() {
return MULTI_COMMENT_CONTENT_PREFIX;
}
/*
* @see org.eclipse.jdt.internal.ui.text.comment.CommentLine#getEndLinePrefix()
*/
protected String getEndingPrefix() {
return MULTI_COMMENT_END_PREFIX;
}
/**
* Returns the reference indentation to use for this line.
*
* @return The reference indentation for this line
*/
protected final String getIndentation() {
return fIndentation;
}
/*
* @see org.eclipse.jdt.internal.ui.text.comment.CommentLine#getStartLinePrefix()
*/
protected String getStartingPrefix() {
return MULTI_COMMENT_START_PREFIX;
}
/*
* @see org.eclipse.jdt.internal.ui.text.comment.CommentLine#scanLine(int)
*/
protected void scanLine(final int line) {
final CommentRegion parent= getParent();
final String start= getStartingPrefix().trim();
final String end= getEndingPrefix().trim();
final String content= getContentPrefix().trim();
final int lines= parent.getSize();
final CommentRange range= getFirst();
int offset= 0;
int postfix= 0;
String text= parent.getText(range.getOffset(), range.getLength());
if (line == 0) {
offset= text.indexOf(start);
if (offset >= 0) {
offset += start.length();
range.trimBegin(offset);
postfix= text.lastIndexOf(end);
if (postfix > offset)
range.setLength(postfix - offset);
else {
postfix= text.lastIndexOf(content);
if (postfix >= offset) {
range.setLength(postfix - offset);
parent.setBorder(BORDER_UPPER);
if (postfix > offset) {
text= parent.getText(range.getOffset(), range.getLength());
final IRegion region= trimLine(text, content);
range.move(region.getOffset());
range.setLength(region.getLength());
}
}
}
}
} else if (line == lines - 1) {
offset= text.indexOf(content);
if (offset >= 0) {
range.trimBegin(offset + 1);
if (text.startsWith(end, offset))
range.setLength(0);
else {
postfix= text.lastIndexOf(end);
if (postfix > offset) {
range.trimEnd(-end.length());
text= parent.getText(range.getOffset(), range.getLength());
final IRegion region= trimLine(text, content);
if (region.getOffset() != 0 || region.getLength() != text.length()) {
range.move(region.getOffset());
range.setLength(region.getLength());
parent.setBorder(BORDER_UPPER);
parent.setBorder(BORDER_LOWER);
}
}
}
}
} else {
offset= text.indexOf(content);
if (offset >= 0) {
offset += content.length();
range.trimBegin(offset);
}
}
}
/*
* @see org.eclipse.jdt.internal.ui.text.comment.CommentLine#tokenizeLine(int)
*/
protected void tokenizeLine(int line) {
int offset= 0;
int index= offset;
final CommentRegion parent= getParent();
final CommentRange range= getFirst();
final int begin= range.getOffset();
final String content= parent.getText(begin, range.getLength());
final int length= content.length();
while (offset < length && Character.isWhitespace(content.charAt(offset)))
offset++;
CommentRange result= null;
if (offset >= length && !parent.isClearLines() && (line > 0 && line < parent.getSize() - 1)) {
result= new CommentRange(begin, 0);
result.setAttribute(COMMENT_BLANKLINE);
parent.append(result);
}
int attribute= 0;
while (offset < length) {
while (offset < length && Character.isWhitespace(content.charAt(offset)))
offset++;
attribute= 0;
index= offset;
if (index < length) {
if (content.charAt(index) == HTML_TAG_PREFIX) {
while (index < length && content.charAt(index) != HTML_TAG_POSTFIX)
index++;
if (index < length && content.charAt(index) == HTML_TAG_POSTFIX)
index++;
attribute= COMMENT_HTML;
} else if (content.startsWith(LINK_TAG_PREFIX, index)) {
while (index < length && content.charAt(index) != LINK_TAG_POSTFIX)
index++;
if (index < length && content.charAt(index) == LINK_TAG_POSTFIX)
index++;
attribute= COMMENT_OPEN | COMMENT_CLOSE;
} else {
while (index < length && !Character.isWhitespace(content.charAt(index)) && content.charAt(index) != HTML_TAG_PREFIX && !content.startsWith(LINK_TAG_PREFIX, index))
index++;
}
}
if (index - offset > 0) {
result= new CommentRange(begin + offset, index - offset);
result.setAttribute(attribute);
parent.append(result);
offset= index;
}
}
}
/**
* Removes all leading and trailing occurrences from <code>line</code>.
*
* @param line
* The string to remove the occurrences of <code>trimmable</code>
* @param trimmable
* The string to remove from <code>line</code>
* @return The region of the trimmed substring within <code>line</code>
*/
protected final IRegion trimLine(final String line, final String trimmable) {
final int trim= trimmable.length();
int offset= 0;
int length= line.length() - trim;
while (line.startsWith(trimmable, offset))
offset += trim;
while (line.startsWith(trimmable, length))
length -= trim;
return new Region(offset, length + trim);
}
}
|
44,035 |
Bug 44035 [formatting] Error in formatting parts of java code snippets in comment
|
This is for build I20030930. The Java code formatter options are set to Format java code snippets. Taking the following comment: /** * The following is a Java snipet. * * <pre> * while ((size = availableSize(stream, size)) > 0) { * System.out.println("available"); * } * </pre> */ public void test() { } And trying to format it here is what we got: /** * The following is a Java snipet. * * <pre> * while ((size = availableSize(stream, size)) > 0) { * System.out.println("available"); } * </pre> */ public void test() { }
|
resolved fixed
|
8cecdcd
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-14T07:55:00Z | 2003-10-01T20:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/comment/MultiCommentRegion.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.ListIterator;
import java.util.Map;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.TypedPosition;
import org.eclipse.jdt.ui.PreferenceConstants;
/**
* Multi-comment region in a source code document.
*
* @since 3.0
*/
public class MultiCommentRegion extends CommentRegion implements ICommentTagConstants {
/** Should root tag parameter descriptions be indented after the tag? */
private final boolean fIndentDescriptions;
/** Should root tag parameter descriptions be indented? */
private final boolean fIndentRoots;
/** Should description of parameters go to the next line? */
private final boolean fParameterNewLine;
/** Should root tags be separated from description? */
private boolean fSeparateRoots;
/**
* Creates a new multi-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 MultiCommentRegion(final CommentFormattingStrategy strategy, final TypedPosition position, final String delimiter) {
super(strategy, position, delimiter);
final Map preferences= strategy.getPreferences();
fIndentRoots= IPreferenceStore.TRUE.equals(preferences.get(PreferenceConstants.FORMATTER_COMMENT_INDENTROOTTAGS));
fIndentDescriptions= IPreferenceStore.TRUE.equals(preferences.get(PreferenceConstants.FORMATTER_COMMENT_INDENTPARAMETERDESCRIPTION));
fSeparateRoots= IPreferenceStore.TRUE.equals(preferences.get(PreferenceConstants.FORMATTER_COMMENT_SEPARATEROOTTAGS));
fParameterNewLine= IPreferenceStore.TRUE.equals(preferences.get(PreferenceConstants.FORMATTER_COMMENT_NEWLINEFORPARAMETER));
}
/*
* @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 position, int count) {
final boolean blank= next.hasAttribute(COMMENT_BLANKLINE);
if (next.getLength() <= 2 && !blank && !isCommentWord(next))
return true;
if (fParameterNewLine && line.hasAttribute(COMMENT_PARAMETER) && line.getSize() > 1)
return false;
if (previous != null) {
if (previous.hasAttribute(COMMENT_ROOT))
return true;
if (position != 0 && (blank || previous.hasAttribute(COMMENT_BLANKLINE) || next.hasAttribute(COMMENT_PARAMETER) || next.hasAttribute(COMMENT_ROOT) || next.hasAttribute(COMMENT_SEPARATOR) || next.hasAttribute(COMMENT_NEWLINE) || previous.hasAttribute(COMMENT_BREAK) || previous.hasAttribute(COMMENT_SEPARATOR)))
return false;
if (next.hasAttribute(COMMENT_IMMUTABLE) && previous.hasAttribute(COMMENT_IMMUTABLE))
return true;
}
if (fIndentRoots && !line.hasAttribute(COMMENT_ROOT) && !line.hasAttribute(COMMENT_PARAMETER))
count -= stringToLength(line.getIndentation());
return super.canAppend(line, previous, next, position, count);
}
/*
* @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(CommentLine predecessor, CommentLine successor, CommentRange previous, CommentRange next, String indentation) {
final String delimiter= super.getDelimiter(predecessor, successor, previous, next, indentation);
if (previous != null) {
if (previous.hasAttribute(COMMENT_IMMUTABLE | COMMENT_SEPARATOR) && !next.hasAttribute(COMMENT_CODE) && !successor.hasAttribute(COMMENT_BLANKLINE))
return delimiter + delimiter;
else if (previous.hasAttribute(COMMENT_CODE) && !next.hasAttribute(COMMENT_CODE))
return getDelimiter();
else if ((next.hasAttribute(COMMENT_IMMUTABLE | COMMENT_SEPARATOR) || ((fSeparateRoots || !isClearLines()) && previous.hasAttribute(COMMENT_PARAGRAPH))) && !successor.hasAttribute(COMMENT_BLANKLINE))
return delimiter + delimiter;
else if (fIndentRoots && !predecessor.hasAttribute(COMMENT_ROOT) && !predecessor.hasAttribute(COMMENT_PARAMETER) && !predecessor.hasAttribute(COMMENT_BLANKLINE))
return delimiter + stringToIndent(predecessor.getIndentation(), 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(COMMENT_CODE) && previous.hasAttribute(COMMENT_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 root tag parameter descriptions be indented after the tag?
*
* @return <code>true</code> iff the descriptions should be indented after,
* <code>false</code> otherwise.
*/
protected final boolean isIndentDescriptions() {
return fIndentDescriptions;
}
/**
* Should root tag parameter descriptions be indented?
*
* @return <code>true</code> iff the root tags should be indented,
* <code>false</code> otherwise.
*/
protected final boolean isIndentRoots() {
return fIndentRoots;
}
/**
* Marks the comment ranges confined by html tags.
*/
protected void markHtmlRanges() {
// Do nothing
}
/**
* Marks the comment range with its html tag attributes.
*
* @param range
* The comment range to mark
* @param token
* Token associated with the comment range
*/
protected void markHtmlTag(final CommentRange range, final String token) {
// Do nothing
}
/**
* Marks the comment range with its javadoc tag attributes.
*
* @param range
* The comment range to mark
* @param token
* Token associated with the comment range
*/
protected void markJavadocTag(final CommentRange range, final String token) {
range.markPrefixTag(COMMENT_ROOT_TAGS, COMMENT_TAG_PREFIX, token, COMMENT_ROOT);
}
/*
* @see org.eclipse.jdt.internal.ui.text.comment.CommentRegion#markRegion()
*/
protected final void markRegion() {
int count= 0;
boolean paragraph= false;
String token= null;
CommentRange range= null;
CommentRange blank= null;
for (final ListIterator iterator= getRanges().listIterator(); iterator.hasNext();) {
range= (CommentRange)iterator.next();
count= range.getLength();
if (count > 0) {
token= getText(range.getOffset(), count).toLowerCase();
markJavadocTag(range, token);
if (!paragraph && (range.hasAttribute(COMMENT_ROOT) || range.hasAttribute(COMMENT_PARAMETER))) {
iterator.previous();
while (iterator.hasPrevious()) {
blank= (CommentRange)iterator.previous();
if (blank.hasAttribute(COMMENT_BLANKLINE))
iterator.remove();
else
break;
}
range.setAttribute(COMMENT_PARAGRAPH);
paragraph= true;
}
markHtmlTag(range, token);
}
}
markHtmlRanges();
}
}
|
44,035 |
Bug 44035 [formatting] Error in formatting parts of java code snippets in comment
|
This is for build I20030930. The Java code formatter options are set to Format java code snippets. Taking the following comment: /** * The following is a Java snipet. * * <pre> * while ((size = availableSize(stream, size)) > 0) { * System.out.println("available"); * } * </pre> */ public void test() { } And trying to format it here is what we got: /** * The following is a Java snipet. * * <pre> * while ((size = availableSize(stream, size)) > 0) { * System.out.println("available"); } * </pre> */ public void test() { }
|
resolved fixed
|
8cecdcd
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-14T07:55:00Z | 2003-10-01T20:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/text/JavaSourceViewerConfiguration.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.text;
import java.util.Vector;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.DefaultInformationControl;
import org.eclipse.jface.text.DefaultTextDoubleClickStrategy;
import org.eclipse.jface.text.IAutoIndentStrategy;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IInformationControl;
import org.eclipse.jface.text.IInformationControlCreator;
import org.eclipse.jface.text.ITextDoubleClickStrategy;
import org.eclipse.jface.text.ITextHover;
import org.eclipse.jface.text.ITextViewerExtension2;
import org.eclipse.jface.text.contentassist.ContentAssistant;
import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
import org.eclipse.jface.text.contentassist.IContentAssistant;
import org.eclipse.jface.text.formatter.ContentFormatter2;
import org.eclipse.jface.text.formatter.IContentFormatter;
import org.eclipse.jface.text.formatter.IFormattingStrategy;
import org.eclipse.jface.text.information.IInformationPresenter;
import org.eclipse.jface.text.information.IInformationProvider;
import org.eclipse.jface.text.information.InformationPresenter;
import org.eclipse.jface.text.presentation.IPresentationReconciler;
import org.eclipse.jface.text.presentation.PresentationReconciler;
import org.eclipse.jface.text.reconciler.IReconciler;
import org.eclipse.jface.text.rules.DefaultDamagerRepairer;
import org.eclipse.jface.text.rules.RuleBasedScanner;
import org.eclipse.jface.text.source.IAnnotationHover;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.corext.util.CodeFormatterUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.ContentAssistPreference;
import org.eclipse.jdt.internal.ui.text.HTMLTextPresenter;
import org.eclipse.jdt.internal.ui.text.IJavaPartitions;
import org.eclipse.jdt.internal.ui.text.JavaAnnotationHover;
import org.eclipse.jdt.internal.ui.text.JavaElementProvider;
import org.eclipse.jdt.internal.ui.text.JavaOutlineInformationControl;
import org.eclipse.jdt.internal.ui.text.JavaReconciler;
import org.eclipse.jdt.internal.ui.text.comment.CommentFormattingStrategy;
import org.eclipse.jdt.internal.ui.text.java.JavaAutoIndentStrategy;
import org.eclipse.jdt.internal.ui.text.java.JavaCompletionProcessor;
import org.eclipse.jdt.internal.ui.text.java.JavaDoubleClickSelector;
import org.eclipse.jdt.internal.ui.text.java.JavaFormattingStrategy;
import org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy;
import org.eclipse.jdt.internal.ui.text.java.JavaStringAutoIndentStrategy;
import org.eclipse.jdt.internal.ui.text.java.JavaStringDoubleClickSelector;
import org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverDescriptor;
import org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy;
import org.eclipse.jdt.internal.ui.text.java.hover.JavaInformationProvider;
import org.eclipse.jdt.internal.ui.text.javadoc.JavaDocAutoIndentStrategy;
import org.eclipse.jdt.internal.ui.text.javadoc.JavaDocCompletionProcessor;
import org.eclipse.jdt.internal.ui.typehierarchy.HierarchyInformationControl;
/**
* Configuration for a source viewer which shows Java code.
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*/
public class JavaSourceViewerConfiguration extends SourceViewerConfiguration {
/**
* Preference key used to look up display tab width.
*
* @since 2.0
*/
public final static String PREFERENCE_TAB_WIDTH= PreferenceConstants.EDITOR_TAB_WIDTH;
/**
* Preference key for inserting spaces rather than tabs.
*
* @since 2.0
*/
public final static String SPACES_FOR_TABS= PreferenceConstants.EDITOR_SPACES_FOR_TABS;
private JavaTextTools fJavaTextTools;
private ITextEditor fTextEditor;
private String fDocumentPartitioning;
/**
* Creates a new Java source viewer configuration for viewers in the given editor
* using the given Java tools and the specified document partitioning.
*
* @param tools the Java text tools to be used
* @param editor the editor in which the configured viewer(s) will reside
* @param partitioning the document partitioning for this configuration
* @see JavaTextTools
* @since 3.0
*/
public JavaSourceViewerConfiguration(JavaTextTools tools, ITextEditor editor, String partitioning) {
fJavaTextTools= tools;
fTextEditor= editor;
fDocumentPartitioning= partitioning;
}
/**
* Creates a new Java source viewer configuration for viewers in the given editor
* using the given Java tools.
*
* @param tools the Java text tools to be used
* @param editor the editor in which the configured viewer(s) will reside
* @see JavaTextTools
*/
public JavaSourceViewerConfiguration(JavaTextTools tools, ITextEditor editor) {
this(tools, editor, null);
}
/**
* Returns the Java source code scanner for this configuration.
*
* @return the Java source code scanner
*/
protected RuleBasedScanner getCodeScanner() {
return fJavaTextTools.getCodeScanner();
}
/**
* Returns the Java multiline comment scanner for this configuration.
*
* @return the Java multiline comment scanner
* @since 2.0
*/
protected RuleBasedScanner getMultilineCommentScanner() {
return fJavaTextTools.getMultilineCommentScanner();
}
/**
* Returns the Java singleline comment scanner for this configuration.
*
* @return the Java singleline comment scanner
* @since 2.0
*/
protected RuleBasedScanner getSinglelineCommentScanner() {
return fJavaTextTools.getSinglelineCommentScanner();
}
/**
* Returns the Java string scanner for this configuration.
*
* @return the Java string scanner
* @since 2.0
*/
protected RuleBasedScanner getStringScanner() {
return fJavaTextTools.getStringScanner();
}
/**
* Returns the JavaDoc scanner for this configuration.
*
* @return the JavaDoc scanner
*/
protected RuleBasedScanner getJavaDocScanner() {
return fJavaTextTools.getJavaDocScanner();
}
/**
* Returns the color manager for this configuration.
*
* @return the color manager
*/
protected IColorManager getColorManager() {
return fJavaTextTools.getColorManager();
}
/**
* Returns the editor in which the configured viewer(s) will reside.
*
* @return the enclosing editor
*/
protected ITextEditor getEditor() {
return fTextEditor;
}
/**
* Returns the preference store used by this configuration to initialize
* the individual bits and pieces.
*
* @return the preference store used to initialize this configuration
*
* @since 2.0
*/
public IPreferenceStore getPreferenceStore() {
return fJavaTextTools.getPreferenceStore();
}
/*
* @see SourceViewerConfiguration#getPresentationReconciler(ISourceViewer)
*/
public IPresentationReconciler getPresentationReconciler(ISourceViewer sourceViewer) {
PresentationReconciler reconciler= new PresentationReconciler();
reconciler.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer));
DefaultDamagerRepairer dr= new DefaultDamagerRepairer(getCodeScanner());
reconciler.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE);
reconciler.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE);
dr= new DefaultDamagerRepairer(getJavaDocScanner());
reconciler.setDamager(dr, IJavaPartitions.JAVA_DOC);
reconciler.setRepairer(dr, IJavaPartitions.JAVA_DOC);
dr= new DefaultDamagerRepairer(getMultilineCommentScanner());
reconciler.setDamager(dr, IJavaPartitions.JAVA_MULTI_LINE_COMMENT);
reconciler.setRepairer(dr, IJavaPartitions.JAVA_MULTI_LINE_COMMENT);
dr= new DefaultDamagerRepairer(getSinglelineCommentScanner());
reconciler.setDamager(dr, IJavaPartitions.JAVA_SINGLE_LINE_COMMENT);
reconciler.setRepairer(dr, IJavaPartitions.JAVA_SINGLE_LINE_COMMENT);
dr= new DefaultDamagerRepairer(getStringScanner());
reconciler.setDamager(dr, IJavaPartitions.JAVA_STRING);
reconciler.setRepairer(dr, IJavaPartitions.JAVA_STRING);
dr= new DefaultDamagerRepairer(getStringScanner());
reconciler.setDamager(dr, IJavaPartitions.JAVA_CHARACTER);
reconciler.setRepairer(dr, IJavaPartitions.JAVA_CHARACTER);
return reconciler;
}
/*
* @see SourceViewerConfiguration#getContentAssistant(ISourceViewer)
*/
public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) {
if (getEditor() != null) {
ContentAssistant assistant= new ContentAssistant();
assistant.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer));
IContentAssistProcessor processor= new JavaCompletionProcessor(getEditor());
assistant.setContentAssistProcessor(processor, 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(processor, IJavaPartitions.JAVA_STRING);
assistant.setContentAssistProcessor(processor, IJavaPartitions.JAVA_SINGLE_LINE_COMMENT);
assistant.setContentAssistProcessor(new JavaDocCompletionProcessor(getEditor()), IJavaPartitions.JAVA_DOC);
ContentAssistPreference.configure(assistant, getPreferenceStore());
assistant.setContextInformationPopupOrientation(ContentAssistant.CONTEXT_INFO_ABOVE);
assistant.setInformationControlCreator(getInformationControlCreator(sourceViewer));
return assistant;
}
return null;
}
/*
* @see SourceViewerConfiguration#getReconciler(ISourceViewer)
*/
public IReconciler getReconciler(ISourceViewer sourceViewer) {
if (getEditor() != null && getEditor().isEditable()) {
JavaReconciler reconciler= new JavaReconciler(getEditor(), new JavaReconcilingStrategy(getEditor()), false);
reconciler.setProgressMonitor(new NullProgressMonitor());
reconciler.setDelay(500);
return reconciler;
}
return null;
}
/*
* @see SourceViewerConfiguration#getAutoIndentStrategy(ISourceViewer, String)
*/
public IAutoIndentStrategy getAutoIndentStrategy(ISourceViewer sourceViewer, String contentType) {
if (IJavaPartitions.JAVA_DOC.equals(contentType) ||
IJavaPartitions.JAVA_MULTI_LINE_COMMENT.equals(contentType))
return new JavaDocAutoIndentStrategy(getConfiguredDocumentPartitioning(sourceViewer));
else if (IJavaPartitions.JAVA_STRING.equals(contentType))
return new JavaStringAutoIndentStrategy(getConfiguredDocumentPartitioning(sourceViewer));
return new JavaAutoIndentStrategy(getConfiguredDocumentPartitioning(sourceViewer));
}
/*
* @see SourceViewerConfiguration#getDoubleClickStrategy(ISourceViewer, String)
*/
public ITextDoubleClickStrategy getDoubleClickStrategy(ISourceViewer sourceViewer, String contentType) {
if (IJavaPartitions.JAVA_DOC.equals(contentType) ||
IJavaPartitions.JAVA_MULTI_LINE_COMMENT.equals(contentType) ||
IJavaPartitions.JAVA_SINGLE_LINE_COMMENT.equals(contentType))
return new DefaultTextDoubleClickStrategy();
else if (IJavaPartitions.JAVA_STRING.equals(contentType) ||
IJavaPartitions.JAVA_CHARACTER.equals(contentType))
return new JavaStringDoubleClickSelector(getConfiguredDocumentPartitioning(sourceViewer));
return new JavaDoubleClickSelector();
}
/*
* @see SourceViewerConfiguration#getDefaultPrefixes(ISourceViewer, String)
* @since 2.0
*/
public String[] getDefaultPrefixes(ISourceViewer sourceViewer, String contentType) {
return new String[] { "//", "" }; //$NON-NLS-1$ //$NON-NLS-2$
}
/*
* @see SourceViewerConfiguration#getIndentPrefixes(ISourceViewer, String)
*/
public String[] getIndentPrefixes(ISourceViewer sourceViewer, String contentType) {
Vector vector= new Vector();
// prefix[0] is either '\t' or ' ' x tabWidth, depending on useSpaces
int tabWidth= CodeFormatterUtil.getTabWidth();
boolean useSpaces= getPreferenceStore().getBoolean(SPACES_FOR_TABS);
for (int i= 0; i <= tabWidth; i++) {
StringBuffer prefix= new StringBuffer();
if (useSpaces) {
for (int j= 0; j + i < tabWidth; j++)
prefix.append(' ');
if (i != 0)
prefix.append('\t');
} else {
for (int j= 0; j < i; j++)
prefix.append(' ');
if (i != tabWidth)
prefix.append('\t');
}
vector.add(prefix.toString());
}
vector.add(""); //$NON-NLS-1$
return (String[]) vector.toArray(new String[vector.size()]);
}
/*
* @see SourceViewerConfiguration#getTabWidth(ISourceViewer)
*/
public int getTabWidth(ISourceViewer sourceViewer) {
return getPreferenceStore().getInt(PREFERENCE_TAB_WIDTH);
}
/*
* @see SourceViewerConfiguration#getAnnotationHover(ISourceViewer)
*/
public IAnnotationHover getAnnotationHover(ISourceViewer sourceViewer) {
return new JavaAnnotationHover(JavaAnnotationHover.VERTICAL_RULER_HOVER);
}
/*
* @see SourceViewerConfiguration#getOverviewRulerAnnotationHover(ISourceViewer)
* @since 3.0
*/
public IAnnotationHover getOverviewRulerAnnotationHover(ISourceViewer sourceViewer) {
return new JavaAnnotationHover(JavaAnnotationHover.OVERVIEW_RULER_HOVER);
}
/*
* @see SourceViewerConfiguration#getConfiguredTextHoverStateMasks(ISourceViewer, String)
* @since 2.1
*/
public int[] getConfiguredTextHoverStateMasks(ISourceViewer sourceViewer, String contentType) {
JavaEditorTextHoverDescriptor[] hoverDescs= JavaPlugin.getDefault().getJavaEditorTextHoverDescriptors();
int stateMasks[]= new int[hoverDescs.length];
int stateMasksLength= 0;
for (int i= 0; i < hoverDescs.length; i++) {
if (hoverDescs[i].isEnabled()) {
int j= 0;
int stateMask= hoverDescs[i].getStateMask();
while (j < stateMasksLength) {
if (stateMasks[j] == stateMask)
break;
j++;
}
if (j == stateMasksLength)
stateMasks[stateMasksLength++]= stateMask;
}
}
if (stateMasksLength == hoverDescs.length)
return stateMasks;
int[] shortenedStateMasks= new int[stateMasksLength];
System.arraycopy(stateMasks, 0, shortenedStateMasks, 0, stateMasksLength);
return shortenedStateMasks;
}
/*
* @see SourceViewerConfiguration#getTextHover(ISourceViewer, String, int)
* @since 2.1
*/
public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType, int stateMask) {
JavaEditorTextHoverDescriptor[] hoverDescs= JavaPlugin.getDefault().getJavaEditorTextHoverDescriptors();
int i= 0;
while (i < hoverDescs.length) {
if (hoverDescs[i].isEnabled() && hoverDescs[i].getStateMask() == stateMask)
return new JavaEditorTextHoverProxy(hoverDescs[i], getEditor());
i++;
}
return null;
}
/*
* @see SourceViewerConfiguration#getTextHover(ISourceViewer, String)
*/
public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType) {
return getTextHover(sourceViewer, contentType, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK);
}
/*
* @see SourceViewerConfiguration#getConfiguredContentTypes(ISourceViewer)
*/
public String[] getConfiguredContentTypes(ISourceViewer sourceViewer) {
return new String[] {
IDocument.DEFAULT_CONTENT_TYPE,
IJavaPartitions.JAVA_DOC,
IJavaPartitions.JAVA_MULTI_LINE_COMMENT,
IJavaPartitions.JAVA_SINGLE_LINE_COMMENT,
IJavaPartitions.JAVA_STRING,
IJavaPartitions.JAVA_CHARACTER
};
}
/*
* @see org.eclipse.jface.text.source.SourceViewerConfiguration#getConfiguredDocumentPartitioning(org.eclipse.jface.text.source.ISourceViewer)
*/
public String getConfiguredDocumentPartitioning(ISourceViewer sourceViewer) {
if (fDocumentPartitioning != null)
return fDocumentPartitioning;
return super.getConfiguredDocumentPartitioning(sourceViewer);
}
/*
* @see SourceViewerConfiguration#getContentFormatter(ISourceViewer)
*/
public IContentFormatter getContentFormatter(ISourceViewer sourceViewer) {
final ContentFormatter2 formatter= new ContentFormatter2();
formatter.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer));
IFormattingStrategy strategy= new JavaFormattingStrategy(sourceViewer);
formatter.setFormattingStrategy(strategy);
formatter.setFormattingStrategy(strategy, IDocument.DEFAULT_CONTENT_TYPE);
formatter.setFormattingStrategy(new CommentFormattingStrategy(formatter, sourceViewer), IJavaPartitions.JAVA_DOC);
formatter.setFormattingStrategy(new CommentFormattingStrategy(formatter, sourceViewer), IJavaPartitions.JAVA_SINGLE_LINE_COMMENT);
formatter.setFormattingStrategy(new CommentFormattingStrategy(formatter, sourceViewer), IJavaPartitions.JAVA_MULTI_LINE_COMMENT);
return formatter;
}
/*
* @see SourceViewerConfiguration#getInformationControlCreator(ISourceViewer)
* @since 2.0
*/
public IInformationControlCreator getInformationControlCreator(ISourceViewer sourceViewer) {
return new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell parent) {
return new DefaultInformationControl(parent, SWT.NONE, new HTMLTextPresenter(true));
}
};
}
/**
* Returns the information presenter control creator. The creator is a factory creating the
* presenter controls for the given source viewer. This implementation always returns a creator
* for <code>DefaultInformationControl</code> instances.
*
* @param sourceViewer the source viewer to be configured by this configuration
* @return an information control creator
* @since 2.1
*/
private IInformationControlCreator getInformationPresenterControlCreator(ISourceViewer sourceViewer) {
return new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell parent) {
int shellStyle= SWT.RESIZE;
int style= SWT.V_SCROLL | SWT.H_SCROLL;
return new DefaultInformationControl(parent, shellStyle, style, new HTMLTextPresenter(false));
// return new HoverBrowserControl(parent);
}
};
}
/**
* Returns the outline presenter control creator. The creator is a factory creating outline
* presenter controls for the given source viewer. This implementation always returns a creator
* for <code>JavaOutlineInformationControl</code> instances.
*
* @param sourceViewer the source viewer to be configured by this configuration
* @return an information control creator
* @since 2.1
*/
private IInformationControlCreator getOutlinePresenterControlCreator(ISourceViewer sourceViewer) {
return new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell parent) {
int shellStyle= SWT.RESIZE;
int treeStyle= SWT.V_SCROLL | SWT.H_SCROLL;
return new JavaOutlineInformationControl(parent, shellStyle, treeStyle);
}
};
}
private IInformationControlCreator getHierarchyPresenterControlCreator(ISourceViewer sourceViewer) {
return new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell parent) {
int shellStyle= SWT.RESIZE;
int treeStyle= SWT.V_SCROLL | SWT.H_SCROLL;
return new HierarchyInformationControl(parent, shellStyle, treeStyle);
}
};
}
/*
* @see SourceViewerConfiguration#getInformationPresenter(ISourceViewer)
* @since 2.0
*/
public IInformationPresenter getInformationPresenter(ISourceViewer sourceViewer) {
InformationPresenter presenter= new InformationPresenter(getInformationPresenterControlCreator(sourceViewer));
presenter.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer));
IInformationProvider provider= new JavaInformationProvider(getEditor());
presenter.setInformationProvider(provider, IDocument.DEFAULT_CONTENT_TYPE);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_DOC);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_CHARACTER);
presenter.setSizeConstraints(60, 10, true, true);
return presenter;
}
/**
* Returns the outline presenter which will determine and shown
* information requested for the current cursor position.
*
* @param sourceViewer the source viewer to be configured by this configuration
* @param doCodeResolve a boolean which specifies whether code resolve should be used to compute the Java element
* @return an information presenter
* @since 2.1
*/
public IInformationPresenter getOutlinePresenter(ISourceViewer sourceViewer, boolean doCodeResolve) {
InformationPresenter presenter= new InformationPresenter(getOutlinePresenterControlCreator(sourceViewer));
presenter.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer));
presenter.setAnchor(InformationPresenter.ANCHOR_GLOBAL);
IInformationProvider provider= new JavaElementProvider(getEditor(), doCodeResolve);
presenter.setInformationProvider(provider, IDocument.DEFAULT_CONTENT_TYPE);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_DOC);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_MULTI_LINE_COMMENT);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_SINGLE_LINE_COMMENT);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_STRING);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_CHARACTER);
presenter.setSizeConstraints(40, 20, true, false);
return presenter;
}
public IInformationPresenter getHierarchyPresenter(ISourceViewer sourceViewer, boolean doCodeResolve) {
InformationPresenter presenter= new InformationPresenter(getHierarchyPresenterControlCreator(sourceViewer));
presenter.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer));
presenter.setAnchor(InformationPresenter.ANCHOR_GLOBAL);
IInformationProvider provider= new JavaElementProvider(getEditor(), doCodeResolve);
presenter.setInformationProvider(provider, IDocument.DEFAULT_CONTENT_TYPE);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_DOC);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_MULTI_LINE_COMMENT);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_SINGLE_LINE_COMMENT);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_STRING);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_CHARACTER);
presenter.setSizeConstraints(50, 20, true, false);
return presenter;
}
}
|
49,352 |
Bug 49352 [typing] Smart quotes problem
|
M6: write this: System.out.println(filter:) Now let's fix this: - enter a '"' between the ':' and the ')' System.out.println(filter:"") To correct this try to enter a '"' between '(' and 'f' System.out.println(filter:"""")
|
resolved fixed
|
65d4593
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-14T07:56:52Z | 2003-12-26T20:20:00Z |
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.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.IWorkspaceRoot;
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.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.BadPositionCategoryException;
import org.eclipse.jface.text.DocumentCommand;
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.ILineTracker;
import org.eclipse.jface.text.IPositionUpdater;
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.contentassist.IContentAssistantExtension;
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.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.ExclusivePositionUpdater;
import org.eclipse.jdt.internal.ui.text.link.ILinkedListener;
import org.eclipse.jdt.internal.ui.text.link.LinkedEnvironment;
import org.eclipse.jdt.internal.ui.text.link.LinkedPositionGroup;
import org.eclipse.jdt.internal.ui.text.link.LinkedUIControl;
import org.eclipse.jdt.internal.ui.text.link.LinkedUIControl.ExitFlags;
import org.eclipse.jdt.internal.ui.text.link.LinkedUIControl.IExitPolicy;
/**
* 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;
/**
* Text operation code for requesting common prefix completion.
*/
public static final int CONTENTASSIST_COMPLETE_PREFIX= 60;
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;
case CONTENTASSIST_COMPLETE_PREFIX:
if (fContentAssistant instanceof IContentAssistantExtension) {
msg= ((IContentAssistantExtension) fContentAssistant).completePrefix();
setStatusLineErrorMessage(msg);
return;
} else
break;
}
super.doOperation(operation);
}
/*
* @see ITextOperationTarget#canDoOperation(int)
*/
public boolean canDoOperation(int operation) {
if (operation == CORRECTIONASSIST_PROPOSALS)
return isEditable();
else if (operation == CONTENTASSIST_COMPLETE_PREFIX)
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 IExitPolicy {
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(LinkedEnvironment environment, VerifyEvent event, int offset, int length) {
if (event.character == fExitCharacter) {
if (fSize == fStack.size() && !isMasked(offset)) {
BracketLevel level= (BracketLevel) fStack.peek();
if (level.fSecondPosition.offset == offset && length == 0)
// don't enter the character if if its the closing peer
return new ExitFlags(ILinkedListener.UPDATE_CARET, false);
else
return new ExitFlags(ILinkedListener.UPDATE_CARET, true);
}
}
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;
LinkedUIControl fEditor;
Position fFirstPosition;
Position fSecondPosition;
}
private class BracketInserter implements VerifyKeyListener, ILinkedListener {
private boolean fCloseBrackets= true;
private boolean fCloseStrings= true;
private final String CATEGORY= toString();
private IPositionUpdater fUpdater= new ExclusivePositionUpdater(CATEGORY);
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);
LinkedPositionGroup group= new LinkedPositionGroup();
group.createPosition(document, offset + 1, 0);
LinkedEnvironment env= new LinkedEnvironment();
env.addLinkedListener(this);
env.addGroup(group);
env.forceInstall();
level.fOffset= offset;
level.fLength= 2;
// set up position tracking for our magic peers
if (fBracketLevelStack.size() == 1) {
document.addPositionCategory(CATEGORY);
document.addPositionUpdater(fUpdater);
}
level.fFirstPosition= new Position(offset, 1);
level.fSecondPosition= new Position(offset + 1, 1);
document.addPosition(CATEGORY, level.fFirstPosition);
document.addPosition(CATEGORY, level.fSecondPosition);
level.fEditor= new LinkedUIControl(env, sourceViewer);
level.fEditor.setExitPolicy(new ExitPolicy(closingCharacter, getEscapeCharacter(closingCharacter), fBracketLevelStack));
level.fEditor.setExitPosition(sourceViewer, offset + 2, 0, Integer.MAX_VALUE);
level.fEditor.setCyclingMode(LinkedUIControl.CYCLE_NEVER);
level.fEditor.enter();
IRegion newSelection= level.fEditor.getSelectedRegion();
sourceViewer.setSelectedRange(newSelection.getOffset(), newSelection.getLength());
event.doit= false;
} catch (BadLocationException e) {
JavaPlugin.log(e);
} catch (BadPositionCategoryException e) {
JavaPlugin.log(e);
}
break;
}
}
/*
* @see org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment.ILinkedListener#left(org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment, int)
*/
public void left(LinkedEnvironment environment, int flags) {
final BracketLevel level= (BracketLevel) fBracketLevelStack.pop();
if (flags != ILinkedListener.EXTERNAL_MODIFICATION)
return;
// remove brackets
final ISourceViewer sourceViewer= getSourceViewer();
final IDocument document= sourceViewer.getDocument();
if (document instanceof IDocumentExtension) {
IDocumentExtension extension= (IDocumentExtension) document;
extension.registerPostNotificationReplace(null, new IDocumentExtension.IReplace() {
public void perform(IDocument d, IDocumentListener owner) {
if ((level.fFirstPosition.isDeleted || level.fFirstPosition.length == 0) && !level.fSecondPosition.isDeleted && level.fSecondPosition.offset == level.fFirstPosition.offset) {
try {
document.replace(level.fSecondPosition.offset, level.fSecondPosition.length, null);
} catch (BadLocationException e) {
}
}
if (fBracketLevelStack.size() == 0) {
document.removePositionUpdater(fUpdater);
try {
document.removePositionCategory(CATEGORY);
} catch (BadPositionCategoryException e) {
}
}
}
});
}
}
/*
* @see org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment.ILinkedListener#suspend(org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment)
*/
public void suspend(LinkedEnvironment environment) {
}
/*
* @see org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment.ILinkedListener#resume(org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment, int)
*/
public void resume(LinkedEnvironment environment, int flags) {
}
}
/** 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(), "ContentAssistCompletePrefix.", this, CONTENTASSIST_COMPLETE_PREFIX); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.CONTENT_ASSIST_COMPLETE_PREFIX);
setAction("ContentAssistCompletePrefix", action); //$NON-NLS-1$
markAsStateDependentAction("ContentAssistCompletePrefix", 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 org.eclipse.jdt.internal.ui.javaeditor.JavaEditor#getInputElement()
*/
protected IJavaElement getInputJavaElement() {
return JavaPlugin.getDefault().getWorkingCopyManager().getWorkingCopy(getEditorInput());
}
/*
* @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 org.eclipse.ui.texteditor.AbstractTextEditor#performSave(boolean, org.eclipse.core.runtime.IProgressMonitor)
*/
protected void performSave(boolean overwrite, IProgressMonitor progressMonitor) {
IDocumentProvider p= getDocumentProvider();
if (p instanceof ICompilationUnitDocumentProvider) {
ICompilationUnitDocumentProvider cp= (ICompilationUnitDocumentProvider) p;
cp.setSavePolicy(fSavePolicy);
}
try {
super.performSave(overwrite, 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) {
performSave(false, progressMonitor);
}
} else
performSave(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;
}
IWorkspaceRoot workspaceRoot= ResourcesPlugin.getWorkspace().getRoot();
IFile file= workspaceRoot.getFile(filePath);
final IEditorInput newInput= new FileEditorInput(file);
boolean success= false;
try {
provider.aboutToChange(newInput);
getDocumentProvider().saveDocument(progressMonitor, newInput, getDocumentProvider().getDocument(getEditorInput()), true);
success= true;
} catch (CoreException x) {
ErrorDialog.openError(shell, JavaEditorMessages.getString("CompilationUnitEditor.error.saving.title2"), JavaEditorMessages.getString("CompilationUnitEditor.error.saving.message2"), x.getStatus()); //$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);
}
}
|
49,869 |
Bug 49869 NPE showing Type Hierarchies history after layout change
|
M6 - I retrieve the org.eclipse.swt project from cvs, though this should happen with any java project - select the project in the Package Explorer and press F4 to open a hierarchy view on it - drop down the hierarchy view's Previous Type Hierarchies tool item, it will show 1+ item(s), good - drop down the hierarchy view's dropdown (ie.- the down-pointing triangle in the toolbar) and select Layout -> Horizontal View Orientation - now try to drop down the Previous Type Hierarchies tool item and the attached exception will occur
|
resolved fixed
|
65b4d52
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-14T09:56:15Z | 2004-01-12T17:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/HistoryDropDownAction.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.typehierarchy;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.ActionContributionItem;
import org.eclipse.jface.action.IMenuCreator;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
public class HistoryDropDownAction extends Action implements IMenuCreator {
public static final int RESULTS_IN_DROP_DOWN= 10;
private TypeHierarchyViewPart fHierarchyView;
private Menu fMenu;
public HistoryDropDownAction(TypeHierarchyViewPart view) {
fHierarchyView= view;
fMenu= null;
setToolTipText(TypeHierarchyMessages.getString("HistoryDropDownAction.tooltip")); //$NON-NLS-1$
JavaPluginImages.setLocalImageDescriptors(this, "history_list.gif"); //$NON-NLS-1$
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.TYPEHIERARCHY_HISTORY_ACTION);
setMenuCreator(this);
}
public void dispose() {
fHierarchyView= null;
if (fMenu != null) {
fMenu.dispose();
fMenu= null;
}
}
public Menu getMenu(Menu parent) {
return null;
}
public Menu getMenu(Control parent) {
if (fMenu != null) {
fMenu.dispose();
}
fMenu= new Menu(parent);
IJavaElement[] elements= fHierarchyView.getHistoryEntries();
boolean checked= addEntries(fMenu, elements);
if (elements.length > RESULTS_IN_DROP_DOWN) {
new MenuItem(fMenu, SWT.SEPARATOR);
Action others= new HistoryListAction(fHierarchyView);
others.setChecked(checked);
addActionToMenu(fMenu, others);
}
return fMenu;
}
private boolean addEntries(Menu menu, IJavaElement[] elements) {
boolean checked= false;
int min= Math.min(elements.length, RESULTS_IN_DROP_DOWN);
for (int i= 0; i < min; i++) {
HistoryAction action= new HistoryAction(fHierarchyView, elements[i]);
action.setChecked(elements[i].equals(fHierarchyView.getInputElement()));
checked= checked || action.isChecked();
addActionToMenu(menu, action);
}
return checked;
}
protected void addActionToMenu(Menu parent, Action action) {
ActionContributionItem item= new ActionContributionItem(action);
item.fill(parent, -1);
}
public void run() {
(new HistoryListAction(fHierarchyView)).run();
}
}
|
49,840 |
Bug 49840 refactoring "Convert local variable to field" is buggy for arrays [refactoring]
|
When refactoring the code below to "Convert local variable to field", the type of the variable is not preserved. The type of the field is int, NOT array of int as expected. <my code> void someMethod(){ int someArray[]; } </my code>
|
resolved fixed
|
5dd25e4
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-14T10:42:58Z | 2004-01-12T09:33:20Z |
org.eclipse.jdt.ui.tests.refactoring/resources/PromoteTempToField/canPromote/A_test19_in.java
| |
49,840 |
Bug 49840 refactoring "Convert local variable to field" is buggy for arrays [refactoring]
|
When refactoring the code below to "Convert local variable to field", the type of the variable is not preserved. The type of the field is int, NOT array of int as expected. <my code> void someMethod(){ int someArray[]; } </my code>
|
resolved fixed
|
5dd25e4
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-14T10:42:58Z | 2004-01-12T09:33:20Z |
org.eclipse.jdt.ui.tests.refactoring/resources/PromoteTempToField/canPromote/A_test19_out.java
| |
49,840 |
Bug 49840 refactoring "Convert local variable to field" is buggy for arrays [refactoring]
|
When refactoring the code below to "Convert local variable to field", the type of the variable is not preserved. The type of the field is int, NOT array of int as expected. <my code> void someMethod(){ int someArray[]; } </my code>
|
resolved fixed
|
5dd25e4
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-14T10:42:58Z | 2004-01-12T09:33:20Z |
org.eclipse.jdt.ui.tests.refactoring/resources/PromoteTempToField/canPromote/A_test20_in.java
| |
49,840 |
Bug 49840 refactoring "Convert local variable to field" is buggy for arrays [refactoring]
|
When refactoring the code below to "Convert local variable to field", the type of the variable is not preserved. The type of the field is int, NOT array of int as expected. <my code> void someMethod(){ int someArray[]; } </my code>
|
resolved fixed
|
5dd25e4
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-14T10:42:58Z | 2004-01-12T09:33:20Z |
org.eclipse.jdt.ui.tests.refactoring/resources/PromoteTempToField/canPromote/A_test20_out.java
| |
49,840 |
Bug 49840 refactoring "Convert local variable to field" is buggy for arrays [refactoring]
|
When refactoring the code below to "Convert local variable to field", the type of the variable is not preserved. The type of the field is int, NOT array of int as expected. <my code> void someMethod(){ int someArray[]; } </my code>
|
resolved fixed
|
5dd25e4
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-14T10:42:58Z | 2004-01-12T09:33:20Z |
org.eclipse.jdt.ui.tests.refactoring/test
| |
49,840 |
Bug 49840 refactoring "Convert local variable to field" is buggy for arrays [refactoring]
|
When refactoring the code below to "Convert local variable to field", the type of the variable is not preserved. The type of the field is int, NOT array of int as expected. <my code> void someMethod(){ int someArray[]; } </my code>
|
resolved fixed
|
5dd25e4
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-14T10:42:58Z | 2004-01-12T09:33:20Z |
cases/org/eclipse/jdt/ui/tests/refactoring/PromoteTempToFieldTests.java
| |
49,840 |
Bug 49840 refactoring "Convert local variable to field" is buggy for arrays [refactoring]
|
When refactoring the code below to "Convert local variable to field", the type of the variable is not preserved. The type of the field is int, NOT array of int as expected. <my code> void someMethod(){ int someArray[]; } </my code>
|
resolved fixed
|
5dd25e4
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-14T10:42:58Z | 2004-01-12T09:33:20Z |
org.eclipse.jdt.ui/core
| |
49,840 |
Bug 49840 refactoring "Convert local variable to field" is buggy for arrays [refactoring]
|
When refactoring the code below to "Convert local variable to field", the type of the variable is not preserved. The type of the field is int, NOT array of int as expected. <my code> void someMethod(){ int someArray[]; } </my code>
|
resolved fixed
|
5dd25e4
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-14T10:42:58Z | 2004-01-12T09:33:20Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/PromoteTempToFieldRefactoring.java
| |
44,535 |
Bug 44535 [misc] Wrong message displayed while opening a class file outside classapth
| null |
verified fixed
|
9a60ab1
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-14T15:24:24Z | 2003-10-09T11:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/ResourceLocator.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;
import org.eclipse.core.resources.IResource;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.JavaModelException;
/**
* This class locates different resources
* which are related to an object
*/
public class ResourceLocator implements IResourceLocator {
public IResource getUnderlyingResource(Object element) throws JavaModelException {
if (element instanceof IJavaElement)
return ((IJavaElement) element).getUnderlyingResource();
else
return null;
}
public IResource getCorrespondingResource(Object element) throws JavaModelException {
if (element instanceof IJavaElement)
return ((IJavaElement) element).getUnderlyingResource();
else
return null;
}
public IResource getContainingResource(Object element) throws JavaModelException {
IResource resource= null;
if (element instanceof IResource)
resource= (IResource) element;
if (element instanceof IJavaElement) {
resource= ((IJavaElement) element).getUnderlyingResource();
if (resource == null)
resource= ((IJavaElement) element).getJavaProject().getProject();
}
return resource;
}
}
|
44,535 |
Bug 44535 [misc] Wrong message displayed while opening a class file outside classapth
| null |
verified fixed
|
9a60ab1
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-14T15:24:24Z | 2003-10-09T11:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/ClassFileEditor.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.javaeditor;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.custom.StackLayout;
import org.eclipse.swt.custom.StyledText;
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.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
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.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.ScrollBar;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.window.Window;
import org.eclipse.jface.text.IWidgetTokenKeeper;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.IVerticalRuler;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.IClasspathContainer;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaModelStatusConstants;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.ToolFactory;
import org.eclipse.jdt.core.util.IClassFileDisassembler;
import org.eclipse.jdt.core.util.IClassFileReader;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaUIStatus;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.wizards.buildpaths.SourceAttachmentDialog;
/**
* Java specific text editor.
*/
public class ClassFileEditor extends JavaEditor implements ClassFileDocumentProvider.InputChangeListener {
/** The horizontal scroll increment. */
private static final int HORIZONTAL_SCROLL_INCREMENT= 10;
/** The vertical scroll increment. */
private static final int VERTICAL_SCROLL_INCREMENT= 10;
/**
* A form to attach source to a class file.
*/
private class SourceAttachmentForm implements IPropertyChangeListener {
private final IClassFile fFile;
private ScrolledComposite fScrolledComposite;
private Color fBackgroundColor;
private Color fForegroundColor;
private Color fSeparatorColor;
private List fBannerLabels= new ArrayList();
private List fHeaderLabels= new ArrayList();
private Font fFont;
/**
* Creates a source attachment form for a class file.
*/
public SourceAttachmentForm(IClassFile file) {
fFile= file;
}
/**
* Returns the package fragment root of this file.
*/
private IPackageFragmentRoot getPackageFragmentRoot(IClassFile file) {
IJavaElement element= file.getParent();
while (element != null && element.getElementType() != IJavaElement.PACKAGE_FRAGMENT_ROOT)
element= element.getParent();
return (IPackageFragmentRoot) element;
}
/**
* Creates the control of the source attachment form.
*/
public Control createControl(Composite parent) {
Display display= parent.getDisplay();
fBackgroundColor= display.getSystemColor(SWT.COLOR_LIST_BACKGROUND);
fForegroundColor= display.getSystemColor(SWT.COLOR_LIST_FOREGROUND);
fSeparatorColor= new Color(display, 152, 170, 203);
JFaceResources.getFontRegistry().addListener(this);
fScrolledComposite= new ScrolledComposite(parent, SWT.H_SCROLL | SWT.V_SCROLL);
fScrolledComposite.setAlwaysShowScrollBars(false);
fScrolledComposite.setExpandHorizontal(true);
fScrolledComposite.setExpandVertical(true);
fScrolledComposite.addDisposeListener(new DisposeListener() {
public void widgetDisposed(DisposeEvent e) {
JFaceResources.getFontRegistry().removeListener(SourceAttachmentForm.this);
fScrolledComposite= null;
fSeparatorColor.dispose();
fSeparatorColor= null;
fBannerLabels.clear();
fHeaderLabels.clear();
if (fFont != null) {
fFont.dispose();
fFont= null;
}
}
});
fScrolledComposite.addControlListener(new ControlListener() {
public void controlMoved(ControlEvent e) {}
public void controlResized(ControlEvent e) {
Rectangle clientArea = fScrolledComposite.getClientArea();
ScrollBar verticalBar= fScrolledComposite.getVerticalBar();
verticalBar.setIncrement(VERTICAL_SCROLL_INCREMENT);
verticalBar.setPageIncrement(clientArea.height - verticalBar.getIncrement());
ScrollBar horizontalBar= fScrolledComposite.getHorizontalBar();
horizontalBar.setIncrement(HORIZONTAL_SCROLL_INCREMENT);
horizontalBar.setPageIncrement(clientArea.width - horizontalBar.getIncrement());
}
});
Composite composite= createComposite(fScrolledComposite);
composite.setLayout(new GridLayout());
createTitleLabel(composite, JavaEditorMessages.getString("SourceAttachmentForm.title")); //$NON-NLS-1$
createLabel(composite, null);
createLabel(composite, null);
createHeadingLabel(composite, JavaEditorMessages.getString("SourceAttachmentForm.heading")); //$NON-NLS-1$
Composite separator= createCompositeSeparator(composite);
GridData data= new GridData(GridData.FILL_HORIZONTAL);
data.heightHint= 2;
separator.setLayoutData(data);
try {
IPackageFragmentRoot root= getPackageFragmentRoot(fFile);
if (root != null) {
createSourceAttachmentControls(composite, root);
}
} catch (JavaModelException e) {
String title= JavaEditorMessages.getString("SourceAttachmentForm.error.title"); //$NON-NLS-1$
String message= JavaEditorMessages.getString("SourceAttachmentForm.error.message"); //$NON-NLS-1$
ExceptionHandler.handle(e, fScrolledComposite.getShell(), title, message);
}
separator= createCompositeSeparator(composite);
data= new GridData(GridData.FILL_HORIZONTAL);
data.heightHint= 2;
separator.setLayoutData(data);
StyledText styledText= createCodeView(composite);
data= new GridData(GridData.FILL_BOTH);
styledText.setLayoutData(data);
updateCodeView(styledText, fFile);
fScrolledComposite.setContent(composite);
fScrolledComposite.setMinSize(composite.computeSize(SWT.DEFAULT, SWT.DEFAULT));
return fScrolledComposite;
}
private void createSourceAttachmentControls(Composite composite, IPackageFragmentRoot root) throws JavaModelException {
IClasspathEntry entry= root.getRawClasspathEntry();
IPath containerPath= null;
IJavaProject jproject= root.getJavaProject();
if (entry == null || !root.isArchive()) {
createLabel(composite, JavaEditorMessages.getFormattedString("SourceAttachmentForm.message.noSource", fFile.getElementName())); //$NON-NLS-1$
return;
}
if (entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
containerPath= entry.getPath();
IClasspathEntry entry2= SourceAttachmentDialog.getClasspathEntryToEdit(jproject, containerPath, root.getPath());
if (entry2 == null) {
IClasspathContainer container= JavaCore.getClasspathContainer(entry.getPath(), root.getJavaProject());
String containerName= container == null ? entry.getPath().toString() : container.getDescription();
createLabel(composite, JavaEditorMessages.getFormattedString("SourceAttachmentForm.message.containerEntry", containerName)); //$NON-NLS-1$
return;
}
entry= entry2;
}
Button button;
IPath path= entry.getSourceAttachmentPath();
if (path == null || path.isEmpty()) {
createLabel(composite, JavaEditorMessages.getFormattedString("SourceAttachmentForm.message.noSourceAttachment", root.getElementName())); //$NON-NLS-1$
createLabel(composite, JavaEditorMessages.getString("SourceAttachmentForm.message.pressButtonToAttach")); //$NON-NLS-1$
createLabel(composite, null);
button= createButton(composite, JavaEditorMessages.getString("SourceAttachmentForm.button.attachSource")); //$NON-NLS-1$
} else {
createLabel(composite, JavaEditorMessages.getFormattedString("SourceAttachmentForm.message.noSourceInAttachment", fFile.getElementName())); //$NON-NLS-1$
createLabel(composite, JavaEditorMessages.getString("SourceAttachmentForm.message.pressButtonToChange")); //$NON-NLS-1$
createLabel(composite, null);
button= createButton(composite, JavaEditorMessages.getString("SourceAttachmentForm.button.changeAttachedSource")); //$NON-NLS-1$
}
button.addSelectionListener(getButtonListener(entry, containerPath, jproject));
}
private SelectionListener getButtonListener(final IClasspathEntry entry, final IPath containerPath, final IJavaProject jproject) {
return new SelectionListener() {
public void widgetSelected(SelectionEvent event) {
try {
SourceAttachmentDialog dialog= new SourceAttachmentDialog(fScrolledComposite.getShell(), entry, containerPath, jproject, true);
if (dialog.open() == Window.OK)
verifyInput(getEditorInput());
} catch (CoreException e) {
String title= JavaEditorMessages.getString("SourceAttachmentForm.error.title"); //$NON-NLS-1$
String message= JavaEditorMessages.getString("SourceAttachmentForm.error.message"); //$NON-NLS-1$
ExceptionHandler.handle(e, fScrolledComposite.getShell(), title, message);
}
}
public void widgetDefaultSelected(SelectionEvent e) {}
};
}
/*
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
for (Iterator iterator = fBannerLabels.iterator(); iterator.hasNext();) {
Label label = (Label) iterator.next();
label.setFont(JFaceResources.getBannerFont());
}
for (Iterator iterator = fHeaderLabels.iterator(); iterator.hasNext();) {
Label label = (Label) iterator.next();
label.setFont(JFaceResources.getHeaderFont());
}
Control control= fScrolledComposite.getContent();
fScrolledComposite.setMinSize(control.computeSize(SWT.DEFAULT, SWT.DEFAULT));
fScrolledComposite.setContent(control);
fScrolledComposite.layout(true);
fScrolledComposite.redraw();
}
// --- copied from org.eclipse.update.ui.forms.internal.FormWidgetFactory
private Composite createComposite(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
composite.setBackground(fBackgroundColor);
// composite.addMouseListener(new MouseAdapter() {
// public void mousePressed(MouseEvent e) {
// ((Control) e.widget).setFocus();
// }
// });
return composite;
}
private Composite createCompositeSeparator(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
composite.setBackground(fSeparatorColor);
return composite;
}
private StyledText createCodeView(Composite parent) {
int styles= SWT.MULTI | SWT.FULL_SELECTION;
StyledText styledText= new StyledText(parent, styles);
styledText.setBackground(fBackgroundColor);
styledText.setForeground(fForegroundColor);
styledText.setEditable(false);
return styledText;
}
private Label createLabel(Composite parent, String text) {
Label label = new Label(parent, SWT.NONE);
if (text != null)
label.setText(text);
label.setBackground(fBackgroundColor);
label.setForeground(fForegroundColor);
return label;
}
private Label createTitleLabel(Composite parent, String text) {
Label label = new Label(parent, SWT.NONE);
if (text != null)
label.setText(text);
label.setBackground(fBackgroundColor);
label.setForeground(fForegroundColor);
label.setFont(JFaceResources.getHeaderFont());
fHeaderLabels.add(label);
return label;
}
private Label createHeadingLabel(Composite parent, String text) {
Label label = new Label(parent, SWT.NONE);
if (text != null)
label.setText(text);
label.setBackground(fBackgroundColor);
label.setForeground(fForegroundColor);
label.setFont(JFaceResources.getBannerFont());
fBannerLabels.add(label);
return label;
}
private Button createButton(Composite parent, String text) {
Button button = new Button(parent, SWT.FLAT);
button.setBackground(fBackgroundColor);
button.setForeground(fForegroundColor);
if (text != null)
button.setText(text);
// button.addFocusListener(visibilityHandler);
return button;
}
private void updateCodeView(StyledText styledText, IClassFile classFile) {
String content= null;
int flags= IClassFileReader.FIELD_INFOS | IClassFileReader.METHOD_INFOS | IClassFileReader.SUPER_INTERFACES;
IClassFileReader classFileReader= ToolFactory.createDefaultClassFileReader(classFile, flags);
if (classFileReader != null) {
IClassFileDisassembler disassembler= ToolFactory.createDefaultClassFileDisassembler();
content= disassembler.disassemble(classFileReader, "\n"); //$NON-NLS-1$
}
styledText.setText(content == null ? "" : content); //$NON-NLS-1$
}
}
/**
* Updater that takes care of minimizing changes of the editor input.
*/
private class InputUpdater implements Runnable {
/** Has the runnable already been posted? */
private boolean fPosted= false;
/** Editor input */
private IClassFileEditorInput fClassFileEditorInput;
public InputUpdater() {
}
/*
* @see Runnable#run()
*/
public void run() {
IClassFileEditorInput input;
synchronized (this) {
input= fClassFileEditorInput;
}
try {
if (getSourceViewer() != null)
setInput(input);
} finally {
synchronized (this) {
fPosted= false;
}
}
}
/**
* Posts this runnable into the event queue if not already there.
*
* @param input the input to be set when executed
*/
public void post(IClassFileEditorInput input) {
synchronized(this) {
if (fPosted) {
if (input != null && input.equals(fClassFileEditorInput))
fClassFileEditorInput= input;
return;
}
}
if (input != null && input.equals(getEditorInput())) {
ISourceViewer viewer= getSourceViewer();
if (viewer != null) {
StyledText textWidget= viewer.getTextWidget();
if (textWidget != null && !textWidget.isDisposed()) {
synchronized (this) {
fPosted= true;
fClassFileEditorInput= input;
}
textWidget.getDisplay().asyncExec(this);
}
}
}
}
}
private StackLayout fStackLayout;
private Composite fParent;
private Composite fViewerComposite;
private Control fSourceAttachmentForm;
private InputUpdater fInputUpdater= new InputUpdater();
/**
* Default constructor.
*/
public ClassFileEditor() {
super();
setDocumentProvider(JavaPlugin.getDefault().getClassFileDocumentProvider());
setEditorContextMenuId("#ClassFileEditorContext"); //$NON-NLS-1$
setRulerContextMenuId("#ClassFileRulerContext"); //$NON-NLS-1$
setOutlinerContextMenuId("#ClassFileOutlinerContext"); //$NON-NLS-1$
// don't set help contextId, we install our own help context
}
/*
* @see AbstractTextEditor#createActions()
*/
protected void createActions() {
super.createActions();
setAction(ITextEditorActionConstants.SAVE, null);
setAction(ITextEditorActionConstants.REVERT_TO_SAVED, null);
/*
* 1GF82PL: ITPJUI:ALL - Need to be able to add bookmark to classfile
*
* // replace default action with class file specific ones
*
* setAction(ITextEditorActionConstants.BOOKMARK, new AddClassFileMarkerAction("AddBookmark.", this, IMarker.BOOKMARK, true)); //$NON-NLS-1$
* setAction(ITextEditorActionConstants.ADD_TASK, new AddClassFileMarkerAction("AddTask.", this, IMarker.TASK, false)); //$NON-NLS-1$
* setAction(ITextEditorActionConstants.RULER_MANAGE_BOOKMARKS, new ClassFileMarkerRulerAction("ManageBookmarks.", getVerticalRuler(), this, IMarker.BOOKMARK, true)); //$NON-NLS-1$
* setAction(ITextEditorActionConstants.RULER_MANAGE_TASKS, new ClassFileMarkerRulerAction("ManageTasks.", getVerticalRuler(), this, IMarker.TASK, true)); //$NON-NLS-1$
*/
}
/*
* @see JavaEditor#getElementAt(int)
*/
protected IJavaElement getElementAt(int offset) {
if (getEditorInput() instanceof IClassFileEditorInput) {
try {
IClassFileEditorInput input= (IClassFileEditorInput) getEditorInput();
return input.getClassFile().getElementAt(offset);
} catch (JavaModelException x) {
}
}
return null;
}
/*
* @see JavaEditor#getCorrespondingElement(IJavaElement)
*/
protected IJavaElement getCorrespondingElement(IJavaElement element) {
if (getEditorInput() instanceof IClassFileEditorInput) {
IClassFileEditorInput input= (IClassFileEditorInput) getEditorInput();
IJavaElement parent= element.getAncestor(IJavaElement.CLASS_FILE);
if (input.getClassFile().equals(parent))
return element;
}
return null;
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor#getInputElement()
*/
protected IJavaElement getInputJavaElement() {
return ((IClassFileEditorInput)getEditorInput()).getClassFile();
}
/*
* @see IEditorPart#saveState(IMemento)
*/
public void saveState(IMemento memento) {
}
/*
* @see JavaEditor#setOutlinePageInput(JavaOutlinePage, IEditorInput)
*/
protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input) {
if (page != null && input instanceof IClassFileEditorInput) {
IClassFileEditorInput cfi= (IClassFileEditorInput) input;
page.setInput(cfi.getClassFile());
}
}
/*
* 1GEPKT5: ITPJUI:Linux - Source in editor for external classes is editable
* Removed methods isSaveOnClosedNeeded and isDirty.
* Added method isEditable.
*/
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#isEditable()
*/
public boolean isEditable() {
return false;
}
/**
* Translates the given editor input into an <code>ExternalClassFileEditorInput</code>
* if it is a file editor input representing an external class file.
*
* @param input the editor input to be transformed if necessary
* @return the transformed editor input
*/
protected IEditorInput transformEditorInput(IEditorInput input) {
if (input instanceof IFileEditorInput) {
IFile file= ((IFileEditorInput) input).getFile();
IClassFileEditorInput classFileInput= new ExternalClassFileEditorInput(file);
if (classFileInput.getClassFile() != null)
input= classFileInput;
}
return input;
}
/*
* @see AbstractTextEditor#doSetInput(IEditorInput)
*/
protected void doSetInput(IEditorInput input) throws CoreException {
input= transformEditorInput(input);
if (!(input instanceof IClassFileEditorInput))
throw new CoreException(JavaUIStatus.createError(
IJavaModelStatusConstants.INVALID_RESOURCE_TYPE,
JavaEditorMessages.getString("ClassFileEditor.error.invalid_input_message"), //$NON-NLS-1$
null)); //$NON-NLS-1$
JavaModelException e= probeInputForSource(input);
if (e != null) {
IClassFileEditorInput classFileEditorInput= (IClassFileEditorInput) input;
IClassFile file= classFileEditorInput.getClassFile();
IJavaProject javaProject= file.getJavaProject();
if (!javaProject.exists() || !javaProject.isOnClasspath(file)) {
throw new CoreException(JavaUIStatus.createError(
IJavaModelStatusConstants.INVALID_RESOURCE,
JavaEditorMessages.getString("ClassFileEditor.error.classfile_not_on_classpath"), //$NON-NLS-1$
null)); //$NON-NLS-1$
} else {
throw e;
}
}
IDocumentProvider documentProvider= getDocumentProvider();
if (documentProvider instanceof ClassFileDocumentProvider)
((ClassFileDocumentProvider) documentProvider).removeInputChangeListener(this);
super.doSetInput(input);
documentProvider= getDocumentProvider();
if (documentProvider instanceof ClassFileDocumentProvider)
((ClassFileDocumentProvider) documentProvider).addInputChangeListener(this);
verifyInput(getEditorInput());
}
/*
* @see IWorkbenchPart#createPartControl(Composite)
*/
public void createPartControl(Composite parent) {
fParent= new Composite(parent, SWT.NONE);
fStackLayout= new StackLayout();
fParent.setLayout(fStackLayout);
fViewerComposite= new Composite(fParent, SWT.NONE);
fViewerComposite.setLayout(new FillLayout());
super.createPartControl(fViewerComposite);
fStackLayout.topControl= fViewerComposite;
fParent.layout();
try {
verifyInput(getEditorInput());
} catch (CoreException e) {
String title= JavaEditorMessages.getString("ClassFileEditor.error.title"); //$NON-NLS-1$
String message= JavaEditorMessages.getString("ClassFileEditor.error.message"); //$NON-NLS-1$
ExceptionHandler.handle(e, fParent.getShell(), title, message);
}
}
private JavaModelException probeInputForSource(IEditorInput input) {
if (input == null)
return null;
IClassFileEditorInput classFileEditorInput= (IClassFileEditorInput) input;
IClassFile file= classFileEditorInput.getClassFile();
try {
file.getSourceRange();
} catch (JavaModelException e) {
return e;
}
return null;
}
/**
* Checks if the class file input has no source attached. If so, a source attachment form is shown.
*/
private void verifyInput(IEditorInput input) throws CoreException {
if (fParent == null || input == null)
return;
IClassFileEditorInput classFileEditorInput= (IClassFileEditorInput) input;
IClassFile file= classFileEditorInput.getClassFile();
// show source attachment form if no source found
if (file.getSourceRange() == null) {
// dispose old source attachment form
if (fSourceAttachmentForm != null)
fSourceAttachmentForm.dispose();
SourceAttachmentForm form= new SourceAttachmentForm(file);
fSourceAttachmentForm= form.createControl(fParent);
fStackLayout.topControl= fSourceAttachmentForm;
fParent.layout();
// show source viewer
} else {
if (fSourceAttachmentForm != null) {
fSourceAttachmentForm.dispose();
fSourceAttachmentForm= null;
fStackLayout.topControl= fViewerComposite;
fParent.layout();
}
}
}
/*
* @see ClassFileDocumentProvider.InputChangeListener#inputChanged(IClassFileEditorInput)
*/
public void inputChanged(IClassFileEditorInput input) {
fInputUpdater.post(input);
}
/*
* @see JavaEditor#createJavaSourceViewer(Composite, IVerticalRuler, int)
*/
protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler ruler, int styles) {
return new JavaSourceViewer(parent, ruler, null, false, styles) {
public boolean requestWidgetToken(IWidgetTokenKeeper requester) {
if (WorkbenchHelp.isContextHelpDisplayed())
return false;
return super.requestWidgetToken(requester);
}
public boolean requestWidgetToken(IWidgetTokenKeeper requester, int priority) {
if (WorkbenchHelp.isContextHelpDisplayed())
return false;
return super.requestWidgetToken(requester, priority);
}
};
}
/*
* @see org.eclipse.ui.IWorkbenchPart#dispose()
*/
public void dispose() {
// http://bugs.eclipse.org/bugs/show_bug.cgi?id=18510
IDocumentProvider documentProvider= getDocumentProvider();
if (documentProvider instanceof ClassFileDocumentProvider)
((ClassFileDocumentProvider) documentProvider).removeInputChangeListener(this);
super.dispose();
}
/*
* @see org.eclipse.ui.IWorkbenchPart#setFocus()
*/
public void setFocus() {
super.setFocus();
if (fSourceAttachmentForm != null && !fSourceAttachmentForm.isDisposed())
fSourceAttachmentForm.setFocus();
}
}
|
50,000 |
Bug 50000 PostSelectionWithAST causes IllegalArgumentException
|
I20040113 Opening a class file from a JAR which has no source causes IAE. !ENTRY org.eclipse.core.runtime 4 2 Jan 14, 2004 17:43:55.905 !MESSAGE An internal error occurred during: "Java AST creation". !STACK 0 java.lang.IllegalArgumentException at org.eclipse.jdt.core.dom.AST.parseCompilationUnit(AST.java:528) at org.eclipse.jdt.core.dom.AST.parseCompilationUnit(AST.java:439) at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.computeAST(SelectionListenerWithASTManager.java:122) at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$PartListenerGroup.calculateASTandInform(SelectionListenerWithASTManager.java:133) at org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager$1.run(SelectionListenerWithASTManager.java:93) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:62)
|
resolved fixed
|
e223827
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-14T17:07:55Z | 2004-01-14T17:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/viewsupport/SelectionListenerWithASTManager.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 java.util.HashMap;
import java.util.Map;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.util.ListenerList;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.ISelectionService;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.internal.ui.JavaUIMessages;
/**
* Infrastructure to share an AST for editor post selection listeners.
*/
public class SelectionListenerWithASTManager {
private static SelectionListenerWithASTManager fgDefault;
/**
* @return Returns the default manager instance.
*/
public static SelectionListenerWithASTManager getDefault() {
if (fgDefault == null) {
fgDefault= new SelectionListenerWithASTManager();
}
return fgDefault;
}
private static class PartListenerGroup {
private IEditorPart fPart;
private Job fCurrentJob;
private ListenerList fAstListeners;
public PartListenerGroup(IEditorPart part) {
fPart= part;
fCurrentJob= null;
fAstListeners= new ListenerList();
}
public boolean isEmpty() {
return fAstListeners.isEmpty();
}
public void install(ISelectionListenerWithAST listener) {
fAstListeners.add(listener);
}
public void uninstall(ISelectionListenerWithAST listener) {
fAstListeners.remove(listener);
}
public void fireSelectionChanged(final ITextSelection selection) {
if (fCurrentJob != null) {
fCurrentJob.cancel();
}
fCurrentJob= new Job(JavaUIMessages.getString("SelectionListenerWithASTManager.job.title")) { //$NON-NLS-1$
public IStatus run(IProgressMonitor monitor) {
if (monitor == null) {
monitor= new NullProgressMonitor();
}
synchronized (PartListenerGroup.this) {
return calculateASTandInform(selection, monitor);
}
}
};
fCurrentJob.setPriority(Job.DECORATE);
fCurrentJob.setSystem(true);
fCurrentJob.schedule();
}
private CompilationUnit computeAST(IProgressMonitor monitor) {
IEditorInput editorInput= fPart.getEditorInput();
if (editorInput != null) {
IJavaElement element= (IJavaElement) editorInput.getAdapter(IJavaElement.class);
if (element instanceof ICompilationUnit) {
ICompilationUnit cu= (ICompilationUnit) element;
char[] buffer= null;
synchronized (element) { // sychronize on cu to avoid conflict with reconciler: bug
if (!monitor.isCanceled()) {
try {
buffer= cu.getBuffer().getCharacters();
} catch (JavaModelException e) {
// ignore
}
}
}
if (buffer != null) {
return AST.parseCompilationUnit(buffer, cu.getElementName(), cu.getJavaProject());
}
} else if (element instanceof IClassFile) {
return AST.parseCompilationUnit((IClassFile) element, true);
}
}
return null;
}
protected IStatus calculateASTandInform(ITextSelection selection, IProgressMonitor monitor) {
if (monitor.isCanceled()) {
return Status.CANCEL_STATUS;
}
// create AST
CompilationUnit astRoot= computeAST(monitor);
if (astRoot != null && !monitor.isCanceled()) {
Object[] listeners= fAstListeners.getListeners();
for (int i= 0; i < listeners.length; i++) {
((ISelectionListenerWithAST) listeners[i]).selectionChanged(fPart, selection, astRoot);
if (monitor.isCanceled()) {
return Status.CANCEL_STATUS;
}
}
return Status.OK_STATUS;
}
return Status.CANCEL_STATUS;
}
}
private static class WorkbenchWindowListener implements ISelectionListener {
private ISelectionService fSelectionService;
private Map fPartListeners; // key: IEditorPart, value: PartListenerGroup
public WorkbenchWindowListener(ISelectionService service) {
fSelectionService= service;
fPartListeners= new HashMap();
}
public boolean isEmpty() {
return fPartListeners.isEmpty();
}
public void install(IEditorPart part, ISelectionListenerWithAST listener) {
if (fPartListeners.isEmpty()) {
fSelectionService.addPostSelectionListener(this);
}
PartListenerGroup listenerGroup= (PartListenerGroup) fPartListeners.get(part);
if (listenerGroup == null) {
listenerGroup= new PartListenerGroup(part);
fPartListeners.put(part, listenerGroup);
}
listenerGroup.install(listener);
}
public void uninstall(IEditorPart part, ISelectionListenerWithAST listener) {
PartListenerGroup listenerGroup= (PartListenerGroup) fPartListeners.get(part);
if (listenerGroup == null) {
return;
}
listenerGroup.uninstall(listener);
if (listenerGroup.isEmpty()) {
fPartListeners.remove(part);
if (fPartListeners.isEmpty()) {
fSelectionService.removePostSelectionListener(this);
}
}
}
/* (non-Javadoc)
* @see org.eclipse.ui.ISelectionListener#selectionChanged(org.eclipse.ui.IWorkbenchPart, org.eclipse.jface.viewers.ISelection)
*/
public void selectionChanged(IWorkbenchPart part, ISelection selection) {
if (part instanceof IEditorPart && selection instanceof ITextSelection) { // only editor parts are interesting
PartListenerGroup listenerGroup= (PartListenerGroup) fPartListeners.get(part);
if (listenerGroup != null) {
listenerGroup.fireSelectionChanged((ITextSelection) selection);
}
}
}
}
private Map fListenerGroups;
private SelectionListenerWithASTManager() {
fListenerGroups= new HashMap();
}
/**
* Registers a selection listener for the given editor part.
* @param part The editor part to listen to.
* @param listener The listener to register.
*/
public void addListener(IEditorPart part, ISelectionListenerWithAST listener) {
ISelectionService service= part.getSite().getWorkbenchWindow().getSelectionService();
WorkbenchWindowListener windowListener= (WorkbenchWindowListener) fListenerGroups.get(service);
if (windowListener == null) {
windowListener= new WorkbenchWindowListener(service);
fListenerGroups.put(service, windowListener);
}
windowListener.install(part, listener);
}
/**
* Unregisters a selection listener.
* @param part The editor part the listener was registered.
* @param listener The listener to unregister.
*/
public void removeListener(IEditorPart part, ISelectionListenerWithAST listener) {
ISelectionService service= part.getSite().getWorkbenchWindow().getSelectionService();
WorkbenchWindowListener windowListener= (WorkbenchWindowListener) fListenerGroups.get(service);
if (windowListener != null) {
windowListener.uninstall(part, listener);
if (windowListener.isEmpty()) {
fListenerGroups.remove(service);
}
}
}
/**
* Forces a selection changed event that is sent to all listeners registered to the given editor
* part. The event is sent from a background thread: this method call can return before the listeners
* are informed.
*/
public void forceSelectionChange(IEditorPart part, ITextSelection selection) {
ISelectionService service= part.getSite().getWorkbenchWindow().getSelectionService();
WorkbenchWindowListener windowListener= (WorkbenchWindowListener) fListenerGroups.get(service);
if (windowListener != null) {
windowListener.selectionChanged(part, selection);
}
}}
|
49,966 |
Bug 49966 Assertion failed while creating copy of compilation unit
|
CreateCopyOfCompilationUnitChange.createChangeManager passed a negative offset to the constructor of ReplaceEdit. This is reproducible with one specific compilation unit (a modified AbstractTextEditor, no errors, no warnings): - start eclipse - click on AbstractTextEditor in Package Explorer - Ctrl-C, Ctrl-V - confirm suggested new name with Enter -> Error dialog box with undo/abort buttons: "An exception has been caught while processing the change 'Create file:/test/src/test4/CopyOfAbstractTextEditor'. Reason: Assertion failed: " - and nothing more apart from the description of the buttons. From the log: 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.text.edits.TextEdit.<init>(TextEdit.java:137) at org.eclipse.text.edits.ReplaceEdit.<init>(ReplaceEdit.java:35) at org.eclipse.jdt.internal.corext.refactoring.reorg.CreateCopyOfCompilationUnitChange.createChangeManager(CreateCopyOfCompilationUnitChange.java:103) at org.eclipse.jdt.internal.corext.refactoring.reorg.CreateCopyOfCompilationUnitChange.getCopiedFileSource(CreateCopyOfCompilationUnitChange.java:81) at org.eclipse.jdt.internal.corext.refactoring.reorg.CreateCopyOfCompilationUnitChange.getOldFile(CreateCopyOfCompilationUnitChange.java:63) at org.eclipse.jdt.internal.corext.refactoring.nls.changes.CreateFileChange.perform(CreateFileChange.java:79) at org.eclipse.jdt.internal.corext.refactoring.CompositeChange.createUndoList(CompositeChange.java:122) at org.eclipse.jdt.internal.corext.refactoring.CompositeChange.perform(CompositeChange.java:149) at org.eclipse.jdt.internal.ui.refactoring.RefactoringExecutionHelper$1.run(RefactoringExecutionHelper.java:80) at org.eclipse.jdt.internal.core.BatchOperation.executeOperation(BatchOperation.java:34) at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:698) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1555) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1574) at org.eclipse.jdt.core.JavaCore.run(JavaCore.java:3129) at org.eclipse.jdt.internal.ui.refactoring.RefactoringExecutionHelper$Operation.run(RefactoringExecutionHelper.java:78) at org.eclipse.jface.operation.ModalContext.runInCurrentThread(ModalContext.java:302) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:252) at org.eclipse.jface.dialogs.ProgressMonitorDialog.run(ProgressMonitorDialog.java:394) at org.eclipse.jdt.internal.ui.refactoring.RefactoringExecutionHelper.perform(RefactoringExecutionHelper.java:130) at org.eclipse.jdt.internal.ui.refactoring.reorg.ReorgCopyStarter.run(ReorgCopyStarter.java:70) at org.eclipse.jdt.internal.ui.refactoring.reorg.PasteAction$JavaElementAndResourcePaster.paste(PasteAction.java:402) at org.eclipse.jdt.internal.ui.refactoring.reorg.PasteAction.run(PasteAction.java:189) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun(SelectionDispatchAction.java:212) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run(SelectionDispatchAction.java:188) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.ui.actions.RetargetAction.runWithEvent(RetargetAction.java:212) at org.eclipse.ui.internal.commands.ActionHandler.execute(ActionHandler.java:40) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.executeCommand(WorkbenchKeyboard.java:390) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.press(WorkbenchKeyboard.java:763) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.processKeyEvent(WorkbenchKeyboard.java:803) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.filterKeySequenceBindings(WorkbenchKeyboard.java:486) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.access$0(WorkbenchKeyboard.java:421) at org.eclipse.ui.internal.keys.WorkbenchKeyboard$1.handleEvent(WorkbenchKeyboard.java:215) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Display.filterEvent(Display.java:692) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:846) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:871) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:856) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1716) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1712) at org.eclipse.swt.widgets.Control.WM_CHAR(Control.java:3036) at org.eclipse.swt.widgets.Tree.WM_CHAR(Tree.java:1292) at org.eclipse.swt.widgets.Control.windowProc(Control.java:2939) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2836) at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:1369) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1990) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1506) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1482) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:246) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:47) at org.eclipse.core.internal.runtime.PlatformActivator$1.run(PlatformActivator.java:226) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:85) 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:279) at org.eclipse.core.launcher.Main.run(Main.java:742) at org.eclipse.core.launcher.Main.main(Main.java:581)
|
verified fixed
|
0abeada
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-14T17:11:21Z | 2004-01-14T11:33:20Z |
org.eclipse.jdt.ui/core
| |
49,966 |
Bug 49966 Assertion failed while creating copy of compilation unit
|
CreateCopyOfCompilationUnitChange.createChangeManager passed a negative offset to the constructor of ReplaceEdit. This is reproducible with one specific compilation unit (a modified AbstractTextEditor, no errors, no warnings): - start eclipse - click on AbstractTextEditor in Package Explorer - Ctrl-C, Ctrl-V - confirm suggested new name with Enter -> Error dialog box with undo/abort buttons: "An exception has been caught while processing the change 'Create file:/test/src/test4/CopyOfAbstractTextEditor'. Reason: Assertion failed: " - and nothing more apart from the description of the buttons. From the log: 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.text.edits.TextEdit.<init>(TextEdit.java:137) at org.eclipse.text.edits.ReplaceEdit.<init>(ReplaceEdit.java:35) at org.eclipse.jdt.internal.corext.refactoring.reorg.CreateCopyOfCompilationUnitChange.createChangeManager(CreateCopyOfCompilationUnitChange.java:103) at org.eclipse.jdt.internal.corext.refactoring.reorg.CreateCopyOfCompilationUnitChange.getCopiedFileSource(CreateCopyOfCompilationUnitChange.java:81) at org.eclipse.jdt.internal.corext.refactoring.reorg.CreateCopyOfCompilationUnitChange.getOldFile(CreateCopyOfCompilationUnitChange.java:63) at org.eclipse.jdt.internal.corext.refactoring.nls.changes.CreateFileChange.perform(CreateFileChange.java:79) at org.eclipse.jdt.internal.corext.refactoring.CompositeChange.createUndoList(CompositeChange.java:122) at org.eclipse.jdt.internal.corext.refactoring.CompositeChange.perform(CompositeChange.java:149) at org.eclipse.jdt.internal.ui.refactoring.RefactoringExecutionHelper$1.run(RefactoringExecutionHelper.java:80) at org.eclipse.jdt.internal.core.BatchOperation.executeOperation(BatchOperation.java:34) at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:698) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1555) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1574) at org.eclipse.jdt.core.JavaCore.run(JavaCore.java:3129) at org.eclipse.jdt.internal.ui.refactoring.RefactoringExecutionHelper$Operation.run(RefactoringExecutionHelper.java:78) at org.eclipse.jface.operation.ModalContext.runInCurrentThread(ModalContext.java:302) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:252) at org.eclipse.jface.dialogs.ProgressMonitorDialog.run(ProgressMonitorDialog.java:394) at org.eclipse.jdt.internal.ui.refactoring.RefactoringExecutionHelper.perform(RefactoringExecutionHelper.java:130) at org.eclipse.jdt.internal.ui.refactoring.reorg.ReorgCopyStarter.run(ReorgCopyStarter.java:70) at org.eclipse.jdt.internal.ui.refactoring.reorg.PasteAction$JavaElementAndResourcePaster.paste(PasteAction.java:402) at org.eclipse.jdt.internal.ui.refactoring.reorg.PasteAction.run(PasteAction.java:189) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun(SelectionDispatchAction.java:212) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run(SelectionDispatchAction.java:188) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.ui.actions.RetargetAction.runWithEvent(RetargetAction.java:212) at org.eclipse.ui.internal.commands.ActionHandler.execute(ActionHandler.java:40) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.executeCommand(WorkbenchKeyboard.java:390) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.press(WorkbenchKeyboard.java:763) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.processKeyEvent(WorkbenchKeyboard.java:803) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.filterKeySequenceBindings(WorkbenchKeyboard.java:486) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.access$0(WorkbenchKeyboard.java:421) at org.eclipse.ui.internal.keys.WorkbenchKeyboard$1.handleEvent(WorkbenchKeyboard.java:215) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Display.filterEvent(Display.java:692) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:846) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:871) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:856) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1716) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1712) at org.eclipse.swt.widgets.Control.WM_CHAR(Control.java:3036) at org.eclipse.swt.widgets.Tree.WM_CHAR(Tree.java:1292) at org.eclipse.swt.widgets.Control.windowProc(Control.java:2939) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2836) at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:1369) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1990) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1506) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1482) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:246) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:47) at org.eclipse.core.internal.runtime.PlatformActivator$1.run(PlatformActivator.java:226) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:85) 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:279) at org.eclipse.core.launcher.Main.run(Main.java:742) at org.eclipse.core.launcher.Main.main(Main.java:581)
|
verified fixed
|
0abeada
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-14T17:11:21Z | 2004-01-14T11:33:20Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/reorg/CreateCopyOfCompilationUnitChange.java
| |
49,975 |
Bug 49975 Java Editor "hangs" and JavaEditorTextHoverDescriptor
|
Software: Windows 2000, Eclipse build id I200401060800, Sun JDK 1.4.1_05. Hardware: Celeron 1,7Ghz, 512MB Ram, -Xms64M -Xmx380M vm parameters At various tasks (simple editing, saving, changing to other java editor) sometimes Eclipse "hangs" on several seconds. After some investigating I think that it maybe related to the org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverDescriptor class. I imported the jdt.ui plugin as a source plugin and and enhance the following function with one System.out: private boolean dependsOn(IPluginDescriptor descriptor0, IPluginDescriptor descriptor1) { System.out.println("# Enter: " + descriptor0.getLabel() + ", " + descriptor1.getLabel()); ... - the other remains the same } When running the runtime workbench every occured "hang" produces a large list (over 1600 elements). After this list completes I can continue my work. A sample list fraction I got for a simple "hang" (after switching two java editor with Ctrl+F6). The full list consists of 1764 lines): # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Text, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Eclipse UI, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Text, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Resource Management, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Default Text Editor, JDI Debug UI # Enter: Eclipse IDE UI, JDI Debug UI # Enter: Views, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Eclipse UI, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: Install/Update Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: Install/Update Configurator, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Resource Management, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Eclipse UI, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: JFace Text, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Text, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: Text Editor Framework, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: JFace Text, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Text, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Eclipse UI, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Text, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Resource Management, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: File Buffers, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: Core Resource Management, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Text, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Eclipse UI, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Text, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Eclipse UI, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Text, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Compare Support, JDI Debug UI # Enter: Eclipse IDE UI, JDI Debug UI # Enter: Views, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Eclipse UI, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: Install/Update Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: Install/Update Configurator, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Resource Management, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Eclipse UI, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: JFace Text, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Text, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: Text Editor Framework, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: JFace Text, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Text, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Eclipse UI, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Text, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Resource Management, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Eclipse UI, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Text, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Eclipse IDE UI, JDI Debug UI # Enter: Views, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Eclipse UI, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: Install/Update Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: Install/Update Configurator, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Resource Management, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Eclipse UI, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Search Support, JDI Debug UI # Enter: Eclipse IDE UI, JDI Debug UI # Enter: Views, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Eclipse UI, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: Install/Update Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: Install/Update Configurator, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Resource Management, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Eclipse UI, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Ent
|
resolved fixed
|
417760c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-15T17:37:58Z | 2004-01-14T14:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/JavaPlugin.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;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdapterManager;
import org.eclipse.core.runtime.IPluginDescriptor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.eclipse.ui.texteditor.MarkerAnnotationPreferences;
import org.eclipse.jdt.core.IBufferFactory;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.IWorkingCopyManager;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jdt.internal.core.DefaultWorkingCopyOwner;
import org.eclipse.jdt.internal.corext.javadoc.JavaDocLocations;
import org.eclipse.jdt.internal.corext.refactoring.base.Refactoring;
import org.eclipse.jdt.internal.corext.util.AllTypesCache;
import org.eclipse.jdt.internal.ui.browsing.LogicalPackage;
import org.eclipse.jdt.internal.ui.javaeditor.ClassFileDocumentProvider;
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitDocumentProvider;
import org.eclipse.jdt.internal.ui.javaeditor.CustomBufferFactory;
import org.eclipse.jdt.internal.ui.javaeditor.ICompilationUnitDocumentProvider;
import org.eclipse.jdt.internal.ui.javaeditor.WorkingCopyManager;
import org.eclipse.jdt.internal.ui.javaeditor.filebuffers.CompilationUnitDocumentProvider2;
import org.eclipse.jdt.internal.ui.javaeditor.filebuffers.CustomBufferFactory2;
import org.eclipse.jdt.internal.ui.preferences.MembersOrderPreferenceCache;
import org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverDescriptor;
import org.eclipse.jdt.internal.ui.viewsupport.ImageDescriptorRegistry;
import org.eclipse.jdt.internal.ui.viewsupport.ProblemMarkerManager;
/**
* Represents the java plugin. It provides a series of convenience methods such as
* access to the workbench, keeps track of elements shared by all editors and viewers
* of the plugin such as document providers and find-replace-dialogs.
*/
public class JavaPlugin extends AbstractUIPlugin {
/** temporarily */
public static final boolean USE_WORKING_COPY_OWNERS= true;
/** temporarily */
public static final boolean USE_FILE_BUFFERS= true;
private static JavaPlugin fgJavaPlugin;
private IWorkingCopyManager fWorkingCopyManager;
private IBufferFactory fBufferFactory;
private ICompilationUnitDocumentProvider fCompilationUnitDocumentProvider;
private ClassFileDocumentProvider fClassFileDocumentProvider;
private JavaTextTools fJavaTextTools;
private ProblemMarkerManager fProblemMarkerManager;
private ImageDescriptorRegistry fImageDescriptorRegistry;
private JavaElementAdapterFactory fJavaElementAdapterFactory;
private MarkerAdapterFactory fMarkerAdapterFactory;
private EditorInputAdapterFactory fEditorInputAdapterFactory;
private ResourceAdapterFactory fResourceAdapterFactory;
private LogicalPackageAdapterFactory fLogicalPackageAdapterFactory;
private MembersOrderPreferenceCache fMembersOrderPreferenceCache;
private IPropertyChangeListener fFontPropertyChangeListener;
private JavaEditorTextHoverDescriptor[] fJavaEditorTextHoverDescriptors;
public static JavaPlugin getDefault() {
return fgJavaPlugin;
}
public static IWorkspace getWorkspace() {
return ResourcesPlugin.getWorkspace();
}
public static IWorkbenchPage getActivePage() {
return getDefault().internalGetActivePage();
}
public static IWorkbenchWindow getActiveWorkbenchWindow() {
return getDefault().getWorkbench().getActiveWorkbenchWindow();
}
public static Shell getActiveWorkbenchShell() {
IWorkbenchWindow window= getActiveWorkbenchWindow();
if (window != null) {
return window.getShell();
}
return null;
}
/**
* Returns an array of all editors that have an unsaved content. If the identical content is
* presented in more than one editor, only one of those editor parts is part of the result.
*
* @return an array of all dirty editor parts.
*/
public static IEditorPart[] getDirtyEditors() {
Set inputs= new HashSet();
List result= new ArrayList(0);
IWorkbench workbench= getDefault().getWorkbench();
IWorkbenchWindow[] windows= workbench.getWorkbenchWindows();
for (int i= 0; i < windows.length; i++) {
IWorkbenchPage[] pages= windows[i].getPages();
for (int x= 0; x < pages.length; x++) {
IEditorPart[] editors= pages[x].getDirtyEditors();
for (int z= 0; z < editors.length; z++) {
IEditorPart ep= editors[z];
IEditorInput input= ep.getEditorInput();
if (!inputs.contains(input)) {
inputs.add(input);
result.add(ep);
}
}
}
}
return (IEditorPart[])result.toArray(new IEditorPart[result.size()]);
}
/**
* Returns an array of all instanciated editors.
*/
public static IEditorPart[] getInstanciatedEditors() {
List result= new ArrayList(0);
IWorkbench workbench= getDefault().getWorkbench();
IWorkbenchWindow[] windows= workbench.getWorkbenchWindows();
for (int windowIndex= 0; windowIndex < windows.length; windowIndex++) {
IWorkbenchPage[] pages= windows[windowIndex].getPages();
for (int pageIndex= 0; pageIndex < pages.length; pageIndex++) {
IEditorReference[] references= pages[pageIndex].getEditorReferences();
for (int refIndex= 0; refIndex < references.length; refIndex++) {
IEditorPart editor= references[refIndex].getEditor(false);
if (editor != null)
result.add(editor);
}
}
}
return (IEditorPart[])result.toArray(new IEditorPart[result.size()]);
}
public static String getPluginId() {
return getDefault().getDescriptor().getUniqueIdentifier();
}
public static void log(IStatus status) {
getDefault().getLog().log(status);
}
public static void logErrorMessage(String message) {
log(new Status(IStatus.ERROR, getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, message, null));
}
public static void logErrorStatus(String message, IStatus status) {
if (status == null) {
logErrorMessage(message);
return;
}
MultiStatus multi= new MultiStatus(getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, message, null);
multi.add(status);
log(multi);
}
public static void log(Throwable e) {
log(new Status(IStatus.ERROR, getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, JavaUIMessages.getString("JavaPlugin.internal_error"), e)); //$NON-NLS-1$
}
public static boolean isDebug() {
return getDefault().isDebugging();
}
public static ImageDescriptorRegistry getImageDescriptorRegistry() {
return getDefault().internalGetImageDescriptorRegistry();
}
public JavaPlugin(IPluginDescriptor descriptor) {
super(descriptor);
fgJavaPlugin= this;
}
/* (non - Javadoc)
* Method declared in Plugin
*/
public void startup() throws CoreException {
super.startup();
registerAdapters();
if (USE_WORKING_COPY_OWNERS)
DefaultWorkingCopyOwner.PRIMARY.factory= getBufferFactory();
/*
* Backward compatibility: propagate the Java editor font from a
* pre-2.1 plug-in to the Platform UI's preference store to preserve
* the Java editor font from a pre-2.1 workspace. This is done only
* once.
*/
String fontPropagatedKey= "fontPropagated"; //$NON-NLS-1$
if (getPreferenceStore().contains(JFaceResources.TEXT_FONT) && !getPreferenceStore().isDefault(JFaceResources.TEXT_FONT)) {
if (!getPreferenceStore().getBoolean(fontPropagatedKey))
PreferenceConverter.setValue(PlatformUI.getWorkbench().getPreferenceStore(), PreferenceConstants.EDITOR_TEXT_FONT, PreferenceConverter.getFontDataArray(getPreferenceStore(), JFaceResources.TEXT_FONT));
}
getPreferenceStore().setValue(fontPropagatedKey, true);
/*
* Backward compatibility: set the Java editor font in this plug-in's
* preference store to let older versions access it. Since 2.1 the
* Java editor font is managed by the workbench font preference page.
*/
PreferenceConverter.putValue(getPreferenceStore(), JFaceResources.TEXT_FONT, JFaceResources.getFontRegistry().getFontData(PreferenceConstants.EDITOR_TEXT_FONT));
fFontPropertyChangeListener= new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
if (PreferenceConstants.EDITOR_TEXT_FONT.equals(event.getProperty()))
PreferenceConverter.putValue(getPreferenceStore(), JFaceResources.TEXT_FONT, JFaceResources.getFontRegistry().getFontData(PreferenceConstants.EDITOR_TEXT_FONT));
}
};
JFaceResources.getFontRegistry().addListener(fFontPropertyChangeListener);
AllTypesCache.initialize();
}
/* (non - Javadoc)
* Method declared in AbstractUIPlugin
*/
protected ImageRegistry createImageRegistry() {
return JavaPluginImages.getImageRegistry();
}
/* (non - Javadoc)
* Method declared in Plugin
*/
public void shutdown() throws CoreException {
AllTypesCache.terminate();
if (fImageDescriptorRegistry != null)
fImageDescriptorRegistry.dispose();
unregisterAdapters();
super.shutdown();
if (fWorkingCopyManager != null) {
fWorkingCopyManager.shutdown();
fWorkingCopyManager= null;
}
if (fCompilationUnitDocumentProvider != null) {
fCompilationUnitDocumentProvider.shutdown();
fCompilationUnitDocumentProvider= null;
}
if (fJavaTextTools != null) {
fJavaTextTools.dispose();
fJavaTextTools= null;
}
JavaDocLocations.shutdownJavadocLocations();
JFaceResources.getFontRegistry().removeListener(fFontPropertyChangeListener);
Refactoring.getUndoManager().shutdown();
}
private IWorkbenchPage internalGetActivePage() {
IWorkbenchWindow window= getWorkbench().getActiveWorkbenchWindow();
if (window == null)
return null;
return getWorkbench().getActiveWorkbenchWindow().getActivePage();
}
public synchronized IBufferFactory getBufferFactory() {
if (fBufferFactory == null)
fBufferFactory= USE_FILE_BUFFERS ? (IBufferFactory) new CustomBufferFactory2() : (IBufferFactory) new CustomBufferFactory();
return fBufferFactory;
}
public synchronized ICompilationUnitDocumentProvider getCompilationUnitDocumentProvider() {
if (fCompilationUnitDocumentProvider == null)
fCompilationUnitDocumentProvider= USE_FILE_BUFFERS ? (ICompilationUnitDocumentProvider) new CompilationUnitDocumentProvider2() : (ICompilationUnitDocumentProvider) new CompilationUnitDocumentProvider();
return fCompilationUnitDocumentProvider;
}
public synchronized ClassFileDocumentProvider getClassFileDocumentProvider() {
if (fClassFileDocumentProvider == null)
fClassFileDocumentProvider= new ClassFileDocumentProvider();
return fClassFileDocumentProvider;
}
public synchronized IWorkingCopyManager getWorkingCopyManager() {
if (fWorkingCopyManager == null) {
ICompilationUnitDocumentProvider provider= getCompilationUnitDocumentProvider();
fWorkingCopyManager= new WorkingCopyManager(provider);
}
return fWorkingCopyManager;
}
public synchronized ProblemMarkerManager getProblemMarkerManager() {
if (fProblemMarkerManager == null)
fProblemMarkerManager= new ProblemMarkerManager();
return fProblemMarkerManager;
}
public synchronized JavaTextTools getJavaTextTools() {
if (fJavaTextTools == null)
fJavaTextTools= new JavaTextTools(getPreferenceStore(), JavaCore.getPlugin().getPluginPreferences());
return fJavaTextTools;
}
public synchronized MembersOrderPreferenceCache getMemberOrderPreferenceCache() {
if (fMembersOrderPreferenceCache == null)
fMembersOrderPreferenceCache= new MembersOrderPreferenceCache();
return fMembersOrderPreferenceCache;
}
/**
* Returns all Java editor text hovers contributed to the workbench.
*
* @return an array of JavaEditorTextHoverDescriptor
* @since 2.1
*/
public JavaEditorTextHoverDescriptor[] getJavaEditorTextHoverDescriptors() {
if (fJavaEditorTextHoverDescriptors == null)
fJavaEditorTextHoverDescriptors= JavaEditorTextHoverDescriptor.getContributedHovers();
return fJavaEditorTextHoverDescriptors;
}
/**
* Resets the Java editor text hovers contributed to the workbench.
* <p>
* This will force a rebuild of the descriptors the next time
* a client asks for them.
* </p>
*
* @return an array of JavaEditorTextHoverDescriptor
* @since 2.1
*/
public void resetJavaEditorTextHoverDescriptors() {
fJavaEditorTextHoverDescriptors= null;
}
/**
* Creates the Java plugin standard groups in a context menu.
*/
public static void createStandardGroups(IMenuManager menu) {
if (!menu.isEmpty())
return;
menu.add(new Separator(IContextMenuConstants.GROUP_NEW));
menu.add(new GroupMarker(IContextMenuConstants.GROUP_GOTO));
menu.add(new Separator(IContextMenuConstants.GROUP_OPEN));
menu.add(new GroupMarker(IContextMenuConstants.GROUP_SHOW));
menu.add(new Separator(IContextMenuConstants.GROUP_REORGANIZE));
menu.add(new Separator(IContextMenuConstants.GROUP_GENERATE));
menu.add(new Separator(IContextMenuConstants.GROUP_SEARCH));
menu.add(new Separator(IContextMenuConstants.GROUP_BUILD));
menu.add(new Separator(IContextMenuConstants.GROUP_ADDITIONS));
menu.add(new Separator(IContextMenuConstants.GROUP_VIEWER_SETUP));
menu.add(new Separator(IContextMenuConstants.GROUP_PROPERTIES));
}
/**
* @see AbstractUIPlugin#initializeDefaultPreferences
*/
protected void initializeDefaultPreferences(IPreferenceStore store) {
super.initializeDefaultPreferences(store);
MarkerAnnotationPreferences.initializeDefaultValues(store);
PreferenceConstants.initializeDefaultValues(store);
}
private synchronized ImageDescriptorRegistry internalGetImageDescriptorRegistry() {
if (fImageDescriptorRegistry == null)
fImageDescriptorRegistry= new ImageDescriptorRegistry();
return fImageDescriptorRegistry;
}
private void registerAdapters() {
fJavaElementAdapterFactory= new JavaElementAdapterFactory();
fMarkerAdapterFactory= new MarkerAdapterFactory();
fEditorInputAdapterFactory= new EditorInputAdapterFactory();
fResourceAdapterFactory= new ResourceAdapterFactory();
fLogicalPackageAdapterFactory= new LogicalPackageAdapterFactory();
IAdapterManager manager= Platform.getAdapterManager();
manager.registerAdapters(fJavaElementAdapterFactory, IJavaElement.class);
manager.registerAdapters(fMarkerAdapterFactory, IMarker.class);
manager.registerAdapters(fEditorInputAdapterFactory, IEditorInput.class);
manager.registerAdapters(fResourceAdapterFactory, IResource.class);
manager.registerAdapters(fLogicalPackageAdapterFactory, LogicalPackage.class);
}
private void unregisterAdapters() {
IAdapterManager manager= Platform.getAdapterManager();
manager.unregisterAdapters(fJavaElementAdapterFactory);
manager.unregisterAdapters(fMarkerAdapterFactory);
manager.unregisterAdapters(fEditorInputAdapterFactory);
manager.unregisterAdapters(fResourceAdapterFactory);
manager.unregisterAdapters(fLogicalPackageAdapterFactory);
}
}
|
49,975 |
Bug 49975 Java Editor "hangs" and JavaEditorTextHoverDescriptor
|
Software: Windows 2000, Eclipse build id I200401060800, Sun JDK 1.4.1_05. Hardware: Celeron 1,7Ghz, 512MB Ram, -Xms64M -Xmx380M vm parameters At various tasks (simple editing, saving, changing to other java editor) sometimes Eclipse "hangs" on several seconds. After some investigating I think that it maybe related to the org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverDescriptor class. I imported the jdt.ui plugin as a source plugin and and enhance the following function with one System.out: private boolean dependsOn(IPluginDescriptor descriptor0, IPluginDescriptor descriptor1) { System.out.println("# Enter: " + descriptor0.getLabel() + ", " + descriptor1.getLabel()); ... - the other remains the same } When running the runtime workbench every occured "hang" produces a large list (over 1600 elements). After this list completes I can continue my work. A sample list fraction I got for a simple "hang" (after switching two java editor with Ctrl+F6). The full list consists of 1764 lines): # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Text, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Eclipse UI, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Text, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Resource Management, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Default Text Editor, JDI Debug UI # Enter: Eclipse IDE UI, JDI Debug UI # Enter: Views, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Eclipse UI, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: Install/Update Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: Install/Update Configurator, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Resource Management, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Eclipse UI, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: JFace Text, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Text, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: Text Editor Framework, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: JFace Text, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Text, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Eclipse UI, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Text, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Resource Management, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: File Buffers, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: Core Resource Management, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Text, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Eclipse UI, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Text, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Eclipse UI, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Text, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Compare Support, JDI Debug UI # Enter: Eclipse IDE UI, JDI Debug UI # Enter: Views, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Eclipse UI, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: Install/Update Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: Install/Update Configurator, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Resource Management, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Eclipse UI, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: JFace Text, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Text, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: Text Editor Framework, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: JFace Text, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Text, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Eclipse UI, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Text, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Resource Management, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Eclipse UI, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Text, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Eclipse IDE UI, JDI Debug UI # Enter: Views, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Eclipse UI, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: Install/Update Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: Install/Update Configurator, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Resource Management, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Eclipse UI, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Search Support, JDI Debug UI # Enter: Eclipse IDE UI, JDI Debug UI # Enter: Views, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Eclipse UI, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: Install/Update Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: Install/Update Configurator, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Resource Management, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Eclipse UI, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Ent
|
resolved fixed
|
417760c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-15T17:37:58Z | 2004-01-14T14:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/hover/BestMatchHover.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text.java.hover;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import org.eclipse.jface.text.IInformationControlCreator;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextHover;
import org.eclipse.jface.text.ITextHoverExtension;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.information.IInformationProviderExtension2;
import org.eclipse.ui.IEditorPart;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.text.java.hover.IJavaEditorTextHover;
import org.eclipse.jdt.internal.ui.JavaPlugin;
/**
* Caution: this implementation is a layer breaker and contains some "shortcuts"
*/
public class BestMatchHover extends AbstractJavaEditorTextHover implements ITextHoverExtension, IInformationProviderExtension2 {
private static class JavaEditorTextHoverDescriptorComparator implements Comparator {
/*
* @see Comparator#compare(Object, Object)
*/
public int compare(Object object0, Object object1) {
JavaEditorTextHoverDescriptor element0= (JavaEditorTextHoverDescriptor)object0;
JavaEditorTextHoverDescriptor element1= (JavaEditorTextHoverDescriptor)object1;
String id0= element0.getId();
String id1= element1.getId();
if (id0 != null && id0.equals(id1))
return 0;
if (id0 != null && AnnotationHover.isJavaProblemHover(id0))
return -1;
if (id1 != null && AnnotationHover.isJavaProblemHover(id1))
return +1;
// now compare non-problem hovers
if (element0.dependsOn(element1))
return -1;
if (element1.dependsOn(element0))
return +1;
return 0;
}
}
private List fTextHoverSpecifications;
private List fInstantiatedTextHovers;
private ITextHover fBestHover;
public BestMatchHover() {
installTextHovers();
}
public BestMatchHover(IEditorPart editor) {
this();
setEditor(editor);
}
/**
* Installs all text hovers.
*/
private void installTextHovers() {
// initialize lists - indicates that the initialization happened
fTextHoverSpecifications= new ArrayList(2);
fInstantiatedTextHovers= new ArrayList(2);
// populate list
JavaEditorTextHoverDescriptor[] hoverDescs= JavaPlugin.getDefault().getJavaEditorTextHoverDescriptors();
for (int i= 0; i < hoverDescs.length; i++) {
// ensure that we don't add ourselves to the list
if (!PreferenceConstants.ID_BESTMATCH_HOVER.equals(hoverDescs[i].getId()))
fTextHoverSpecifications.add(hoverDescs[i]);
}
Collections.sort(fTextHoverSpecifications, new JavaEditorTextHoverDescriptorComparator());
}
private void checkTextHovers() {
if (fTextHoverSpecifications.size() == 0)
return;
for (Iterator iterator= new ArrayList(fTextHoverSpecifications).iterator(); iterator.hasNext(); ) {
JavaEditorTextHoverDescriptor spec= (JavaEditorTextHoverDescriptor) iterator.next();
IJavaEditorTextHover hover= spec.createTextHover();
if (hover != null) {
hover.setEditor(getEditor());
addTextHover(hover);
fTextHoverSpecifications.remove(spec);
}
}
}
protected void addTextHover(ITextHover hover) {
if (!fInstantiatedTextHovers.contains(hover))
fInstantiatedTextHovers.add(hover);
}
/*
* @see ITextHover#getHoverInfo(ITextViewer, IRegion)
*/
public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
checkTextHovers();
fBestHover= null;
if (fInstantiatedTextHovers == null)
return null;
for (Iterator iterator= fInstantiatedTextHovers.iterator(); iterator.hasNext(); ) {
ITextHover hover= (ITextHover)iterator.next();
String s= hover.getHoverInfo(textViewer, hoverRegion);
if (s != null && s.trim().length() > 0) {
fBestHover= hover;
return s;
}
}
return null;
}
/*
* @see org.eclipse.jface.text.ITextHoverExtension#getInformationControlCreator()
* @since 3.0
*/
public IInformationControlCreator getInformationControlCreator() {
if (fBestHover instanceof ITextHoverExtension)
return ((ITextHoverExtension)fBestHover).getInformationControlCreator();
return null;
}
/*
* @see org.eclipse.jface.text.information.IInformationProviderExtension2#getInformationPresenterControlCreator()
* @since 3.0
*/
public IInformationControlCreator getInformationPresenterControlCreator() {
if (fBestHover instanceof IInformationProviderExtension2)
return ((IInformationProviderExtension2)fBestHover).getInformationPresenterControlCreator();
return null;
}
}
|
49,975 |
Bug 49975 Java Editor "hangs" and JavaEditorTextHoverDescriptor
|
Software: Windows 2000, Eclipse build id I200401060800, Sun JDK 1.4.1_05. Hardware: Celeron 1,7Ghz, 512MB Ram, -Xms64M -Xmx380M vm parameters At various tasks (simple editing, saving, changing to other java editor) sometimes Eclipse "hangs" on several seconds. After some investigating I think that it maybe related to the org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverDescriptor class. I imported the jdt.ui plugin as a source plugin and and enhance the following function with one System.out: private boolean dependsOn(IPluginDescriptor descriptor0, IPluginDescriptor descriptor1) { System.out.println("# Enter: " + descriptor0.getLabel() + ", " + descriptor1.getLabel()); ... - the other remains the same } When running the runtime workbench every occured "hang" produces a large list (over 1600 elements). After this list completes I can continue my work. A sample list fraction I got for a simple "hang" (after switching two java editor with Ctrl+F6). The full list consists of 1764 lines): # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Text, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Eclipse UI, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Text, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Resource Management, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Default Text Editor, JDI Debug UI # Enter: Eclipse IDE UI, JDI Debug UI # Enter: Views, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Eclipse UI, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: Install/Update Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: Install/Update Configurator, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Resource Management, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Eclipse UI, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: JFace Text, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Text, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: Text Editor Framework, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: JFace Text, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Text, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Eclipse UI, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Text, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Resource Management, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: File Buffers, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: Core Resource Management, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Text, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Eclipse UI, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Text, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Eclipse UI, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Text, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Compare Support, JDI Debug UI # Enter: Eclipse IDE UI, JDI Debug UI # Enter: Views, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Eclipse UI, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: Install/Update Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: Install/Update Configurator, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Resource Management, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Eclipse UI, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: JFace Text, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Text, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: Text Editor Framework, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: JFace Text, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Text, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Eclipse UI, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Text, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Resource Management, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Eclipse UI, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Text, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Eclipse IDE UI, JDI Debug UI # Enter: Views, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Eclipse UI, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: Install/Update Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: Install/Update Configurator, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Resource Management, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Eclipse UI, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Search Support, JDI Debug UI # Enter: Eclipse IDE UI, JDI Debug UI # Enter: Views, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Eclipse UI, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Help System Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: Install/Update Core, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: Install/Update Configurator, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Core Resource Management, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Eclipse UI, JDI Debug UI # Enter: JFace, JDI Debug UI # Enter: Standard Widget Toolkit, JDI Debug UI # Enter: Core Runtime Plug-in Compatibility, JDI Debug UI # Enter: org.eclipse.core.runtime, JDI Debug UI # Enter: Workbench, JDI Debug UI # Enter: JFace, JDI Debug UI # Ent
|
resolved fixed
|
417760c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-15T17:37:58Z | 2004-01-14T14:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/hover/JavaEditorTextHoverDescriptorComparator.java
| |
50,194 |
Bug 50194 Indenting Java breaks comments
|
When correcting indentation (ctrl-I in my configuration), java comments are not properly preserved. My original code [1] is 'indented' to code [2], which is unexpected and syntactically incorrect. thanks PhF .. [1] try{ /* for(int i=0; i<8; i++){ System.out.println("something");} */ somethingElse(); .. [2] try{ /* */ for(int i=0; i<8; i++){ System.out.println("something");} */ somethingElse();
|
verified fixed
|
1f57f57
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-19T14:14:41Z | 2004-01-19T08:13:20Z |
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.jface.text.source.ISourceViewer;
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.javaeditor.JavaEditor;
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() || !validateEditorInputState())
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;
fCaretOffset= -1;
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, "", e)); //$NON-NLS-1$
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, newLength;
if (fIsTabAction) {
newOffset= fCaretOffset;
newLength= 0;
} else if (nLines > 1) {
newOffset= offset;
newLength= end.getOffset() - offset;
} else {
newOffset= fCaretOffset;
newLength= 0;
}
// always reset the selection if anything was replaced
// but not when we had a singleline nontab invocation
if (newOffset != -1 && (hasChanged || newOffset != offset || newLength != length))
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, "ConcurrentModification in IndentAction", e)); //$NON-NLS-1$
} 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();
}
}
/**
* Selects the given range on the editor.
*
* @param newOffset the selection offset
* @param newLength the selection range
*/
private void selectAndReveal(int newOffset, int newLength) {
Assert.isTrue(newOffset >= 0);
Assert.isTrue(newLength >= 0);
ITextEditor editor= getTextEditor();
if (editor instanceof JavaEditor) {
ISourceViewer viewer= ((JavaEditor)editor).getViewer();
if (viewer != null)
viewer.setSelectedRange(newOffset, newLength);
} else
// this is too intrusive, but will never get called anyway
getTextEditor().selectAndReveal(newOffset, newLength);
}
/**
* 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;
int start= 0;
if (line > 0) {
IRegion previousLine= document.getLineInformation(line - 1);
start= previousLine.getOffset() + previousLine.getLength();
}
DocumentCommand command= new DocumentCommand() {};
command.text= "\n"; //$NON-NLS-1$
command.offset= start;
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) {
StringBuffer computed= indenter.computeIndentation(offset);
if (computed != null)
indent= computed.toString();
else
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
if (caret >= offset && caret <= end)
fCaretOffset= offset + indent.length();
else
fCaretOffset= -1;
// 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();
}
}
|
50,194 |
Bug 50194 Indenting Java breaks comments
|
When correcting indentation (ctrl-I in my configuration), java comments are not properly preserved. My original code [1] is 'indented' to code [2], which is unexpected and syntactically incorrect. thanks PhF .. [1] try{ /* for(int i=0; i<8; i++){ System.out.println("something");} */ somethingElse(); .. [2] try{ /* */ for(int i=0; i<8; i++){ System.out.println("something");} */ somethingElse();
|
verified fixed
|
1f57f57
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-19T14:14:41Z | 2004-01-19T08:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/javadoc/JavaDocAutoIndentStrategy.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text.javadoc;
import java.text.BreakIterator;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DefaultAutoIndentStrategy;
import org.eclipse.jface.text.DocumentCommand;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.TextUtilities;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.texteditor.ExtendedTextEditorPreferenceConstants;
import org.eclipse.ui.texteditor.ITextEditorExtension3;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.CodeGeneration;
import org.eclipse.jdt.ui.IWorkingCopyManager;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.corext.util.CodeFormatterUtil;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.corext.util.Strings;
import org.eclipse.jdt.internal.corext.util.SuperTypeHierarchyCache;
import org.eclipse.jdt.internal.ui.JavaPlugin;
/**
* Auto indent strategy for java doc comments
*/
public class JavaDocAutoIndentStrategy extends DefaultAutoIndentStrategy {
private String fPartitioning;
/**
* Creates a new Javadoc auto indent strategy for the given document partitioning.
*
* @param partitioning the document partitioning
*/
public JavaDocAutoIndentStrategy(String partitioning) {
fPartitioning= partitioning;
}
private static String getLineDelimiter(IDocument document) {
try {
if (document.getNumberOfLines() > 1)
return document.getLineDelimiter(0);
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
return System.getProperty("line.separator"); //$NON-NLS-1$
}
/**
* Copies the indentation of the previous line and add a star.
* If the javadoc just started on this line add standard method tags
* and close the javadoc.
*
* @param d the document to work on
* @param c the command to deal with
*/
private void jdocIndentAfterNewLine(IDocument d, DocumentCommand c) {
if (c.offset == -1 || d.getLength() == 0)
return;
try {
// find start of line
int p= (c.offset == d.getLength() ? c.offset - 1 : c.offset);
IRegion info= d.getLineInformationOfOffset(p);
int start= info.getOffset();
// find white spaces
int end= findEndOfWhiteSpace(d, start, c.offset);
StringBuffer buf= new StringBuffer(c.text);
if (end >= start) { // 1GEYL1R: ITPJUI:ALL - java doc edit smartness not work for class comments
// append to input
String indentation= jdocExtractLinePrefix(d, d.getLineOfOffset(c.offset));
buf.append(indentation);
if (end < c.offset) {
if (d.getChar(end) == '/') {
// javadoc started on this line
buf.append(" * "); //$NON-NLS-1$
if (JavaPlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_CLOSE_JAVADOCS) && isNewComment(d, c.offset, fPartitioning)) {
String lineDelimiter= getLineDelimiter(d);
c.doit= false;
d.replace(c.offset, 0, lineDelimiter + indentation + " */"); //$NON-NLS-1$
// evaluate method signature
ICompilationUnit unit= getCompilationUnit();
if (JavaPlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS) &&
unit != null)
{
try {
synchronized (unit) {
unit.reconcile();
}
String string= createJavaDocTags(d, c, indentation, lineDelimiter, unit);
if (string != null)
d.replace(c.offset, 0, string);
} catch (CoreException e) {
// ignore
}
}
}
}
}
}
c.text= buf.toString();
} catch (BadLocationException excp) {
// stop work
}
}
private String createJavaDocTags(IDocument document, DocumentCommand command, String indentation, String lineDelimiter, ICompilationUnit unit)
throws CoreException, BadLocationException
{
IJavaElement element= unit.getElementAt(command.offset);
if (element == null)
return null;
switch (element.getElementType()) {
case IJavaElement.TYPE:
return createTypeTags(document, command, indentation, lineDelimiter, (IType) element);
case IJavaElement.METHOD:
return createMethodTags(document, command, indentation, lineDelimiter, (IMethod) element);
default:
return null;
}
}
/*
* Removes start and end of a comment and corrects indentation and line delimiters.
*/
private String prepareTemplateComment(String comment, String indentation, String lineDelimiter) {
// trim comment start and end if any
if (comment.endsWith("*/")) //$NON-NLS-1$
comment= comment.substring(0, comment.length() - 2);
comment= comment.trim();
if (comment.startsWith("/*")) { //$NON-NLS-1$
if (comment.length() > 2 && comment.charAt(2) == '*') {
comment= comment.substring(3); // remove '/**'
} else {
comment= comment.substring(2); // remove '/*'
}
}
return Strings.changeIndent(comment, 0, CodeFormatterUtil.getTabWidth(), indentation, lineDelimiter);
}
private String createTypeTags(IDocument document, DocumentCommand command, String indentation, String lineDelimiter, IType type)
throws CoreException
{
String comment= CodeGeneration.getTypeComment(type.getCompilationUnit(), type.getTypeQualifiedName('.'), lineDelimiter);
if (comment != null) {
return prepareTemplateComment(comment.trim(), indentation, lineDelimiter);
}
return null;
}
private String createMethodTags(IDocument document, DocumentCommand command, String indentation, String lineDelimiter, IMethod method)
throws CoreException, BadLocationException
{
IRegion partition= TextUtilities.getPartition(document, fPartitioning, command.offset);
ISourceRange sourceRange= method.getSourceRange();
if (sourceRange == null || sourceRange.getOffset() != partition.getOffset())
return null;
IMethod inheritedMethod= getInheritedMethod(method);
String comment= CodeGeneration.getMethodComment(method, inheritedMethod, lineDelimiter);
if (comment != null) {
comment= comment.trim();
boolean javadocComment= comment.startsWith("/**"); //$NON-NLS-1$
boolean isJavaDoc= partition.getLength() >= 3 && document.get(partition.getOffset(), 3).equals("/**"); //$NON-NLS-1$
if (javadocComment == isJavaDoc) {
return prepareTemplateComment(comment, indentation, lineDelimiter);
}
}
return null;
}
/**
* Returns the method inherited from, <code>null</code> if method is newly defined.
*/
private static IMethod getInheritedMethod(IMethod method) throws JavaModelException {
IType declaringType= method.getDeclaringType();
ITypeHierarchy typeHierarchy= SuperTypeHierarchyCache.getTypeHierarchy(declaringType);
return JavaModelUtil.findMethodDeclarationInHierarchy(typeHierarchy, declaringType,
method.getElementName(), method.getParameterTypes(), method.isConstructor());
}
protected void jdocIndentForCommentEnd(IDocument d, DocumentCommand c) {
if (c.offset < 2 || d.getLength() == 0) {
return;
}
try {
if ("* ".equals(d.get(c.offset - 2, 2))) { //$NON-NLS-1$
// modify document command
c.length++;
c.offset--;
}
} catch (BadLocationException excp) {
// stop work
}
}
/**
* Guesses if the command operates within a newly created javadoc comment or not.
* If in doubt, it will assume that the javadoc is new.
*/
private static boolean isNewComment(IDocument document, int commandOffset, String partitioning) {
try {
int lineIndex= document.getLineOfOffset(commandOffset) + 1;
if (lineIndex >= document.getNumberOfLines())
return true;
IRegion line= document.getLineInformation(lineIndex);
ITypedRegion partition= TextUtilities.getPartition(document, partitioning, commandOffset);
if (document.getLineOffset(lineIndex) >= partition.getOffset() + partition.getLength())
return false;
String string= document.get(line.getOffset(), line.getLength());
if (!string.trim().startsWith("*")) //$NON-NLS-1$
return true;
return false;
} catch (BadLocationException e) {
return false;
}
}
private boolean isSmartMode() {
IWorkbenchPage page= JavaPlugin.getActivePage();
if (page != null) {
IEditorPart part= page.getActiveEditor();
if (part instanceof ITextEditorExtension3) {
ITextEditorExtension3 extension= (ITextEditorExtension3) part;
return extension.getInsertMode() == ITextEditorExtension3.SMART_INSERT;
}
}
return false;
}
/*
* @see IAutoIndentStrategy#customizeDocumentCommand
*/
public void customizeDocumentCommand(IDocument document, DocumentCommand command) {
if (!isSmartMode())
return;
try {
if (command.text != null && command.length == 0) {
String[] lineDelimiters= document.getLegalLineDelimiters();
int index= TextUtilities.endsWith(lineDelimiters, command.text);
if (index > -1) {
// ends with line delimiter
if (lineDelimiters[index].equals(command.text))
// just the line delimiter
jdocIndentAfterNewLine(document, command);
return;
}
}
if (command.text != null && command.text.equals("/")) { //$NON-NLS-1$
jdocIndentForCommentEnd(document, command);
return;
}
ITypedRegion partition= TextUtilities.getPartition(document, fPartitioning, command.offset);
int partitionStart= partition.getOffset();
int partitionEnd= partition.getLength() + partitionStart;
String text= command.text;
int offset= command.offset;
int length= command.length;
// partition change
final int PREFIX_LENGTH= "/*".length(); //$NON-NLS-1$
final int POSTFIX_LENGTH= "*/".length(); //$NON-NLS-1$
if ((offset < partitionStart + PREFIX_LENGTH || offset + length > partitionEnd - POSTFIX_LENGTH) ||
text != null && text.length() >= 2 && ((text.indexOf("*/") != -1) || (document.getChar(offset) == '*' && text.startsWith("/")))) //$NON-NLS-1$ //$NON-NLS-2$
return;
if (command.text == null || command.text.length() == 0)
jdocHandleBackspaceDelete(document, command);
else if (command.text != null && command.length == 0 && command.text.length() > 0)
jdocWrapParagraphOnInsert(document, command);
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
}
private void flushCommand(IDocument document, DocumentCommand command) throws BadLocationException {
if (!command.doit)
return;
document.replace(command.offset, command.length, command.text);
command.doit= false;
if (command.text != null)
command.offset += command.text.length();
command.length= 0;
command.text= null;
}
protected void jdocWrapParagraphOnInsert(IDocument document, DocumentCommand command) throws BadLocationException {
// Assert.isTrue(command.length == 0);
// Assert.isTrue(command.text != null && command.text.length() == 1);
if (!getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_FORMAT_JAVADOCS))
return;
int line= document.getLineOfOffset(command.offset);
IRegion region= document.getLineInformation(line);
int lineOffset= region.getOffset();
int lineLength= region.getLength();
String lineContents= document.get(lineOffset, lineLength);
StringBuffer buffer= new StringBuffer(lineContents);
int start= command.offset - lineOffset;
int end= command.length + start;
buffer.replace(start, end, command.text);
// handle whitespace
if (command.text != null && command.text.length() != 0 && command.text.trim().length() == 0) {
String endOfLine= document.get(command.offset, lineOffset + lineLength - command.offset);
// end of line
if (endOfLine.length() == 0) {
// move caret to next line
flushCommand(document, command);
if (isLineTooShort(document, line)) {
int[] caretOffset= {command.offset};
jdocWrapParagraphFromLine(document, line, caretOffset, false);
command.offset= caretOffset[0];
return;
}
// move caret to next line if possible
if (line < document.getNumberOfLines() - 1 && isJavaDocLine(document, line + 1)) {
String lineDelimiter= document.getLineDelimiter(line);
String nextLinePrefix= jdocExtractLinePrefix(document, line + 1);
command.offset += lineDelimiter.length() + nextLinePrefix.length();
}
return;
// inside whitespace at end of line
} else if (endOfLine.trim().length() == 0) {
// simply insert space
return;
}
}
// change in prefix region
String prefix= jdocExtractLinePrefix(document, line);
boolean wrapAlways= command.offset >= lineOffset && command.offset <= lineOffset + prefix.length();
// must insert the text now because it may include whitepace
flushCommand(document, command);
if (wrapAlways || calculateDisplayedWidth(buffer.toString()) > getMargin() || isLineTooShort(document, line)) {
int[] caretOffset= {command.offset};
jdocWrapParagraphFromLine(document, line, caretOffset, wrapAlways);
if (!wrapAlways)
command.offset= caretOffset[0];
}
}
/**
* Method jdocWrapParagraphFromLine.
*
* @param document
* @param line
* @param always
*/
private void jdocWrapParagraphFromLine(IDocument document, int line, int[] caretOffset, boolean always) throws BadLocationException {
String indent= jdocExtractLinePrefix(document, line);
if (!always) {
if (!indent.trim().startsWith("*")) //$NON-NLS-1$
return;
if (indent.trim().startsWith("*/")) //$NON-NLS-1$
return;
if (!isLineTooLong(document, line) && !isLineTooShort(document, line))
return;
}
boolean caretRelativeToParagraphOffset= false;
int caret= caretOffset[0];
int caretLine= document.getLineOfOffset(caret);
int lineOffset= document.getLineOffset(line);
int paragraphOffset= lineOffset + indent.length();
if (paragraphOffset < caret) {
caret -= paragraphOffset;
caretRelativeToParagraphOffset= true;
} else {
caret -= lineOffset;
}
StringBuffer buffer= new StringBuffer();
int currentLine= line;
while (line == currentLine || isJavaDocLine(document, currentLine)) {
if (buffer.length() != 0 && !Character.isWhitespace(buffer.charAt(buffer.length() - 1))) {
buffer.append(' ');
if (currentLine <= caretLine) {
// in this case caretRelativeToParagraphOffset is always true
++caret;
}
}
String string= getLineContents(document, currentLine);
buffer.append(string);
currentLine++;
}
String paragraph= buffer.toString();
if (paragraph.trim().length() == 0)
return;
caretOffset[0]= caretRelativeToParagraphOffset ? caret : 0;
String delimiter= document.getLineDelimiter(0);
String wrapped= formatParagraph(paragraph, caretOffset, indent, delimiter, getMargin());
int beginning= document.getLineOffset(line);
int end= document.getLineOffset(currentLine);
document.replace(beginning, end - beginning, wrapped.toString());
caretOffset[0]= caretRelativeToParagraphOffset ? caretOffset[0] + beginning : caret + beginning;
}
/**
* Line break iterator to handle whitespaces as first class citizens.
*/
private static class LineBreakIterator {
private final String fString;
private final BreakIterator fIterator= BreakIterator.getLineInstance();
private int fStart;
private int fEnd;
private int fBufferedEnd;
public LineBreakIterator(String string) {
fString= string;
fIterator.setText(string);
}
public int first() {
fBufferedEnd= -1;
fStart= fIterator.first();
return fStart;
}
public int next() {
if (fBufferedEnd != -1) {
fStart= fEnd;
fEnd= fBufferedEnd;
fBufferedEnd= -1;
return fEnd;
}
fStart= fEnd;
fEnd= fIterator.next();
if (fEnd == BreakIterator.DONE)
return fEnd;
final String string= fString.substring(fStart, fEnd);
// whitespace
if (string.trim().length() == 0)
return fEnd;
final String word= string.trim();
if (word.length() == string.length())
return fEnd;
// suspected whitespace
fBufferedEnd= fEnd;
return fStart + word.length();
}
}
/**
* Formats a paragraph, using break iterator.
*
* @param offset an offset within the paragraph, which will be updated with respect to formatting.
*/
private static String formatParagraph(String paragraph, int[] offset, String prefix, String lineDelimiter, int margin) {
LineBreakIterator iterator= new LineBreakIterator(paragraph);
StringBuffer paragraphBuffer= new StringBuffer();
StringBuffer lineBuffer= new StringBuffer();
StringBuffer whiteSpaceBuffer= new StringBuffer();
int index= offset[0];
int indexBuffer= -1;
// line delimiter could be null
if (lineDelimiter == null)
lineDelimiter= ""; //$NON-NLS-1$
for (int start= iterator.first(), end= iterator.next(); end != BreakIterator.DONE; start= end, end= iterator.next()) {
String word= paragraph.substring(start, end);
// word is whitespace
if (word.trim().length() == 0) {
whiteSpaceBuffer.append(word);
// first word of line is always appended
} else if (lineBuffer.length() == 0) {
lineBuffer.append(prefix);
lineBuffer.append(whiteSpaceBuffer.toString());
lineBuffer.append(word);
} else {
String line= lineBuffer.toString() + whiteSpaceBuffer.toString() + word.toString();
// margin exceeded
if (calculateDisplayedWidth(line) > margin) {
// flush line buffer and wrap paragraph
paragraphBuffer.append(lineBuffer.toString());
paragraphBuffer.append(lineDelimiter);
lineBuffer.setLength(0);
lineBuffer.append(prefix);
lineBuffer.append(word);
// flush index buffer
if (indexBuffer != -1) {
offset[0]= indexBuffer;
// correct for caret in whitespace at the end of line
if (whiteSpaceBuffer.length() != 0 && index < start && index >= start - whiteSpaceBuffer.length())
offset[0] -= (index - (start - whiteSpaceBuffer.length()));
indexBuffer= -1;
}
whiteSpaceBuffer.setLength(0);
// margin not exceeded
} else {
lineBuffer.append(whiteSpaceBuffer.toString());
lineBuffer.append(word);
whiteSpaceBuffer.setLength(0);
}
}
if (index >= start && index < end) {
indexBuffer= paragraphBuffer.length() + lineBuffer.length() + (index - start);
if (word.trim().length() != 0)
indexBuffer -= word.length();
}
}
// flush line buffer
paragraphBuffer.append(lineBuffer.toString());
paragraphBuffer.append(lineDelimiter);
// flush index buffer
if (indexBuffer != -1)
offset[0]= indexBuffer;
// last position is not returned by break iterator
else if (offset[0] == paragraph.length())
offset[0]= paragraphBuffer.length() - lineDelimiter.length();
return paragraphBuffer.toString();
}
private static IPreferenceStore getPreferenceStore() {
return JavaPlugin.getDefault().getPreferenceStore();
}
/**
* Returns the displayed width of a string, taking in account the displayed tab width.
* The result can be compared against the print margin.
*/
private static int calculateDisplayedWidth(String string) {
final int tabWidth= getPreferenceStore().getInt(PreferenceConstants.EDITOR_TAB_WIDTH);
int column= 0;
for (int i= 0; i < string.length(); i++)
if ('\t' == string.charAt(i))
column += tabWidth - (column % tabWidth);
else
column++;
return column;
}
private String jdocExtractLinePrefix(IDocument d, int line) throws BadLocationException {
IRegion region= d.getLineInformation(line);
int lineOffset= region.getOffset();
int index= findEndOfWhiteSpace(d, lineOffset, lineOffset + d.getLineLength(line));
if (d.getChar(index) == '*') {
index++;
if (index != lineOffset + region.getLength() &&d.getChar(index) == ' ')
index++;
}
return d.get(lineOffset, index - lineOffset);
}
private String getLineContents(IDocument d, int line) throws BadLocationException {
int offset = d.getLineOffset(line);
int length = d.getLineLength(line);
String lineDelimiter= d.getLineDelimiter(line);
if (lineDelimiter != null)
length= length - lineDelimiter.length();
String lineContents = d.get(offset, length);
int trim = jdocExtractLinePrefix(d, line).length();
return lineContents.substring(trim);
}
private static String getLine(IDocument document, int line) throws BadLocationException {
IRegion region= document.getLineInformation(line);
return document.get(region.getOffset(), region.getLength());
}
/**
* Returns <code>true</code> if the javadoc line is too short, <code>false</code> otherwise.
*/
private boolean isLineTooShort(IDocument document, int line) throws BadLocationException {
if (!isJavaDocLine(document, line + 1))
return false;
String nextLine= getLineContents(document, line + 1);
if (nextLine.trim().length() == 0)
return false;
return true;
}
/**
* Returns <code>true</code> if the line is too long, <code>false</code> otherwise.
*/
private boolean isLineTooLong(IDocument document, int line) throws BadLocationException {
String lineContents= getLine(document, line);
return calculateDisplayedWidth(lineContents) > getMargin();
}
private static int getMargin() {
return getPreferenceStore().getInt(ExtendedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN);
}
private static final String[] fgInlineTags= {
"<b>", "<i>", "<em>", "<strong>", "<code>" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
};
private boolean isInlineTag(String string) {
for (int i= 0; i < fgInlineTags.length; i++)
if (string.startsWith(fgInlineTags[i]))
return true;
return false;
}
/**
* returns true if the specified line is part of a paragraph and should be merged with
* the previous line.
*/
private boolean isJavaDocLine(IDocument document, int line) throws BadLocationException {
if (document.getNumberOfLines() < line)
return false;
int offset= document.getLineOffset(line);
int length= document.getLineLength(line);
int firstChar= findEndOfWhiteSpace(document, offset, offset + length);
length -= firstChar - offset;
String lineContents= document.get(firstChar, length);
String prefix= lineContents.trim();
if (!prefix.startsWith("*") || prefix.startsWith("*/")) //$NON-NLS-1$ //$NON-NLS-2$
return false;
lineContents= lineContents.substring(1).trim().toLowerCase();
// preserve empty lines
if (lineContents.length() == 0)
return false;
// preserve @TAGS
if (lineContents.startsWith("@")) //$NON-NLS-1$
return false;
// preserve HTML tags which are not inline
if (lineContents.startsWith("<") && !isInlineTag(lineContents)) //$NON-NLS-1$
return false;
return true;
}
protected void jdocHandleBackspaceDelete(IDocument document, DocumentCommand c) {
if (!getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_FORMAT_JAVADOCS))
return;
try {
String text= document.get(c.offset, c.length);
int line= document.getLineOfOffset(c.offset);
int lineOffset= document.getLineOffset(line);
// erase line delimiter
String lineDelimiter= document.getLineDelimiter(line);
if (lineDelimiter != null && lineDelimiter.equals(text)) {
String prefix= jdocExtractLinePrefix(document, line + 1);
// strip prefix if any
if (prefix.length() > 0) {
int length= document.getLineDelimiter(line).length() + prefix.length();
document.replace(c.offset, length, null);
c.doit= false;
c.length= 0;
return;
}
// backspace: beginning of a javadoc line
} else if (document.getChar(c.offset - 1) == '*' && jdocExtractLinePrefix(document, line).length() - 1 >= c.offset - lineOffset) {
lineDelimiter= document.getLineDelimiter(line - 1);
String prefix= jdocExtractLinePrefix(document, line);
int length= (lineDelimiter != null ? lineDelimiter.length() : 0) + prefix.length();
document.replace(c.offset - length + 1, length, null);
c.doit= false;
c.offset -= length - 1;
c.length= 0;
return;
} else {
document.replace(c.offset, c.length, null);
c.doit= false;
c.length= 0;
}
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
try {
int line= document.getLineOfOffset(c.offset);
int lineOffset= document.getLineOffset(line);
String prefix= jdocExtractLinePrefix(document, line);
boolean always= c.offset > lineOffset && c.offset <= lineOffset + prefix.length();
int[] caretOffset= {c.offset};
jdocWrapParagraphFromLine(document, document.getLineOfOffset(c.offset), caretOffset, always);
c.offset= caretOffset[0];
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
}
/**
* Returns the compilation unit of the CompilationUnitEditor invoking the AutoIndentStrategy,
* might return <code>null</code> on error.
*/
private static ICompilationUnit getCompilationUnit() {
IWorkbenchWindow window= PlatformUI.getWorkbench().getActiveWorkbenchWindow();
if (window == null)
return null;
IWorkbenchPage page= window.getActivePage();
if (page == null)
return null;
IEditorPart editor= page.getActiveEditor();
if (editor == null)
return null;
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
ICompilationUnit unit= manager.getWorkingCopy(editor.getEditorInput());
if (unit == null)
return null;
return unit;
}
}
|
50,230 |
Bug 50230 Paste omits a character
|
20040119 - In the following text, double click on 'rel' to get the word selected. - CTRL + C - Set cursor between empty brackets, paste -> only pastes 'el', the letter 'r' is gone protected Object getAttribute(Object parent, int childProperty) { if (child instanceof List) { } else if (rel != null && !rel.equals(child)) { } else if () return child; }
|
verified fixed
|
df434eb
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-20T09:38:38Z | 2004-01-19T19:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/JavaAutoIndentStrategy.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Nikolay Metchev - Fixed bug 29909
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text.java;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DefaultAutoIndentStrategy;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.DocumentCommand;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.TextUtilities;
import org.eclipse.jface.text.rules.DefaultPartitioner;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.texteditor.ITextEditorExtension3;
import org.eclipse.jdt.core.ToolFactory;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.core.compiler.IScanner;
import org.eclipse.jdt.core.compiler.ITerminalSymbols;
import org.eclipse.jdt.core.compiler.InvalidInputException;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.DoStatement;
import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.ForStatement;
import org.eclipse.jdt.core.dom.IfStatement;
import org.eclipse.jdt.core.dom.Statement;
import org.eclipse.jdt.core.dom.WhileStatement;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.corext.Assert;
import org.eclipse.jdt.internal.corext.dom.NodeFinder;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.FastJavaPartitionScanner;
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.Symbols;
/**
* Auto indent strategy sensitive to brackets.
*/
public class JavaAutoIndentStrategy extends DefaultAutoIndentStrategy {
/** The line comment introducer. Value is "{@value}" */
private static final String LINE_COMMENT= "//"; //$NON-NLS-1$
private static class CompilationUnitInfo {
char[] buffer;
int delta;
CompilationUnitInfo(char[] buffer, int delta) {
this.buffer= buffer;
this.delta= delta;
}
}
private boolean fCloseBrace;
private boolean fIsSmartMode;
private String fPartitioning;
/**
* Creates a new Java auto indent strategy for the given document partitioning.
*
* @param partitioning the document partitioning
*/
public JavaAutoIndentStrategy(String partitioning) {
fPartitioning= partitioning;
}
private int getBracketCount(IDocument d, int startOffset, int endOffset, boolean ignoreCloseBrackets) throws BadLocationException {
int bracketCount= 0;
while (startOffset < endOffset) {
char curr= d.getChar(startOffset);
startOffset++;
switch (curr) {
case '/' :
if (startOffset < endOffset) {
char next= d.getChar(startOffset);
if (next == '*') {
// a comment starts, advance to the comment end
startOffset= getCommentEnd(d, startOffset + 1, endOffset);
} else if (next == '/') {
// '//'-comment: nothing to do anymore on this line
startOffset= endOffset;
}
}
break;
case '*' :
if (startOffset < endOffset) {
char next= d.getChar(startOffset);
if (next == '/') {
// we have been in a comment: forget what we read before
bracketCount= 0;
startOffset++;
}
}
break;
case '{' :
bracketCount++;
ignoreCloseBrackets= false;
break;
case '}' :
if (!ignoreCloseBrackets) {
bracketCount--;
}
break;
case '"' :
case '\'' :
startOffset= getStringEnd(d, startOffset, endOffset, curr);
break;
default :
}
}
return bracketCount;
}
// ----------- bracket counting ------------------------------------------------------
private int getCommentEnd(IDocument d, int offset, int endOffset) throws BadLocationException {
while (offset < endOffset) {
char curr= d.getChar(offset);
offset++;
if (curr == '*') {
if (offset < endOffset && d.getChar(offset) == '/') {
return offset + 1;
}
}
}
return endOffset;
}
private String getIndentOfLine(IDocument d, int line) throws BadLocationException {
if (line > -1) {
int start= d.getLineOffset(line);
int end= start + d.getLineLength(line) - 1;
int whiteEnd= findEndOfWhiteSpace(d, start, end);
return d.get(start, whiteEnd - start);
} else {
return ""; //$NON-NLS-1$
}
}
private int getStringEnd(IDocument d, int offset, int endOffset, char ch) throws BadLocationException {
while (offset < endOffset) {
char curr= d.getChar(offset);
offset++;
if (curr == '\\') {
// ignore escaped characters
offset++;
} else if (curr == ch) {
return offset;
}
}
return endOffset;
}
private void smartIndentAfterClosingBracket(IDocument d, DocumentCommand c) {
if (c.offset == -1 || d.getLength() == 0)
return;
try {
int p= (c.offset == d.getLength() ? c.offset - 1 : c.offset);
int line= d.getLineOfOffset(p);
int start= d.getLineOffset(line);
int whiteend= findEndOfWhiteSpace(d, start, c.offset);
JavaHeuristicScanner scanner= new JavaHeuristicScanner(d);
JavaIndenter indenter= new JavaIndenter(d, scanner);
// shift only when line does not contain any text up to the closing bracket
if (whiteend == c.offset) {
// evaluate the line with the opening bracket that matches out closing bracket
int reference= indenter.findReferencePosition(c.offset, false, true, false, false);
int indLine= d.getLineOfOffset(reference);
if (indLine != -1 && indLine != line) {
// take the indent of the found line
StringBuffer replaceText= new StringBuffer(getIndentOfLine(d, indLine));
// add the rest of the current line including the just added close bracket
replaceText.append(d.get(whiteend, c.offset - whiteend));
replaceText.append(c.text);
// modify document command
c.length += c.offset - start;
c.offset= start;
c.text= replaceText.toString();
}
}
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
}
private void smartIndentAfterOpeningBracket(IDocument d, DocumentCommand c) {
if (c.offset < 1 || d.getLength() == 0)
return;
JavaHeuristicScanner scanner= new JavaHeuristicScanner(d);
int p= (c.offset == d.getLength() ? c.offset - 1 : c.offset);
try {
// current line
int line= d.getLineOfOffset(p);
int lineOffset= d.getLineOffset(line);
// make sure we don't have any leading comments etc.
if (d.get(lineOffset, p - lineOffset).trim().length() != 0)
return;
// line of last javacode
int pos= scanner.findNonWhitespaceBackward(p, JavaHeuristicScanner.UNBOUND);
if (pos == -1)
return;
int lastLine= d.getLineOfOffset(pos);
// only shift if the last java line is further up and is a braceless block candidate
if (lastLine < line) {
JavaIndenter indenter= new JavaIndenter(d, scanner);
StringBuffer indent= indenter.computeIndentation(p, true);
if (indent != null) {
c.text= indent.append(c.text).toString();
c.length += c.offset - lineOffset;
c.offset= lineOffset;
}
}
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
}
private void smartIndentAfterNewLine(IDocument d, DocumentCommand c) {
JavaHeuristicScanner scanner= new JavaHeuristicScanner(d);
JavaIndenter indenter= new JavaIndenter(d, scanner);
StringBuffer indent= indenter.computeIndentation(c.offset);
if (indent == null)
indent= new StringBuffer(); //$NON-NLS-1$
int docLength= d.getLength();
if (c.offset == -1 || docLength == 0)
return;
try {
int p= (c.offset == docLength ? c.offset - 1 : c.offset);
int line= d.getLineOfOffset(p);
StringBuffer buf= new StringBuffer(c.text + indent);
IRegion reg= d.getLineInformation(line);
int lineEnd= reg.getOffset() + reg.getLength();
int contentStart= findEndOfWhiteSpace(d, c.offset, lineEnd);
c.length= Math.max(contentStart - c.offset, 0);
int start= reg.getOffset();
ITypedRegion region= TextUtilities.getPartition(d, fPartitioning, start);
if (IJavaPartitions.JAVA_DOC.equals(region.getType()))
start= d.getLineInformationOfOffset(region.getOffset()).getOffset();
if (getBracketCount(d, start, c.offset, true) > 0 && closeBrace() && !isClosed(d, c.offset, c.length)) {
c.caretOffset= c.offset + buf.length();
c.shiftsCaret= false;
// copy old content of line behind insertion point to new line
// unless we think we are inserting an anonymous type definition
if (c.offset == 0 || !(computeAnonymousPosition(d, c.offset - 1, fPartitioning, lineEnd) != -1)) {
if (lineEnd - contentStart > 0) {
c.length= lineEnd - c.offset;
buf.append(d.get(contentStart, lineEnd - contentStart).toCharArray());
}
}
buf.append(getLineDelimiter(d));
StringBuffer reference= indenter.getReferenceIndentation(c.offset);
if (reference != null)
buf.append(reference);
buf.append('}');
}
c.text= buf.toString();
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
}
/**
* Computes an insert position for an opening brace if <code>offset</code> maps to a position in
* <code>document</code> with a expression in parenthesis that will take a block after the closing parenthesis.
*
* @param document the document being modified
* @param offset the offset of the caret position, relative to the line start.
* @param partitioning the document partitioning
* @param max the max position
* @return an insert position relative to the line start if <code>line</code> contains a parenthesized expression that can be followed by a block, -1 otherwise
*/
private static int computeAnonymousPosition(IDocument document, int offset, String partitioning, int max) {
// find the opening parenthesis for every closing parenthesis on the current line after offset
// return the position behind the closing parenthesis if it looks like a method declaration
// or an expression for an if, while, for, catch statement
JavaHeuristicScanner scanner= new JavaHeuristicScanner(document);
int pos= offset;
int length= max;
int scanTo= scanner.scanForward(pos, length, '}');
if (scanTo == -1)
scanTo= length;
int closingParen= findClosingParenToLeft(scanner, pos) - 1;
while (true) {
int startScan= closingParen + 1;
closingParen= scanner.scanForward(startScan, scanTo, ')');
if (closingParen == -1)
break;
int openingParen= scanner.findOpeningPeer(closingParen - 1, '(', ')');
// no way an expression at the beginning of the document can mean anything
if (openingParen < 1)
break;
// only select insert positions for parenthesis currently embracing the caret
if (openingParen > pos)
continue;
if (looksLikeAnonymousClassDef(document, partitioning, scanner, openingParen - 1))
return closingParen + 1;
}
return -1;
}
/**
* Finds a closing parenthesis to the left of <code>position</code> in document, where that parenthesis is only
* separated by whitespace from <code>position</code>. If no such parenthesis can be found, <code>position</code> is returned.
*
* @param document the document being modified
* @param position the first character position in <code>document</code> to be considered
* @param partitioning the document partitioning
* @return the position of a closing parenthesis left to <code>position</code> separated only by whitespace, or <code>position</code> if no parenthesis can be found
*/
private static int findClosingParenToLeft(JavaHeuristicScanner scanner, int position) {
if (position < 1)
return position;
if (scanner.previousToken(position - 1, JavaHeuristicScanner.UNBOUND) == Symbols.TokenRPAREN)
return scanner.getPosition() + 1;
return position;
}
/**
* Checks whether the content of <code>document</code> in the range (<code>offset</code>, <code>length</code>)
* contains the <code>new</code> keyword.
*
* @param document the document being modified
* @param offset the first character position in <code>document</code> to be considered
* @param length the length of the character range to be considered
* @param partitioning the document partitioning
* @return <code>true</code> if the specified character range contains a <code>new</code> keyword, <code>false</code> otherwise.
*/
private static boolean isNewMatch(IDocument document, int offset, int length, String partitioning) {
Assert.isTrue(length >= 0);
Assert.isTrue(offset >= 0);
Assert.isTrue(offset + length < document.getLength() + 1);
try {
String text= document.get(offset, length);
int pos= text.indexOf("new"); //$NON-NLS-1$
while (pos != -1 && !isDefaultPartition(document, pos + offset, partitioning))
pos= text.indexOf("new", pos + 2); //$NON-NLS-1$
if (pos < 0)
return false;
if (pos != 0 && Character.isJavaIdentifierPart(text.charAt(pos - 1)))
return false;
if (pos + 3 < length && Character.isJavaIdentifierPart(text.charAt(pos + 3)))
return false;
return true;
} catch (BadLocationException e) {
}
return false;
}
/**
* Checks whether the content of <code>document</code> at <code>position</code> looks like an
* anonymous class definition. <code>position</code> must be to the left of the opening
* parenthesis of the definition's parameter list.
*
* @param document the document being modified
* @param position the first character position in <code>document</code> to be considered
* @param partitioning the document partitioning
* @return <code>true</code> if the content of <code>document</code> looks like an anonymous class definition, <code>false</code> otherwise
*/
private static boolean looksLikeAnonymousClassDef(IDocument document, String partitioning, JavaHeuristicScanner scanner, int position) {
int previousCommaOrParen= scanner.scanBackward(position - 1, JavaHeuristicScanner.UNBOUND, new char[] {',', '('});
if (previousCommaOrParen == -1 || position < previousCommaOrParen + 5) // 2 for borders, 3 for "new"
return false;
if (isNewMatch(document, previousCommaOrParen + 1, position - previousCommaOrParen - 2, partitioning))
return true;
return false;
}
/**
* Checks whether <code>position</code> resides in a default (Java) partition of <code>document</code>.
*
* @param document the document being modified
* @param position the position to be checked
* @param partitioning the document partitioning
* @return <code>true</code> if <code>position</code> is in the default partition of <code>document</code>, <code>false</code> otherwise
*/
private static boolean isDefaultPartition(IDocument document, int position, String partitioning) {
Assert.isTrue(position >= 0);
Assert.isTrue(position <= document.getLength());
try {
ITypedRegion region= TextUtilities.getPartition(document, partitioning, position);
return region.getType().equals(IDocument.DEFAULT_CONTENT_TYPE);
} catch (BadLocationException e) {
}
return false;
}
private boolean isClosed(IDocument document, int offset, int length) {
CompilationUnitInfo info= getCompilationUnitForMethod(document, offset, fPartitioning);
if (info == null)
return false;
CompilationUnit compilationUnit= null;
try {
compilationUnit= AST.parseCompilationUnit(info.buffer);
} catch (ArrayIndexOutOfBoundsException x) {
// work around for parser problem
return false;
}
IProblem[] problems= compilationUnit.getProblems();
for (int i= 0; i != problems.length; ++i) {
if (problems[i].getID() == IProblem.UnmatchedBracket)
return true;
}
final int relativeOffset= offset - info.delta;
ASTNode node= NodeFinder.perform(compilationUnit, relativeOffset, length);
if (node == null)
return false;
if (length == 0) {
while (node != null && (relativeOffset == node.getStartPosition() || relativeOffset == node.getStartPosition() + node.getLength()))
node= node.getParent();
}
switch (node.getNodeType()) {
case ASTNode.BLOCK:
return areBlocksConsistent(document, offset, fPartitioning);
case ASTNode.IF_STATEMENT:
{
IfStatement ifStatement= (IfStatement) node;
Expression expression= ifStatement.getExpression();
IRegion expressionRegion= createRegion(expression, info.delta);
Statement thenStatement= ifStatement.getThenStatement();
IRegion thenRegion= createRegion(thenStatement, info.delta);
// between expression and then statement
if (expressionRegion.getOffset() + expressionRegion.getLength() <= offset && offset + length <= thenRegion.getOffset())
return thenStatement != null;
Statement elseStatement= ifStatement.getElseStatement();
IRegion elseRegion= createRegion(elseStatement, info.delta);
IRegion elseToken= null;
if (elseStatement != null) {
int sourceOffset= thenRegion.getOffset() + thenRegion.getLength();
int sourceLength= elseRegion.getOffset() - sourceOffset;
elseToken= getToken(document, new Region(sourceOffset, sourceLength), ITerminalSymbols.TokenNameelse);
}
// between 'else' keyword and else statement
if (elseToken.getOffset() + elseToken.getLength() <= offset && offset + length < elseRegion.getOffset())
return elseStatement != null;
}
break;
case ASTNode.WHILE_STATEMENT:
case ASTNode.FOR_STATEMENT:
{
Expression expression= node.getNodeType() == ASTNode.WHILE_STATEMENT ? ((WhileStatement) node).getExpression() : ((ForStatement) node).getExpression();
IRegion expressionRegion= createRegion(expression, info.delta);
Statement body= node.getNodeType() == ASTNode.WHILE_STATEMENT ? ((WhileStatement) node).getBody() : ((ForStatement) node).getBody();
IRegion bodyRegion= createRegion(body, info.delta);
// between expression and body statement
if (expressionRegion.getOffset() + expressionRegion.getLength() <= offset && offset + length <= bodyRegion.getOffset())
return body != null;
}
break;
case ASTNode.DO_STATEMENT:
{
DoStatement doStatement= (DoStatement) node;
IRegion doRegion= createRegion(doStatement, info.delta);
Statement body= doStatement.getBody();
IRegion bodyRegion= createRegion(body, info.delta);
if (doRegion.getOffset() + doRegion.getLength() <= offset && offset + length <= bodyRegion.getOffset())
return body != null;
}
break;
}
return true;
}
private static String getLineDelimiter(IDocument document) {
try {
if (document.getNumberOfLines() > 1)
return document.getLineDelimiter(0);
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
return System.getProperty("line.separator"); //$NON-NLS-1$
}
/**
* Installs a java partitioner with <code>document</code>.
*
* @param document the document
*/
private static void installJavaStuff(Document document) {
String[] types= new String[] {
IJavaPartitions.JAVA_DOC,
IJavaPartitions.JAVA_MULTI_LINE_COMMENT,
IJavaPartitions.JAVA_SINGLE_LINE_COMMENT,
IJavaPartitions.JAVA_STRING,
IJavaPartitions.JAVA_CHARACTER,
IDocument.DEFAULT_CONTENT_TYPE
};
DefaultPartitioner partitioner= new DefaultPartitioner(new FastJavaPartitionScanner(), types);
partitioner.connect(document);
document.setDocumentPartitioner(IJavaPartitions.JAVA_PARTITIONING, partitioner);
}
private static void smartPaste(IDocument document, DocumentCommand command) {
try {
JavaHeuristicScanner scanner= new JavaHeuristicScanner(document);
JavaIndenter indenter= new JavaIndenter(document, scanner);
int offset= command.offset;
// reference position to get the indent from
int refOffset= indenter.findReferencePosition(offset);
if (refOffset == JavaHeuristicScanner.NOT_FOUND)
return;
int peerOffset= getPeerPosition(document, command);
peerOffset= indenter.findReferencePosition(peerOffset);
refOffset= Math.min(refOffset, peerOffset);
// eat any WS before the insertion to the beginning of the line
IRegion line= document.getLineInformationOfOffset(offset);
String notSelected= document.get(line.getOffset(), offset - line.getOffset());
if (notSelected.trim().length() == 0) {
command.length += notSelected.length();
command.offset= line.getOffset();
}
// prefix: the part we need for formatting but won't paste
IRegion refLine= document.getLineInformationOfOffset(refOffset);
String prefix= document.get(refLine.getOffset(), command.offset - refLine.getOffset());
// handle the indentation computation inside a temporary document
Document temp= new Document(prefix + command.text);
scanner= new JavaHeuristicScanner(temp);
indenter= new JavaIndenter(temp, scanner);
installJavaStuff(temp);
// indent the first and second line
// compute the relative indentation difference from the second line
// (as the first might be partially selected) and use the value to
// indent all other lines.
boolean isIndentDetected= false;
StringBuffer addition= new StringBuffer();
int insertLength= 0;
int first= document.computeNumberOfLines(prefix);
int lines= temp.getNumberOfLines();
for (int l= first; l < lines; l++) { // we don't change the number of lines while adding indents
IRegion r= temp.getLineInformation(l);
int lineOffset= r.getOffset();
int lineLength= r.getLength();
if (lineLength == 0) // don't modify empty lines
continue;
if (!isIndentDetected){
// indent the first pasted line
String current= getCurrentIndent(temp, l);
StringBuffer correct= indenter.computeIndentation(lineOffset);
if (correct == null)
return; // bail out
insertLength= subtractIndent(correct, current, addition);
if (l != first)
isIndentDetected= true;
}
// relatively indent all pasted lines
if (insertLength > 0)
addIndent(temp, l, addition);
else if (insertLength < 0)
cutIndent(temp, l, -insertLength);
}
// modify the command
command.text= temp.get(prefix.length(), temp.getLength() - prefix.length());
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
}
/**
* Returns the indentation of the line <code>line</code> in <code>document</code>.
* The returned string may contain pairs of leading slashes that are considered
* part of the indentation. The space before the asterix in a javadoc-like
* comment is not considered part of the indentation.
*
* @param document the document
* @param line the line
* @return the indentation of <code>line</code> in <code>document</code>
* @throws BadLocationException if the document is changed concurrently
*/
private static String getCurrentIndent(Document document, int line) throws BadLocationException {
IRegion region= document.getLineInformation(line);
int from= region.getOffset();
int endOffset= region.getOffset() + region.getLength();
// go behind line comments
int to= from;
while (to < endOffset - 2 && document.get(to, 2).equals(LINE_COMMENT))
to += 2;
while (to < endOffset) {
char ch= document.getChar(to);
if (!Character.isWhitespace(ch))
break;
to++;
}
// don't count the space before javadoc like, asterix-style comment lines
if (to > from && to < endOffset - 1 && document.get(to - 1, 2).equals(" *")) { //$NON-NLS-1$
String type= TextUtilities.getContentType(document, IJavaPartitions.JAVA_PARTITIONING, to);
if (type.equals(IJavaPartitions.JAVA_DOC) || type.equals(IJavaPartitions.JAVA_MULTI_LINE_COMMENT))
to--;
}
return document.get(from, to - from);
}
/**
* Computes the difference of two indentations and returns the difference in
* length of current and correct. If the return value is positive, <code>addition</code>
* is initialized with a substring of that length of <code>correct</code>.
*
* @param correct the correct indentation
* @param current the current indentation (migth contain non-whitespace)
* @param difference a string buffer - if the return value is positive, it will be cleared and set to the substring of <code>current</code> of that length
* @return the difference in lenght of <code>correct</code> and <code>current</code>
*/
private static int subtractIndent(CharSequence correct, CharSequence current, StringBuffer difference) {
int c1= computeVisualLength(correct);
int c2= computeVisualLength(current);
int diff= c1 - c2;
if (diff <= 0)
return diff;
difference.setLength(0);
int len= 0, i= 0;
while (len < diff) {
char c= correct.charAt(i++);
difference.append(c);
len += computeVisualLength(c);
}
return diff;
}
/**
* Indents line <code>line</code> in <code>document</code> with <code>indent</code>.
* Leaves leading comment signs alone.
*
* @param document the document
* @param line the line
* @param indent the indentation to insert
* @throws BadLocationException on concurrent document modification
*/
private static void addIndent(Document document, int line, CharSequence indent) throws BadLocationException {
IRegion region= document.getLineInformation(line);
int insert= region.getOffset();
int endOffset= region.getOffset() + region.getLength();
// go behind line comments
while (insert < endOffset - 2 && document.get(insert, 2).equals(LINE_COMMENT))
insert += 2;
// insert indent
document.replace(insert, 0, indent.toString());
}
/**
* Cuts the visual equivalent of <code>toDelete</code> characters out of the
* indentation of line <code>line</code> in <code>document</code>. Leaves
* leading comment signs alone.
*
* @param document the document
* @param line the line
* @param toDelete the number of space equivalents to delete.
* @throws BadLocationException on concurrent document modification
*/
private static void cutIndent(Document document, int line, int toDelete) throws BadLocationException {
IRegion region= document.getLineInformation(line);
int from= region.getOffset();
int endOffset= region.getOffset() + region.getLength();
// go behind line comments
while (from < endOffset - 2 && document.get(from, 2).equals(LINE_COMMENT))
from += 2;
int to= from;
while (toDelete > 0 && to < endOffset) {
char ch= document.getChar(to);
if (!Character.isWhitespace(ch))
break;
toDelete -= computeVisualLength(ch);
to++;
}
document.replace(from, to - from, null);
}
/**
* Returns the visual length of a given <code>CharSequence</code> taking into
* account the visual tabulator length.
*
* @param seq the string to measure
* @return the visual length of <code>seq</code>
*/
private static int computeVisualLength(CharSequence seq) {
int size= 0;
int tablen= getVisualTabLengthPreference();
for (int i= 0; i < seq.length(); i++) {
char ch= seq.charAt(i);
if (ch == '\t')
size += tablen - size % tablen;
else
size++;
}
return size;
}
/**
* Returns the visual length of a given character taking into
* account the visual tabulator length.
*
* @param ch the character to measure
* @return the visual length of <code>ch</code>
*/
private static int computeVisualLength(char ch) {
if (ch == '\t')
return getVisualTabLengthPreference();
else
return 1;
}
/**
* The preference setting for the visual tabulator display.
*
* @return the number of spaces displayed for a tabulator in the editor
*/
private static int getVisualTabLengthPreference() {
return JavaPlugin.getDefault().getPreferenceStore().getInt(PreferenceConstants.EDITOR_TAB_WIDTH);
}
private static int getPeerPosition(IDocument document, DocumentCommand command) {
/*
* Search for scope closers in the pasted text and find their opening peers
* in the document.
*/
Document pasted= new Document(command.text);
installJavaStuff(pasted);
int firstPeer= command.offset;
JavaHeuristicScanner pScanner= new JavaHeuristicScanner(pasted);
JavaHeuristicScanner dScanner= new JavaHeuristicScanner(document);
// add scope relevant after context to peer search
int afterToken= dScanner.nextToken(command.offset + command.length, JavaHeuristicScanner.UNBOUND);
try {
switch (afterToken) {
case Symbols.TokenRBRACE:
pasted.replace(pasted.getLength(), 0, "}"); //$NON-NLS-1$
break;
case Symbols.TokenRPAREN:
pasted.replace(pasted.getLength(), 0, ")"); //$NON-NLS-1$
break;
case Symbols.TokenRBRACKET:
pasted.replace(pasted.getLength(), 0, "]"); //$NON-NLS-1$
break;
}
} catch (BadLocationException e) {
// cannot happen
Assert.isTrue(false);
}
int pPos= 0; // paste text position (increasing from 0)
int dPos= Math.max(0, command.offset - 1); // document position (decreasing from paste offset)
while (true) {
int token= pScanner.nextToken(pPos, JavaHeuristicScanner.UNBOUND);
pPos= pScanner.getPosition();
switch (token) {
case Symbols.TokenLBRACE:
case Symbols.TokenLBRACKET:
case Symbols.TokenLPAREN:
pPos= skipScope(pScanner, pPos, token);
if (pPos == JavaHeuristicScanner.NOT_FOUND)
return firstPeer;
break; // closed scope -> keep searching
case Symbols.TokenRBRACE:
int peer= dScanner.findOpeningPeer(dPos, '{', '}');
dPos= peer - 1;
if (peer == JavaHeuristicScanner.NOT_FOUND)
return firstPeer;
firstPeer= peer;
break; // keep searching
case Symbols.TokenRBRACKET:
peer= dScanner.findOpeningPeer(dPos, '[', ']');
dPos= peer - 1;
if (peer == JavaHeuristicScanner.NOT_FOUND)
return firstPeer;
firstPeer= peer;
break; // keep searching
case Symbols.TokenRPAREN:
peer= dScanner.findOpeningPeer(dPos, '(', ')');
dPos= peer - 1;
if (peer == JavaHeuristicScanner.NOT_FOUND)
return firstPeer;
firstPeer= peer;
break; // keep searching
case Symbols.TokenCASE:
case Symbols.TokenDEFAULT:
JavaIndenter indenter= new JavaIndenter(document, dScanner);
peer= indenter.findReferencePosition(dPos, false, false, false, true);
if (peer == JavaHeuristicScanner.NOT_FOUND)
return firstPeer;
firstPeer= peer;
break; // keep searching
case Symbols.TokenEOF:
return firstPeer;
default:
// keep searching
}
}
}
/**
* Skips the scope opened by <code>token</code> in <code>document</code>,
* returns either the position of the
* @param pos
* @param token
* @return
*/
private static int skipScope(JavaHeuristicScanner scanner, int pos, int token) {
int openToken= token;
int closeToken;
switch (token) {
case Symbols.TokenLPAREN:
closeToken= Symbols.TokenRPAREN;
break;
case Symbols.TokenLBRACKET:
closeToken= Symbols.TokenRBRACKET;
break;
case Symbols.TokenLBRACE:
closeToken= Symbols.TokenRBRACE;
break;
default:
Assert.isTrue(false);
return -1; // dummy
}
int depth= 1;
int p= pos;
while (true) {
int tok= scanner.nextToken(p, JavaHeuristicScanner.UNBOUND);
p= scanner.getPosition();
if (tok == openToken) {
depth++;
} else if (tok == closeToken) {
depth--;
if (depth == 0)
return p + 1;
} else if (tok == Symbols.TokenEOF) {
return JavaHeuristicScanner.NOT_FOUND;
}
}
}
private boolean isLineDelimiter(IDocument document, String text) {
String[] delimiters= document.getLegalLineDelimiters();
if (delimiters != null)
return TextUtilities.equals(delimiters, text) > -1;
return false;
}
private void smartIndentAfterBlockDelimiter(IDocument document, DocumentCommand command) {
if (command.text.charAt(0) == '}')
smartIndentAfterClosingBracket(document, command);
else if (command.text.charAt(0) == '{')
smartIndentAfterOpeningBracket(document, command);
}
/*
* @see org.eclipse.jface.text.IAutoIndentStrategy#customizeDocumentCommand(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.DocumentCommand)
*/
public void customizeDocumentCommand(IDocument d, DocumentCommand c) {
if (c.doit == false)
return;
clearCachedValues();
if (!isSmartMode()) {
super.customizeDocumentCommand(d, c);
return;
}
if (c.length == 0 && c.text != null && isLineDelimiter(d, c.text))
smartIndentAfterNewLine(d, c);
else if (c.text.length() == 1)
smartIndentAfterBlockDelimiter(d, c);
else if (c.text.length() > 1 && getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SMART_PASTE))
smartPaste(d, c);
}
private static IPreferenceStore getPreferenceStore() {
return JavaPlugin.getDefault().getPreferenceStore();
}
private boolean closeBrace() {
return fCloseBrace;
}
private boolean isSmartMode() {
return fIsSmartMode;
}
private void clearCachedValues() {
IPreferenceStore preferenceStore= getPreferenceStore();
fCloseBrace= preferenceStore.getBoolean(PreferenceConstants.EDITOR_CLOSE_BRACES);
fIsSmartMode= computeSmartMode();
}
private boolean computeSmartMode() {
IWorkbenchPage page= JavaPlugin.getActivePage();
if (page != null) {
IEditorPart part= page.getActiveEditor();
if (part instanceof ITextEditorExtension3) {
ITextEditorExtension3 extension= (ITextEditorExtension3) part;
return extension.getInsertMode() == ITextEditorExtension3.SMART_INSERT;
}
}
return false;
}
private static CompilationUnitInfo getCompilationUnitForMethod(IDocument document, int offset, String partitioning) {
try {
JavaHeuristicScanner scanner= new JavaHeuristicScanner(document);
IRegion sourceRange= scanner.findSurroundingBlock(offset);
if (sourceRange == null)
return null;
String source= document.get(sourceRange.getOffset(), sourceRange.getLength());
StringBuffer contents= new StringBuffer();
contents.append("class ____C{void ____m()"); //$NON-NLS-1$
final int methodOffset= contents.length();
contents.append(source);
contents.append('}');
char[] buffer= contents.toString().toCharArray();
return new CompilationUnitInfo(buffer, sourceRange.getOffset() - methodOffset);
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
return null;
}
private static boolean areBlocksConsistent(IDocument document, int offset, String partitioning) {
if (offset < 1 || offset >= document.getLength())
return false;
int begin= offset;
int end= offset - 1;
JavaHeuristicScanner scanner= new JavaHeuristicScanner(document);
while (true) {
begin= scanner.findOpeningPeer(begin - 1, '{', '}');
end= scanner.findClosingPeer(end + 1, '{', '}');
if (begin == -1 && end == -1)
return true;
if (begin == -1 || end == -1)
return false;
}
}
private static IRegion createRegion(ASTNode node, int delta) {
return node == null ? null : new Region(node.getStartPosition() + delta, node.getLength());
}
private static IRegion getToken(IDocument document, IRegion scanRegion, int tokenId) {
try {
final String source= document.get(scanRegion.getOffset(), scanRegion.getLength());
IScanner scanner= ToolFactory.createScanner(false, false, false, false);
scanner.setSource(source.toCharArray());
int id= scanner.getNextToken();
while (id != ITerminalSymbols.TokenNameEOF && id != tokenId)
id= scanner.getNextToken();
if (id == ITerminalSymbols.TokenNameEOF)
return null;
int tokenOffset= scanner.getCurrentTokenStartPosition();
int tokenLength= scanner.getCurrentTokenEndPosition() + 1 - tokenOffset; // inclusive end
return new Region(tokenOffset + scanRegion.getOffset(), tokenLength);
} catch (InvalidInputException x) {
return null;
} catch (BadLocationException x) {
return null;
}
}
}
|
6,579 |
Bug 6579 Packages view: can't open MANIFEST.MF of JAR file
|
1. Drill into a JAR with a manifest file (MANIFEST.MF) in the Packages view. Note: The JAR must be on the build path. 2. Double-click MANIFEST.MF -> nothing happens 3. From the context menu select "Open" -> nothing happens I used ant.jar in org.eclipse.ant.core as my test case.
|
resolved fixed
|
c4846da
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-20T18:04:24Z | 2001-12-05T08:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/EditorUtility.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 org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IStorage;
import org.eclipse.swt.SWT;
import org.eclipse.jface.action.Action;
import org.eclipse.ui.IEditorDescriptor;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorRegistry;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
/**
* A number of routines for working with JavaElements in editors
*
* Use 'isOpenInEditor' to test if an element is already open in a editor
* Use 'openInEditor' to force opening an element in a editor
* With 'getWorkingCopy' you get the working copy (element in the editor) of an element
*/
public class EditorUtility {
public static boolean isEditorInput(Object element, IEditorPart editor) {
if (editor != null) {
try {
return editor.getEditorInput().equals(getEditorInput(element));
} catch (JavaModelException x) {
JavaPlugin.log(x.getStatus());
}
}
return false;
}
/**
* Tests if a cu is currently shown in an editor
* @return the IEditorPart if shown, null if element is not open in an editor
*/
public static IEditorPart isOpenInEditor(Object inputElement) {
IEditorInput input= null;
try {
input= getEditorInput(inputElement);
} catch (JavaModelException x) {
JavaPlugin.log(x.getStatus());
}
if (input != null) {
IWorkbenchPage p= JavaPlugin.getActivePage();
if (p != null) {
return p.findEditor(input);
}
}
return null;
}
/**
* Opens a Java editor for an element such as <code>IJavaElement</code>, <code>IFile</code>, or <code>IStorage</code>.
* The editor is activated by default.
* @return the IEditorPart or null if wrong element type or opening failed
*/
public static IEditorPart openInEditor(Object inputElement) throws JavaModelException, PartInitException {
return openInEditor(inputElement, true);
}
/**
* Opens a Java editor for an element (IJavaElement, IFile, IStorage...)
* @return the IEditorPart or null if wrong element type or opening failed
*/
public static IEditorPart openInEditor(Object inputElement, boolean activate) throws JavaModelException, PartInitException {
if (inputElement instanceof IFile)
return openInEditor((IFile) inputElement, activate);
IEditorInput input= getEditorInput(inputElement);
if (input instanceof IFileEditorInput) {
IFileEditorInput fileInput= (IFileEditorInput) input;
return openInEditor(fileInput.getFile(), activate);
}
if (input != null)
return openInEditor(input, getEditorID(input, inputElement), activate);
return null;
}
/**
* Selects a Java Element in an editor
*/
public static void revealInEditor(IEditorPart part, IJavaElement element) {
if (element != null && part instanceof JavaEditor) {
((JavaEditor) part).setSelection(element);
}
}
private static IEditorPart openInEditor(IFile file, boolean activate) throws PartInitException {
if (file != null) {
IWorkbenchPage p= JavaPlugin.getActivePage();
if (p != null) {
IEditorPart editorPart= IDE.openEditor(p, file, activate);
initializeHighlightRange(editorPart);
return editorPart;
}
}
return null;
}
private static IEditorPart openInEditor(IEditorInput input, String editorID, boolean activate) throws PartInitException {
if (input != null) {
IWorkbenchPage p= JavaPlugin.getActivePage();
if (p != null) {
IEditorPart editorPart= p.openEditor(input, editorID, activate);
initializeHighlightRange(editorPart);
return editorPart;
}
}
return null;
}
private static void initializeHighlightRange(IEditorPart editorPart) {
if (editorPart instanceof ITextEditor) {
TogglePresentationAction toggleAction= new TogglePresentationAction();
// Initialize editor
toggleAction.setEditor((ITextEditor)editorPart);
// Reset action
toggleAction.setEditor(null);
}
}
/**
*@deprecated Made it public again for java debugger UI.
*/
public static String getEditorID(IEditorInput input, Object inputObject) {
IEditorRegistry registry= PlatformUI.getWorkbench().getEditorRegistry();
IEditorDescriptor descriptor= registry.getDefaultEditor(input.getName());
if (descriptor != null)
return descriptor.getId();
return null;
}
private static IEditorInput getEditorInput(IJavaElement element) throws JavaModelException {
while (element != null) {
if (element instanceof ICompilationUnit) {
ICompilationUnit unit= JavaModelUtil.toOriginal((ICompilationUnit) element);
IResource resource= unit.getResource();
if (resource instanceof IFile)
return new FileEditorInput((IFile) resource);
}
if (element instanceof IClassFile)
return new InternalClassFileEditorInput((IClassFile) element);
element= element.getParent();
}
return null;
}
public static IEditorInput getEditorInput(Object input) throws JavaModelException {
if (input instanceof IJavaElement)
return getEditorInput((IJavaElement) input);
if (input instanceof IFile)
return new FileEditorInput((IFile) input);
if (input instanceof IStorage)
return new JarEntryEditorInput((IStorage)input);
return null;
}
/**
* If the current active editor edits a java element return it, else
* return null
*/
public static IJavaElement getActiveEditorJavaInput() {
IWorkbenchPage page= JavaPlugin.getActivePage();
if (page != null) {
IEditorPart part= page.getActiveEditor();
if (part != null) {
IEditorInput editorInput= part.getEditorInput();
if (editorInput != null) {
return (IJavaElement)editorInput.getAdapter(IJavaElement.class);
}
}
}
return null;
}
/**
* Gets the working copy of an compilation unit opened in an editor
* @param part the editor part
* @param cu the original compilation unit (or another working copy)
* @return the working copy of the compilation unit, or null if not found
*/
public static ICompilationUnit getWorkingCopy(ICompilationUnit cu) {
if (cu == null)
return null;
if (cu.isWorkingCopy())
return cu;
return (ICompilationUnit)cu.findSharedWorkingCopy(JavaUI.getBufferFactory());
}
/**
* Gets the working copy of an member opened in an editor
*
* @param member the original member or a member in a working copy
* @return the corresponding member in the shared working copy or <code>null</code> if not found
*/
public static IMember getWorkingCopy(IMember member) throws JavaModelException {
ICompilationUnit cu= member.getCompilationUnit();
if (cu != null) {
ICompilationUnit workingCopy= getWorkingCopy(cu);
if (workingCopy != null) {
return JavaModelUtil.findMemberInCompilationUnit(workingCopy, member);
}
}
return null;
}
/**
* Returns the compilation unit for the given java element.
* @param element the java element whose compilation unit is searched for
* @return the compilation unit of the given java element
*/
private static ICompilationUnit getCompilationUnit(IJavaElement element) {
if (element == null)
return null;
if (element instanceof IMember)
return ((IMember) element).getCompilationUnit();
int type= element.getElementType();
if (IJavaElement.COMPILATION_UNIT == type)
return (ICompilationUnit) element;
if (IJavaElement.CLASS_FILE == type)
return null;
return getCompilationUnit(element.getParent());
}
/**
* Returns the working copy of the given java element.
* @param javaElement the javaElement for which the working copyshould be found
* @param reconcile indicates whether the working copy must be reconcile prior to searching it
* @return the working copy of the given element or <code>null</code> if none
*/
public static IJavaElement getWorkingCopy(IJavaElement element, boolean reconcile) throws JavaModelException {
ICompilationUnit unit= getCompilationUnit(element);
if (unit == null)
return null;
if (unit.isWorkingCopy())
return element;
ICompilationUnit workingCopy= getWorkingCopy(unit);
if (workingCopy != null) {
if (reconcile) {
synchronized (workingCopy) {
workingCopy.reconcile();
return JavaModelUtil.findInCompilationUnit(workingCopy, element);
}
} else {
return JavaModelUtil.findInCompilationUnit(workingCopy, element);
}
}
return null;
}
/**
* Maps the localized modifier name to a code in the same
* manner as #findModifier.
*
* @return the SWT modifier bit, or <code>0</code> if no match was found
* @see findModifier
* @since 2.1.1
*/
public static int findLocalizedModifier(String token) {
if (token == null)
return 0;
if (token.equalsIgnoreCase(Action.findModifierString(SWT.CTRL)))
return SWT.CTRL;
if (token.equalsIgnoreCase(Action.findModifierString(SWT.SHIFT)))
return SWT.SHIFT;
if (token.equalsIgnoreCase(Action.findModifierString(SWT.ALT)))
return SWT.ALT;
if (token.equalsIgnoreCase(Action.findModifierString(SWT.COMMAND)))
return SWT.COMMAND;
return 0;
}
/**
* Returns the modifier string for the given SWT modifier
* modifier bits.
*
* @param stateMask the SWT modifier bits
* @return the modifier string
* @since 2.1.1
*/
public static String getModifierString(int stateMask) {
String modifierString= ""; //$NON-NLS-1$
if ((stateMask & SWT.CTRL) == SWT.CTRL)
modifierString= appendModifierString(modifierString, SWT.CTRL);
if ((stateMask & SWT.ALT) == SWT.ALT)
modifierString= appendModifierString(modifierString, SWT.ALT);
if ((stateMask & SWT.SHIFT) == SWT.SHIFT)
modifierString= appendModifierString(modifierString, SWT.SHIFT);
if ((stateMask & SWT.COMMAND) == SWT.COMMAND)
modifierString= appendModifierString(modifierString, SWT.COMMAND);
return modifierString;
}
/**
* Appends to modifier string of the given SWT modifier bit
* to the given modifierString.
*
* @param modifierString the modifier string
* @param modifier an int with SWT modifier bit
* @return the concatenated modifier string
* @since 2.1.1
*/
private static String appendModifierString(String modifierString, int modifier) {
if (modifierString == null)
modifierString= ""; //$NON-NLS-1$
String newModifierString= Action.findModifierString(modifier);
if (modifierString.length() == 0)
return newModifierString;
return JavaEditorMessages.getFormattedString("EditorUtility.concatModifierStrings", new String[] {modifierString, newModifierString}); //$NON-NLS-1$
}
}
|
42,233 |
Bug 42233 JUnit code generated for TestSuite is wrong [JUnit]
| null |
resolved fixed
|
9a55400
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-22T23:17:38Z | 2003-08-28T19:46:40Z |
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/wizards/MethodStubsSelectionButtonGroup.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.junit.wizards;
import org.eclipse.jdt.internal.junit.util.*;
import org.eclipse.jface.util.Assert;
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.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
/**
* A group of controls used in the JUnit TestCase and TestSuite wizards
* for selecting method stubs to create.
*/
public class MethodStubsSelectionButtonGroup {
private Label fLabel;
protected String fLabelText;
private SelectionButtonGroupListener fGroupListener;
private boolean fEnabled;
private Composite fButtonComposite;
private Button[] fButtons;
private String[] fButtonNames;
private boolean[] fButtonsSelected;
private boolean[] fButtonsEnabled;
private Combo fMainCombo;
private boolean fMainComboEnabled;
private int fGroupBorderStyle;
private int fGroupNumberOfColumns;
private int fButtonsStyle;
public interface SelectionButtonGroupListener {
/**
* The dialog field has changed.
*/
void groupChanged(MethodStubsSelectionButtonGroup field);
}
/**
* Creates a group without border.
*/
public MethodStubsSelectionButtonGroup(int buttonsStyle, String[] buttonNames, int nColumns) {
this(buttonsStyle, buttonNames, nColumns, SWT.NONE);
}
/**
* Creates a group with border (label in border).
* Accepted button styles are: SWT.RADIO, SWT.CHECK, SWT.TOGGLE
* For border styles see <code>Group</code>
*/
public MethodStubsSelectionButtonGroup(int buttonsStyle, String[] buttonNames, int nColumns, int borderStyle) {
fEnabled= true;
fLabel= null;
fLabelText= ""; //$NON-NLS-1$
Assert.isTrue(buttonsStyle == SWT.RADIO || buttonsStyle == SWT.CHECK || buttonsStyle == SWT.TOGGLE);
fButtonNames= buttonNames;
int nButtons= buttonNames.length;
fButtonsSelected= new boolean[nButtons];
fButtonsEnabled= new boolean[nButtons];
for (int i= 0; i < nButtons; i++) {
fButtonsSelected[i]= false;
fButtonsEnabled[i]= true;
}
fMainComboEnabled= true;
if (fButtonsStyle == SWT.RADIO) {
fButtonsSelected[0]= true;
}
fGroupBorderStyle= borderStyle;
fGroupNumberOfColumns= (nColumns <= 0) ? nButtons : nColumns;
fButtonsStyle= buttonsStyle;
}
/*
* @see DialogField#doFillIntoGrid
*/
public Control[] doFillIntoGrid(Composite parent, int nColumns) {
assertEnoughColumns(nColumns);
if (fGroupBorderStyle == SWT.NONE) {
Label label= getLabelControl(parent);
label.setLayoutData(gridDataForLabel(1));
Composite buttonsgroup= getSelectionButtonsGroup(parent);
GridData gd= new GridData();
gd.horizontalSpan= nColumns - 1;
buttonsgroup.setLayoutData(gd);
return new Control[] { label, buttonsgroup };
} else {
Composite buttonsgroup= getSelectionButtonsGroup(parent);
GridData gd= new GridData();
gd.horizontalSpan= nColumns;
buttonsgroup.setLayoutData(gd);
return new Control[] { buttonsgroup };
}
}
/*
* @see DialogField#doFillIntoGrid
*/
public int getNumberOfControls() {
return (fGroupBorderStyle == SWT.NONE) ? 2 : 1;
}
private Button createSelectionButton(int index, Composite group, SelectionListener listener) {
Button button= new Button(group, fButtonsStyle | SWT.LEFT);
button.setFont(group.getFont());
button.setText(fButtonNames[index]);
button.setEnabled(isEnabled() && fButtonsEnabled[index]);
button.setSelection(fButtonsSelected[index]);
button.addSelectionListener(listener);
button.setLayoutData(new GridData());
return button;
}
private Button createMainCombo(int index, Composite group, SelectionListener listener) {
Composite buttonComboGroup= new Composite(group, 0);
GridLayout layout= new GridLayout();
layout.marginHeight= 0;
layout.marginWidth= 20;
layout.numColumns= 2;
buttonComboGroup.setLayout(layout);
Button button= new Button(buttonComboGroup, fButtonsStyle | SWT.LEFT);
button.setFont(group.getFont());
button.setText(fButtonNames[index]);
button.setEnabled(isEnabled() && fButtonsEnabled[index]);
button.setSelection(fButtonsSelected[index]);
button.addSelectionListener(listener);
button.setLayoutData(new GridData());
fMainCombo= new Combo(buttonComboGroup, SWT.READ_ONLY);
fMainCombo.setItems(new String[] {"text ui","swing ui","awt ui"}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
fMainCombo.select(0);
fMainCombo.setEnabled(isEnabled() && fMainComboEnabled);
fMainCombo.setFont(group.getFont());
fMainCombo.setLayoutData(new GridData());
return button;
}
public String getMainMethod(String typeName) {
StringBuffer main= new StringBuffer("public static void main(String[] args) {"); //$NON-NLS-1$
if (isSelected(1)) {
main.append("junit."); //$NON-NLS-1$
switch (getComboSelection()) {
case 0:
main.append("textui"); //$NON-NLS-1$
break;
case 1:
main.append("swingui"); //$NON-NLS-1$
break;
case 2 :
main.append("awtui"); //$NON-NLS-1$
break;
default :
main.append("textui"); //$NON-NLS-1$
break;
}
main.append(".TestRunner.run(" + typeName + ".class);"); //$NON-NLS-1$ //$NON-NLS-2$
}
main.append("}\n\n"); //$NON-NLS-1$
return main.toString();
}
/**
* Returns the group widget. When called the first time, the widget will be created.
* @param The parent composite when called the first time, or <code>null</code>
* after.
*/
public Composite getSelectionButtonsGroup(Composite parent) {
if (fButtonComposite == null) {
assertCompositeNotNull(parent);
GridLayout layout= new GridLayout();
layout.makeColumnsEqualWidth= true;
layout.numColumns= fGroupNumberOfColumns;
if (fGroupBorderStyle != SWT.NONE) {
Group group= new Group(parent, fGroupBorderStyle);
if (fLabelText != null && fLabelText.length() > 0) {
group.setText(fLabelText);
}
fButtonComposite= group;
} else {
fButtonComposite= new Composite(parent, SWT.NULL);
layout.marginHeight= 0;
layout.marginWidth= 0;
}
fButtonComposite.setLayout(layout);
SelectionListener listener= new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
doWidgetSelected(e);
}
public void widgetSelected(SelectionEvent e) {
doWidgetSelected(e);
}
};
int nButtons= fButtonNames.length;
fButtons= new Button[nButtons];
fButtons[0]= createSelectionButton(0, fButtonComposite, listener);
fButtons[1]= createMainCombo(1, fButtonComposite, listener);
for (int i= 2; i < nButtons; i++) {
fButtons[i]= createSelectionButton(i, fButtonComposite, listener);
}
int nRows= nButtons / fGroupNumberOfColumns;
int nFillElements= nRows * fGroupNumberOfColumns - nButtons;
for (int i= 0; i < nFillElements; i++) {
createEmptySpace(fButtonComposite);
}
setSelectionGroupListener(new SelectionButtonGroupListener() {
public void groupChanged(MethodStubsSelectionButtonGroup field) {
field.setEnabled(1, isEnabled() && field.isSelected(0));
}
});
}
return fButtonComposite;
}
/**
* Returns a button from the group or <code>null</code> if not yet created.
*/
public Button getSelectionButton(int index) {
if (index >= 0 && index < fButtons.length) {
return fButtons[index];
}
return null;
}
private void doWidgetSelected(SelectionEvent e) {
Button button= (Button)e.widget;
for (int i= 0; i < fButtons.length; i++) {
if (fButtons[i] == button) {
fButtonsSelected[i]= button.getSelection();
dialogFieldChanged();
return;
}
}
}
/**
* Returns the selection state of a button contained in the group.
* @param The index of the button
*/
public boolean isSelected(int index) {
if (index >= 0 && index < fButtonsSelected.length) {
return fButtonsSelected[index];
}
return false;
}
/**
* Sets the selection state of a button contained in the group.
*/
public void setSelection(int index, boolean selected) {
if (index >= 0 && index < fButtonsSelected.length) {
if (fButtonsSelected[index] != selected) {
fButtonsSelected[index]= selected;
if (fButtons != null) {
Button button= fButtons[index];
if (isOkToUse(button)) {
button.setSelection(selected);
}
}
}
}
}
/**
* Returns the enabled state of a button contained in the group.
* @param The index of the button
*/
public boolean isEnabled(int index) {
if (index >= 0 && index < fButtonsEnabled.length) {
return fButtonsEnabled[index];
}
return false;
}
/**
* Sets the selection state of a button contained in the group.
*/
public void setEnabled(int index, boolean enabled) {
if (index >= 0 && index < fButtonsEnabled.length) {
if (fButtonsEnabled[index] != enabled) {
fButtonsEnabled[index]= enabled;
if (index == 1)
fMainComboEnabled= enabled;
if (fButtons != null) {
Button button= fButtons[index];
if (isOkToUse(button)) {
button.setEnabled(enabled);
if (index == 1)
fMainCombo.setEnabled(isEnabled() && enabled);
}
}
}
}
}
protected void updateEnableState() {
if (fLabel != null) {
fLabel.setEnabled(fEnabled);
}
if (fButtons != null) {
boolean enabled= isEnabled();
for (int i= 0; i < fButtons.length; i++) {
Button button= fButtons[i];
if (isOkToUse(button)) {
button.setEnabled(enabled && fButtonsEnabled[i]);
}
}
fMainCombo.setEnabled(enabled && fMainComboEnabled);
}
}
public int getComboSelection() {
return fMainCombo.getSelectionIndex();
}
public void setComboSelection(int index) {
fMainCombo.select(index);
}
/**
* Sets the label of the dialog field.
*/
public void setLabelText(String labeltext) {
fLabelText= labeltext;
}
/**
* Defines the listener for this dialog field.
*/
public final void setSelectionGroupListener(SelectionButtonGroupListener listener) {
fGroupListener= listener;
}
/**
* Programatical invocation of a dialog field change.
*/
public void dialogFieldChanged() {
if (fGroupListener != null) {
fGroupListener.groupChanged(this);
}
}
/**
* Tries to set the focus to the dialog field.
* Returns <code>true</code> if the dialog field can take focus.
* To be reimplemented by dialog field implementors.
*/
public boolean setFocus() {
return false;
}
/**
* Posts <code>setFocus</code> to the display event queue.
*/
public void postSetFocusOnDialogField(Display display) {
if (display != null) {
display.asyncExec(
new Runnable() {
public void run() {
setFocus();
}
}
);
}
}
protected static GridData gridDataForLabel(int span) {
GridData gd= new GridData();
gd.horizontalSpan= span;
return gd;
}
/**
* Creates or returns the created label widget.
* @param parent The parent composite or <code>null</code> if the widget has
* already been created.
*/
public Label getLabelControl(Composite parent) {
if (fLabel == null) {
assertCompositeNotNull(parent);
fLabel= new Label(parent, SWT.LEFT | SWT.WRAP);
fLabel.setFont(parent.getFont());
fLabel.setEnabled(fEnabled);
if (fLabelText != null && !"".equals(fLabelText)) { //$NON-NLS-1$
fLabel.setText(fLabelText);
} else {
// XXX: to avoid a 16 pixel wide empty label - revisit
fLabel.setText("."); //$NON-NLS-1$
fLabel.setVisible(false);
}
}
return fLabel;
}
/**
* Creates a spacer control.
* @param parent The parent composite
*/
public static Control createEmptySpace(Composite parent) {
return createEmptySpace(parent, 1);
}
/**
* Creates a spacer control with the given span.
* The composite is assumed to have <code>MGridLayout</code> as
* layout.
* @param parent The parent composite
*/
public static Control createEmptySpace(Composite parent, int span) {
return LayoutUtil.createEmptySpace(parent, span);
}
/**
* Tests is the control is not <code>null</code> and not disposed.
*/
protected final boolean isOkToUse(Control control) {
return (control != null) && !(control.isDisposed());
}
// --------- enable / disable management
/**
* Sets the enable state of the dialog field.
*/
public final void setEnabled(boolean enabled) {
if (enabled != fEnabled) {
fEnabled= enabled;
updateEnableState();
}
}
/**
* Gets the enable state of the dialog field.
*/
public final boolean isEnabled() {
return fEnabled;
}
protected final void assertCompositeNotNull(Composite comp) {
Assert.isNotNull(comp, "uncreated control requested with composite null"); //$NON-NLS-1$
}
protected final void assertEnoughColumns(int nColumns) {
Assert.isTrue(nColumns >= getNumberOfControls(), "given number of columns is too small"); //$NON-NLS-1$
}
}
|
50,386 |
Bug 50386 Autoindent/Smart Tab in case statement
|
1: case SWT.TRAVERSE_ESCAPE : 2: fTableViewer.cancelEditing(); 3: e.doit= true; Pressing Tab at beginning of line 3 removes one tab character from line 3. It shouldn't. Same indentation error for Smart Return, Correct Indentation, ... for all lines which are 2+ lines after the case keyword.
|
resolved fixed
|
eb60839
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-26T11:14:25Z | 2004-01-22T11:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/JavaIndenter.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.core.runtime.Plugin;
import org.eclipse.jface.text.Assert;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
/**
* Uses the {@link org.eclipse.jdt.internal.ui.text.JavaHeuristicScanner}to
* get the indentation level for a certain position in a document.
*
* <p>
* An instance holds some internal position in the document and is therefore
* not threadsafe.
* </p>
*
* @since 3.0
*/
public class JavaIndenter {
/** The document being scanned. */
private IDocument fDocument;
/** The indentation accumulated by <code>findPreviousIndenationUnit</code>. */
private int fIndent;
/**
* The absolute (character-counted) indentation offset for special cases
* (method defs, array initializers)
*/
private int fAlign;
/** The stateful scanposition for the indentation methods. */
private int fPosition;
/** The previous position. */
private int fPreviousPos;
/** The most recent token. */
private int fToken;
/** The line of <code>fPosition</code>. */
private int fLine;
/**
* The scanner we will use to scan the document. It has to be installed
* on the same document as the one we get.
*/
private JavaHeuristicScanner fScanner;
/**
* Creates a new instance.
*
* @param document the document to scan
* @param scanner the {@link JavaHeuristicScanner} to be used for scanning
* the document. It must be installed on the same <code>IDocument</code>.
*/
public JavaIndenter(IDocument document, JavaHeuristicScanner scanner) {
Assert.isNotNull(document);
Assert.isNotNull(scanner);
fDocument= document;
fScanner= scanner;
}
/**
* Computes the indentation at the reference point of <code>position</code>.
*
* @param offset the offset in the document
* @return a String which reflects the indentation at the line in which the
* reference position to <code>offset</code> resides, or <code>null</code>
* if it cannot be determined
*/
public StringBuffer getReferenceIndentation(int offset) {
return getReferenceIndentation(offset, false);
}
/**
* Computes the indentation at the reference point of <code>position</code>.
*
* @param offset the offset in the document
* @param assumeOpeningBrace <code>true</code> if an opening brace should be assumed
* @return a String which reflects the indentation at the line in which the
* reference position to <code>offset</code> resides, or <code>null</code>
* if it cannot be determined
*/
private StringBuffer getReferenceIndentation(int offset, boolean assumeOpeningBrace) {
int unit;
if (assumeOpeningBrace)
unit= findReferencePosition(offset, Symbols.TokenLBRACE);
else
unit= findReferencePosition(offset, peekChar(offset));
// if we were unable to find anything, return null
if (unit == JavaHeuristicScanner.NOT_FOUND)
return null;
return getLeadingWhitespace(unit);
}
/**
* Computes the indentation at <code>offset</code>.
*
* @param offset the offset in the document
* @return a String which reflects the correct indentation for the line in
* which offset resides, or <code>null</code> if it cannot be
* determined
*/
public StringBuffer computeIndentation(int offset) {
return computeIndentation(offset, false);
}
/**
* Computes the indentation at <code>offset</code>.
*
* @param offset the offset in the document
* @param assumeOpeningBrace <code>true</code> if an opening brace should be assumed
* @return a String which reflects the correct indentation for the line in
* which offset resides, or <code>null</code> if it cannot be
* determined
*/
public StringBuffer computeIndentation(int offset, boolean assumeOpeningBrace) {
StringBuffer indent= getReferenceIndentation(offset, assumeOpeningBrace);
// handle special alignment
if (fAlign != JavaHeuristicScanner.NOT_FOUND) {
try {
// a special case has been detected.
IRegion line= fDocument.getLineInformationOfOffset(fAlign);
int lineOffset= line.getOffset();
return createIndent(lineOffset, fAlign);
} catch (BadLocationException e) {
return null;
}
}
if (indent == null)
return null;
// add additional indent
indent.append(createIndent(fIndent));
if (fIndent < 0)
unindent(indent);
return indent;
}
/**
* Returns the indentation of the line at <code>offset</code> as a
* <code>StringBuffer</code>. If the offset is not valid, the empty string
* is returned.
*
* @param offset the offset in the document
* @return the indentation (leading whitespace) of the line in which
* <code>offset</code> is located
*/
private StringBuffer getLeadingWhitespace(int offset) {
StringBuffer indent= new StringBuffer();
try {
IRegion line= fDocument.getLineInformationOfOffset(offset);
int lineOffset= line.getOffset();
int nonWS= fScanner.findNonWhitespaceForwardInAnyPartition(lineOffset, lineOffset + line.getLength());
indent.append(fDocument.get(lineOffset, nonWS - lineOffset));
return indent;
} catch (BadLocationException e) {
return indent;
}
}
/**
* Reduces indentation in <code>indent</code> by one indentation unit.
*
* @param indent the indentation to be modified
*/
private void unindent(StringBuffer indent) {
CharSequence oneIndent= createIndent();
int i= indent.lastIndexOf(oneIndent.toString()); //$NON-NLS-1$
if (i != -1) {
indent.delete(i, i + oneIndent.length());
}
}
/**
* Creates an indentation string of the length indent - start + 1,
* consisting of the content in <code>fDocument</code> in the range
* [start, indent), with every character replaced by a space except for
* tabs, which are kept as such.
*
* <p>Every run of the number of spaces that make up a tab are replaced
* by a tab character.</p>
*
* @return the indentation corresponding to the document content specified
* by <code>start</code> and <code>indent</code>
*/
private StringBuffer createIndent(int start, int indent) {
final int tabLen= prefTabLength();
StringBuffer ret= new StringBuffer();
try {
int spaces= 0;
while (start < indent) {
char ch= fDocument.getChar(start);
if (ch == '\t') {
ret.append('\t');
spaces= 0;
} else if (tabLen == -1){
ret.append(' ');
} else {
spaces++;
if (spaces == tabLen) {
ret.append('\t');
spaces= 0;
}
}
start++;
}
// remainder
if (spaces == tabLen)
ret.append('\t');
else
while (spaces-- > 0)
ret.append(' ');
} catch (BadLocationException e) {
}
return ret;
}
/**
* Creates a string that represents the given number of indents (can be
* spaces or tabs..)
*
* @param indent the requested indentation level.
*
* @return the indentation specified by <code>indent</code>
*/
private StringBuffer createIndent(int indent) {
StringBuffer oneIndent= createIndent();
StringBuffer ret= new StringBuffer();
while (indent-- > 0)
ret.append(oneIndent);
return ret;
}
/**
* Creates a string that represents one indent (can be
* spaces or tabs..)
*
* @return one indentation
*/
private StringBuffer createIndent() {
// get a sensible default when running without the infrastructure for testing
StringBuffer oneIndent= new StringBuffer();
JavaCore plugin= JavaCore.getJavaCore();
if (plugin == null) {
oneIndent.append('\t');
} else {
if (JavaCore.SPACE.equals(JavaCore.getOption(JavaCore.FORMATTER_TAB_CHAR))) {
int tabLen= Integer.parseInt(JavaCore.getOption(JavaCore.FORMATTER_TAB_SIZE));
for (int i= 0; i < tabLen; i++)
oneIndent.append(' ');
} else if (JavaCore.TAB.equals(JavaCore.getOption(JavaCore.FORMATTER_TAB_CHAR)))
oneIndent.append('\t');
else
oneIndent.append('\t'); // default
}
return oneIndent;
}
/**
* Returns the reference position regarding to indentation for <code>offset</code>,
* or <code>NOT_FOUND</code>. This method calls
* {@link #findReferencePosition(int, int) findReferencePosition(offset, nextChar)} where
* <code>nextChar</code> is the next character after <code>offset</code>.
*
* @param offset the offset for which the reference is computed
* @return the reference statement relative to which <code>offset</code>
* should be indented, or {@link JavaHeuristicScanner#NOT_FOUND}
*/
public int findReferencePosition(int offset) {
return findReferencePosition(offset, peekChar(offset));
}
/**
* Peeks the next char in the document that comes after <code>offset</code>
* on the same line as <code>offset</code>.
*
* @param offset the offset into document
* @return the token symbol of the next element, or TokenEOF if there is none
*/
private int peekChar(int offset) {
if (offset < fDocument.getLength()) {
try {
IRegion line= fDocument.getLineInformationOfOffset(offset);
int lineOffset= line.getOffset();
int next= fScanner.nextToken(offset, lineOffset + line.getLength());
return next;
} catch (BadLocationException e) {
}
}
return Symbols.TokenEOF;
}
/**
* Returns the reference position regarding to indentation for <code>position</code>,
* or <code>NOT_FOUND</code>.
*
* <p>If <code>peekNextChar</code> is <code>true</code>, the next token after
* <code>offset</code> is read and taken into account when computing the
* indentation. Currently, if the next token is the first token on the line
* (i.e. only preceded by whitespace), the following tokens are specially
* handled:
* <ul>
* <li><code>switch</code> labels are indented relative to the switch block</li>
* <li>opening curly braces are aligned correctly with the introducing code</li>
* <li>closing curly braces are aligned properly with the introducing code of
* the matching opening brace</li>
* <li>closing parenthesis' are aligned with their opening peer</li>
* <li>the <code>else</code> keyword is aligned with its <code>if</code>, anything
* else is aligned normally (i.e. with the base of any introducing statements).</li>
* <li>if there is no token on the same line after <code>offset</code>, the indentation
* is the same as for an <code>else</code> keyword</li>
* </ul>
*
* @param offset the offset for which the reference is computed
* @param nextChar the next character to assume in the document
* @return the reference statement relative to which <code>offset</code>
* should be indented, or {@link JavaHeuristicScanner#NOT_FOUND}
*/
public int findReferencePosition(int offset, int nextChar) {
boolean danglingElse= false;
boolean unindent= false;
boolean matchBrace= false;
boolean matchParen= false;
boolean matchCase= false;
// account for unindenation characters already typed in, but after position
// if they are on a line by themselves, the indentation gets adjusted
// accordingly
//
// also account for a dangling else
if (offset < fDocument.getLength()) {
try {
IRegion line= fDocument.getLineInformationOfOffset(offset);
int lineOffset= line.getOffset();
int prevPos= Math.max(offset - 1, 0);
boolean isFirstTokenOnLine= fDocument.get(lineOffset, prevPos + 1 - lineOffset).trim().length() == 0;
int prevToken= fScanner.previousToken(prevPos, JavaHeuristicScanner.UNBOUND);
switch (nextChar) {
case Symbols.TokenEOF:
case Symbols.TokenELSE:
danglingElse= true;
break;
case Symbols.TokenCASE:
case Symbols.TokenDEFAULT:
if (isFirstTokenOnLine)
matchCase= true;
break;
case Symbols.TokenLBRACE: // for opening-brace-on-new-line style
if (fScanner.isBracelessBlockStart(prevPos, JavaHeuristicScanner.UNBOUND))
unindent= true;
if (prevToken == Symbols.TokenCOLON || prevToken == Symbols.TokenEQUAL || prevToken == Symbols.TokenRBRACKET)
unindent= true;
break;
case Symbols.TokenRBRACE: // closing braces get unindented
if (isFirstTokenOnLine)
matchBrace= true;
break;
case Symbols.TokenRPAREN:
if (isFirstTokenOnLine)
matchParen= true;
break;
}
} catch (BadLocationException e) {
}
} else {
// assume an else could come if we are at the end of file
danglingElse= true;
}
int ref= findReferencePosition(offset, danglingElse, matchBrace, matchParen, matchCase);
if (unindent)
fIndent--;
return ref;
}
/**
* Returns the reference position regarding to indentation for <code>position</code>,
* or <code>NOT_FOUND</code>.<code>fIndent</code> will contain the
* relative indentation (in indentation units, not characters) after the
* call. If there is a special alignment (e.g. for a method declaration
* where parameters should be aligned), <code>fAlign</code> will contain
* the absolute position of the alignment reference in <code>fDocument</code>,
* otherwise <code>fAlign</code> is set to <code>JavaHeuristicScanner.NOT_FOUND</code>.
*
* @param offset the offset for which the reference is computed
* @param danglingElse whether a dangling else should be assumed at <code>position</code>
* @param matchBrace whether the position of the matching brace should be
* returned instead of doing code analysis
* @param matchParen whether the position of the matching parenthesis
* should be returned instead of doing code analysis
* @param matchCase whether the position of a switch statement reference
* should be returned (either an earlier case statement or the
* switch block brace)
* @return the reference statement relative to which <code>position</code>
* should be indented, or {@link JavaHeuristicScanner#NOT_FOUND}
*/
public int findReferencePosition(int offset, boolean danglingElse, boolean matchBrace, boolean matchParen, boolean matchCase) {
fIndent= 0; // the indentation modification
fAlign= JavaHeuristicScanner.NOT_FOUND;
fPosition= offset;
// forward cases
// an unindentation happens sometimes if the next token is special, namely on braces, parens and case labels
// align braces, but handle the case where we align with the method declaration start instead of
// the opening brace.
if (matchBrace) {
if (skipScope(Symbols.TokenLBRACE, Symbols.TokenRBRACE)) {
try {
// align with the opening brace that is on a line by its own
int lineOffset= fDocument.getLineOffset(fLine);
if (lineOffset <= fPosition && fDocument.get(lineOffset, fPosition - lineOffset).trim().length() == 0)
return fPosition;
} catch (BadLocationException e) {
// concurrent modification - walk default path
}
// if the opening brace is not on the start of the line, skip to the start
return skipToStatementStart(true, true);
} else {
// if we can't find the matching brace, the heuristic is to unindent
// by one against the normal position
int pos= findReferencePosition(offset, danglingElse, false, matchParen, matchCase);
fIndent--;
return pos;
}
}
// align parenthesis'
if (matchParen) {
if (skipScope(Symbols.TokenLPAREN, Symbols.TokenRPAREN))
return fPosition;
else {
// if we can't find the matching paren, the heuristic is to unindent
// by one against the normal position
int pos= findReferencePosition(offset, danglingElse, matchBrace, false, matchCase);
fIndent--;
return pos;
}
}
// the only reliable way to get case labels aligned (due to many different styles of using braces in a block)
// is to go for another case statement, or the scope opening brace
if (matchCase) {
return matchCaseAlignment();
}
nextToken();
switch (fToken) {
case Symbols.TokenRBRACE:
// skip the block and fall through
// if we can't complete the scope, reset the scan position
int pos= fPosition;
if (!skipScope())
fPosition= pos;
case Symbols.TokenSEMICOLON:
// this is the 90% case: after a statement block
// the end of the previous statement / block previous.end
// search to the end of the statement / block before the previous; the token just after that is previous.start
return skipToStatementStart(danglingElse, false);
// scope introduction: special treat who special is
case Symbols.TokenLPAREN:
case Symbols.TokenLBRACE:
case Symbols.TokenLBRACKET:
return handleScopeIntroduction(offset + 1);
case Symbols.TokenEOF:
// trap when hitting start of document
return 0;
case Symbols.TokenEQUAL:
// indent assignments
fIndent= prefAssignmentIndent();
return fPosition;
case Symbols.TokenCOLON:
// TODO handle ternary deep indentation
fIndent= prefCaseBlockIndent();
return fPosition;
case Symbols.TokenQUESTIONMARK:
if (prefTernaryDeepAlign()) {
setFirstElementAlignment(fPosition, offset + 1);
return fPosition;
} else {
fIndent= prefTernaryIndent();
return fPosition;
}
// indentation for blockless introducers:
case Symbols.TokenDO:
case Symbols.TokenWHILE:
case Symbols.TokenELSE:
fIndent= prefSimpleIndent();
return fPosition;
case Symbols.TokenRPAREN:
if (skipScope(Symbols.TokenLPAREN, Symbols.TokenRPAREN)) {
nextToken();
if (fToken == Symbols.TokenIF || fToken == Symbols.TokenWHILE || fToken == Symbols.TokenFOR) {
fIndent= prefSimpleIndent();
return fPosition;
}
}
// else: fall through to default
case Symbols.TokenCOMMA:
// inside a list of some type
// easy if there is already a list item before with its own indentation - we just align
// if not: take the start of the list ( LPAREN, LBRACE, LBRACKET ) and either align or
// indent by list-indent
default:
// inside whatever we don't know about: similar to the list case:
// if we are inside a continued expression, then either align with a previous line that has indentation
// or indent from the expression start line (either a scope introducer or the start of the expr).
return skipToPreviousListItemOrListStart();
}
}
/**
* Skips to the start of a statement that ends at the current position.
*
* @param danglingElse whether to indent aligned with the last <code>if</code>
* @return the reference offset of the start of the statement
*/
private int skipToStatementStart(boolean danglingElse, boolean isInBlock) {
while (true) {
nextToken();
if (isInBlock) {
switch (fToken) {
// exit on all block introducers
case Symbols.TokenIF:
case Symbols.TokenELSE:
case Symbols.TokenSYNCHRONIZED:
case Symbols.TokenCOLON:
case Symbols.TokenSTATIC:
case Symbols.TokenCATCH:
case Symbols.TokenDO:
case Symbols.TokenWHILE:
case Symbols.TokenFINALLY:
case Symbols.TokenFOR:
case Symbols.TokenTRY:
return fPosition;
case Symbols.TokenSWITCH:
fIndent= prefCaseIndent();
return fPosition;
}
}
switch (fToken) {
// scope introduction through: LPAREN, LBRACE, LBRACKET
// search stop on SEMICOLON, RBRACE, COLON, EOF
// -> the next token is the start of the statement (i.e. previousPos when backward scanning)
case Symbols.TokenLPAREN:
case Symbols.TokenLBRACE:
case Symbols.TokenLBRACKET:
case Symbols.TokenSEMICOLON:
case Symbols.TokenEOF:
return fPreviousPos;
case Symbols.TokenCOLON:
int pos= fPreviousPos;
if (!isConditional())
return pos;
break;
case Symbols.TokenRBRACE:
// RBRACE is a little tricky: it can be the end of an array definition, but
// usually it is the end of a previous block
pos= fPreviousPos; // store state
if (skipScope() && looksLikeArrayInitializerIntro())
continue; // it's an array
else
return pos; // it's not - do as with all the above
// scopes: skip them
case Symbols.TokenRPAREN:
case Symbols.TokenRBRACKET:
pos= fPreviousPos;
if (skipScope())
break;
else
return pos;
// IF / ELSE: align the position after the conditional block with the if
// so we are ready for an else, except if danglingElse is false
// in order for this to work, we must skip an else to its if
case Symbols.TokenIF:
if (danglingElse)
return fPosition;
else
break;
case Symbols.TokenELSE:
// skip behind the next if, as we have that one covered
pos= fPosition;
if (skipNextIF())
break;
else
return pos;
case Symbols.TokenDO:
// align the WHILE position with its do
return fPosition;
case Symbols.TokenWHILE:
// this one is tricky: while can be the start of a while loop
// or the end of a do - while
pos= fPosition;
if (hasMatchingDo()) {
// continue searching from the DO on
break;
} else {
// continue searching from the WHILE on
fPosition= pos;
break;
}
default:
// keep searching
}
}
}
/**
* Returns true if the colon at the current position is part of a conditional
* (ternary) expression, false otherwise.
*
* @return true if the colon at the current position is part of a conditional
*/
private boolean isConditional() {
while (true) {
nextToken();
switch (fToken) {
// search for case, otherwise return true
case Symbols.TokenIDENT:
continue;
case Symbols.TokenCASE:
return false;
default:
return true;
}
}
}
/**
* Returns as a reference any previous <code>switch</code> labels (<code>case</code>
* or <code>default</code>) or the offset of the brace that scopes the switch
* statement. Sets <code>fIndent</code> to <code>prefCaseIndent</code> upon
* a match.
*
* @return the reference offset for a <code>switch</code> label
*/
private int matchCaseAlignment() {
while (true) {
nextToken();
switch (fToken) {
// invalid cases: another case label or an LBRACE must come before a case
// -> bail out with the current position
case Symbols.TokenLPAREN:
case Symbols.TokenLBRACKET:
case Symbols.TokenEOF:
return fPosition;
case Symbols.TokenLBRACE:
// opening brace of switch statement
fIndent= prefCaseIndent();
return fPosition;
case Symbols.TokenCASE:
case Symbols.TokenDEFAULT:
// align with previous label
fIndent= 0;
return fPosition;
// scopes: skip them
case Symbols.TokenRPAREN:
case Symbols.TokenRBRACKET:
case Symbols.TokenRBRACE:
skipScope();
break;
default:
// keep searching
continue;
}
}
}
/**
* Returns the reference position for a list element. The algorithm
* tries to match any previous indentation on the same list. If there is none,
* the reference position returned is determined depending on the type of list:
* The indentation will either match the list scope introducer (e.g. for
* method declarations), so called deep indents, or simply increase the
* indentation by a number of standard indents. See also {@link #handleScopeIntroduction(int)}.
*
* @return the reference position for a list item: either a previous list item
* that has its own indentation, or the list introduction start.
*/
private int skipToPreviousListItemOrListStart() {
int startLine= fLine;
int startPosition= fPosition;
while (true) {
nextToken();
// if any line item comes with its own indentation, adapt to it
if (fLine < startLine) {
try {
int lineOffset= fDocument.getLineOffset(startLine);
fAlign= fScanner.findNonWhitespaceForwardInAnyPartition(lineOffset, startPosition + 1);
} catch (BadLocationException e) {
// ignore and return just the position
}
return startPosition;
}
switch (fToken) {
// scopes: skip them
case Symbols.TokenRPAREN:
case Symbols.TokenRBRACKET:
case Symbols.TokenRBRACE:
skipScope();
break;
// scope introduction: special treat who special is
case Symbols.TokenLPAREN:
case Symbols.TokenLBRACE:
case Symbols.TokenLBRACKET:
return handleScopeIntroduction(startPosition + 1);
case Symbols.TokenSEMICOLON:
return fPosition;
case Symbols.TokenQUESTIONMARK:
if (prefTernaryDeepAlign()) {
setFirstElementAlignment(fPosition - 1, fPosition + 1);
return fPosition;
} else {
fIndent= prefTernaryIndent();
return fPosition;
}
case Symbols.TokenEOF:
return 0;
}
}
}
/**
* Skips a scope and positions the cursor (<code>fPosition</code>) on the
* token that opens the scope. Returns <code>true</code> if a matching peer
* could be found, <code>false</code> otherwise. The current token when calling
* must be one out of <code>Symbols.TokenRPAREN</code>, <code>Symbols.TokenRBRACE</code>,
* and <code>Symbols.TokenRBRACKET</code>.
*
* @return <code>true</code> if a matching peer was found, <code>false</code> otherwise
*/
private boolean skipScope() {
switch (fToken) {
case Symbols.TokenRPAREN:
return skipScope(Symbols.TokenLPAREN, Symbols.TokenRPAREN);
case Symbols.TokenRBRACKET:
return skipScope(Symbols.TokenLBRACKET, Symbols.TokenRBRACKET);
case Symbols.TokenRBRACE:
return skipScope(Symbols.TokenLBRACE, Symbols.TokenRBRACE);
default:
Assert.isTrue(false);
return false;
}
}
/**
* Handles the introduction of a new scope. The current token must be one out
* of <code>Symbols.TokenLPAREN</code>, <code>Symbols.TokenLBRACE</code>,
* and <code>Symbols.TokenLBRACKET</code>. Returns as the reference position
* either the token introducing the scope or - if available - the first
* java token after that.
*
* <p>Depending on the type of scope introduction, the indentation will align
* (deep indenting) with the reference position (<code>fAlign</code> will be
* set to the reference position) or <code>fIndent</code> will be set to
* the number of indentation units.
* </p>
*
* @param bound the bound for the search for the first token after the scope
* introduction.
* @return
*/
private int handleScopeIntroduction(int bound) {
switch (fToken) {
// scope introduction: special treat who special is
case Symbols.TokenLPAREN:
int pos= fPosition; // store
// special: method declaration deep indentation
if (looksLikeMethodDecl()) {
if (prefMethodDeclDeepIndent())
return setFirstElementAlignment(pos, bound);
else {
fIndent= prefMethodDeclIndent();
return pos;
}
} else {
fPosition= pos;
if (looksLikeMethodCall()) {
if (prefMethodCallDeepIndent())
return setFirstElementAlignment(pos, bound);
else {
fIndent= prefMethodCallIndent();
return pos;
}
} else if (prefParenthesisDeepIndent())
return setFirstElementAlignment(pos, bound);
}
// normal: return the parenthesis as reference
fIndent= prefParenthesisIndent();
return pos;
case Symbols.TokenLBRACE:
pos= fPosition; // store
// special: array initializer
if (looksLikeArrayInitializerIntro())
if (prefArrayDeepIndent())
return setFirstElementAlignment(pos, bound);
else
fIndent= prefArrayIndent();
else
fIndent= prefBlockIndent();
// normal: skip to the statement start before the scope introducer
// opening braces are often on differently ending indents than e.g. a method definition
fPosition= pos; // restore
return skipToStatementStart(true, true); // set to true to match the first if
case Symbols.TokenLBRACKET:
pos= fPosition; // store
// special: method declaration deep indentation
if (prefArrayDimensionsDeepIndent()) {
return setFirstElementAlignment(pos, bound);
}
// normal: return the bracket as reference
fIndent= prefBracketIndent();
return pos; // restore
default:
Assert.isTrue(false);
return -1; // dummy
}
}
/**
* Sets the deep indent offset (<code>fAlign</code>) to either the offset
* right after <code>scopeIntroducerOffset</code> or - if available - the
* first Java token after <code>scopeIntroducerOffset</code>, but before
* <code>bound</code>.
*
* @param scopeIntroducerOffset the offset of the scope introducer
* @param bound the bound for the search for another element
* @return the reference position
*/
private int setFirstElementAlignment(int scopeIntroducerOffset, int bound) {
int firstPossible= scopeIntroducerOffset + 1; // align with the first position after the scope intro
fAlign= fScanner.findNonWhitespaceForwardInAnyPartition(firstPossible, bound);
if (fAlign == JavaHeuristicScanner.NOT_FOUND)
fAlign= firstPossible;
return fAlign;
}
/**
* Returns <code>true</code> if the next token received after calling
* <code>nextToken</code> is either an equal sign or an array designator ('[]').
*
* @return <code>true</code> if the next elements look like the start of an array definition
*/
private boolean looksLikeArrayInitializerIntro() {
nextToken();
if (fToken == Symbols.TokenEQUAL || skipBrackets()) {
return true;
}
return false;
}
/**
* Skips over the next <code>if</code> keyword. The current token when calling
* this method must be an <code>else</code> keyword. Returns <code>true</code>
* if a matching <code>if</code> could be found, <code>false</code> otherwise.
* The cursor (<code>fPosition</code>) is set to the offset of the <code>if</code>
* token.
*
* @return <code>true</code> if a matching <code>if</code> token was found, <code>false</code> otherwise
*/
private boolean skipNextIF() {
Assert.isTrue(fToken == Symbols.TokenELSE);
while (true) {
nextToken();
switch (fToken) {
// scopes: skip them
case Symbols.TokenRPAREN:
case Symbols.TokenRBRACKET:
case Symbols.TokenRBRACE:
skipScope();
break;
case Symbols.TokenIF:
// found it, return
return true;
case Symbols.TokenELSE:
// recursively skip else-if blocks
skipNextIF();
break;
// shortcut scope starts
case Symbols.TokenLPAREN:
case Symbols.TokenLBRACE:
case Symbols.TokenLBRACKET:
case Symbols.TokenEOF:
return false;
}
}
}
/**
* while(condition); is ambiguous when parsed backwardly, as it is a valid
* statement by its own, so we have to check whether there is a matching
* do. A <code>do</code> can either be separated from the while by a
* block, or by a single statement, which limits our search distance.
*
* @return <code>true</code> if the <code>while</code> currently in
* <code>fToken</code> has a matching <code>do</code>.
*/
private boolean hasMatchingDo() {
Assert.isTrue(fToken == Symbols.TokenWHILE);
nextToken();
switch (fToken) {
case Symbols.TokenRBRACE:
skipScope(); // and fall thru
case Symbols.TokenSEMICOLON:
skipToStatementStart(false, false);
return fToken == Symbols.TokenDO;
}
return false;
}
/**
* Skips brackets if the current token is a RBRACKET. There can be nothing
* but whitespace in between, this is only to be used for <code>[]</code> elements.
*
* @return <code>true</code> if a <code>[]</code> could be scanned, the
* current token is left at the LBRACKET.
*/
private boolean skipBrackets() {
if (fToken == Symbols.TokenRBRACKET) {
nextToken();
if (fToken == Symbols.TokenLBRACKET) {
return true;
}
}
return false;
}
/**
* Reads the next token in backward direction from the heuristic scanner
* and sets the fields <code>fToken, fPreviousPosition</code> and <code>fPosition</code>
* accordingly.
*/
private void nextToken() {
nextToken(fPosition);
}
/**
* Reads the next token in backward direction of <code>start</code> from
* the heuristic scanner and sets the fields <code>fToken, fPreviousPosition</code>
* and <code>fPosition</code> accordingly.
*/
private void nextToken(int start) {
fToken= fScanner.previousToken(start - 1, JavaHeuristicScanner.UNBOUND);
fPreviousPos= start;
fPosition= fScanner.getPosition() + 1;
try {
fLine= fDocument.getLineOfOffset(fPosition);
} catch (BadLocationException e) {
fLine= -1;
}
}
/**
* Returns <code>true</code> if the current tokens look like a method
* declaration header (i.e. only the return type and method name). The
* heuristic calls <code>nextToken</code> and expects an identifier
* (method name) and a type declaration (an identifier with optional
* brackets) which also covers the visibility modifier of constructors; it
* does not recognize package visible constructors.
*
* @return <code>true</code> if the current position looks like a method
* declaration header.
*/
private boolean looksLikeMethodDecl() {
/*
* TODO This heuristic does not recognize package private constructors
* since those do have neither type nor visibility keywords.
* One option would be to go over the parameter list, but that might
* be empty as well - hard to do without an AST...
*/
nextToken();
if (fToken == Symbols.TokenIDENT) { // method name
do nextToken();
while (skipBrackets()); // optional brackets for array valued return types
return fToken == Symbols.TokenIDENT; // type name
}
return false;
}
/**
* Returns <code>true</code> if the current tokens look like a method
* call header (i.e. an identifier as opposed to a keyword taking parenthesized
* parameters such as <code>if</code>).
* <p>The heuristic calls <code>nextToken</code> and expects an identifier
* (method name).
*
* @return <code>true</code> if the current position looks like a method call
* header.
*/
private boolean looksLikeMethodCall() {
nextToken();
return fToken == Symbols.TokenIDENT; // method name
}
/**
* Scans tokens for the matching opening peer. The internal cursor
* (<code>fPosition</code>) is set to the offset of the opening peer if found.
*
* @return <code>true</code> if a matching token was found, <code>false</code>
* otherwise
*/
private boolean skipScope(int openToken, int closeToken) {
int depth= 1;
while (true) {
nextToken();
if (fToken == closeToken) {
depth++;
} else if (fToken == openToken) {
depth--;
if (depth == 0)
return true;
} else if (fToken == Symbols.TokenEOF) {
return false;
}
}
}
// TODO adjust once there are per-project settings
private int prefTabLength() {
int tabLen;
JavaCore core= JavaCore.getJavaCore();
JavaPlugin plugin= JavaPlugin.getDefault();
if (core != null && plugin != null)
if (JavaCore.SPACE.equals(JavaCore.getOption(JavaCore.FORMATTER_TAB_CHAR)))
// if the formatter uses chars to mark indentation, then don't substitute any chars
tabLen= -1; // results in no tabs being substituted for space runs
else
// if the formatter uses tabs to mark indentations, use the visual setting from the editor
// to get nicely aligned indentations
tabLen= plugin.getPreferenceStore().getInt(PreferenceConstants.EDITOR_TAB_WIDTH);
else
tabLen= 4; // sensible default for testing
return tabLen;
}
private boolean prefArrayDimensionsDeepIndent() {
return true; // sensible default
}
private int prefArrayIndent() {
Plugin plugin= JavaCore.getPlugin();
if (plugin != null) {
String option= JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_ARRAY_INITIALIZER_EXPRESSIONS_ALIGNMENT);
try {
if ((Integer.parseInt(option) & Integer.parseInt(DefaultCodeFormatterConstants.FORMATTER_INDENT_BY_ONE)) != 0)
return 1;
else
return prefContinuationIndent();
} catch (NumberFormatException e) {
// ignore and return default
}
}
return prefContinuationIndent(); // default
}
private boolean prefArrayDeepIndent() {
Plugin plugin= JavaCore.getPlugin();
if (plugin != null) {
String option= JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_ARRAY_INITIALIZER_EXPRESSIONS_ALIGNMENT);
try {
if ((Integer.parseInt(option) & Integer.parseInt(DefaultCodeFormatterConstants.FORMATTER_INDENT_ON_COLUMN)) != 0)
return true;
else
return false;
} catch (NumberFormatException e) {
// ignore and return default
}
}
return true;
}
private boolean prefTernaryDeepAlign() {
Plugin plugin= JavaCore.getPlugin();
if (plugin != null) {
String option= JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_CONDITIONAL_EXPRESSION_ALIGNMENT);
try {
if ((Integer.parseInt(option) & Integer.parseInt(DefaultCodeFormatterConstants.FORMATTER_INDENT_ON_COLUMN)) != 0)
return true;
else
return false;
} catch (NumberFormatException e) {
// ignore and return default
}
}
return false;
}
private int prefTernaryIndent() {
Plugin plugin= JavaCore.getPlugin();
if (plugin != null) {
String option= JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_CONDITIONAL_EXPRESSION_ALIGNMENT);
try {
if ((Integer.parseInt(option) & Integer.parseInt(DefaultCodeFormatterConstants.FORMATTER_INDENT_BY_ONE)) != 0)
return 1;
else
return prefContinuationIndent();
} catch (NumberFormatException e) {
// ignore and return default
}
}
return prefContinuationIndent();
}
private int prefCaseIndent() {
Plugin plugin= JavaCore.getPlugin();
if (plugin != null) {
if (DefaultCodeFormatterConstants.TRUE.equals(JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_SWITCH)))
return prefBlockIndent();
else
return 0;
}
return 0; // sun standard
}
private int prefAssignmentIndent() {
return prefBlockIndent();
}
private int prefCaseBlockIndent() {
if (true)
return prefBlockIndent();
Plugin plugin= JavaCore.getPlugin();
if (plugin != null) {
if (DefaultCodeFormatterConstants.TRUE.equals(JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_CASES)))
return prefBlockIndent();
else
return 0;
}
return prefBlockIndent(); // sun standard
}
private int prefSimpleIndent() {
return prefBlockIndent();
}
private int prefBracketIndent() {
return prefBlockIndent();
}
private boolean prefMethodDeclDeepIndent() {
Plugin plugin= JavaCore.getPlugin();
if (plugin != null) {
String option= JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_METHOD_DECLARATION_ARGUMENTS_ALIGNMENT);
try {
if ((Integer.parseInt(option) & Integer.parseInt(DefaultCodeFormatterConstants.FORMATTER_INDENT_ON_COLUMN)) != 0)
return true;
else
return false;
} catch (NumberFormatException e) {
// ignore and return default
}
}
return true;
}
private int prefMethodDeclIndent() {
Plugin plugin= JavaCore.getPlugin();
if (plugin != null) {
String option= JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_METHOD_DECLARATION_ARGUMENTS_ALIGNMENT);
try {
if ((Integer.parseInt(option) & Integer.parseInt(DefaultCodeFormatterConstants.FORMATTER_INDENT_BY_ONE)) != 0)
return 1;
else
return prefContinuationIndent();
} catch (NumberFormatException e) {
// ignore and return default
}
}
return 1;
}
private boolean prefMethodCallDeepIndent() {
Plugin plugin= JavaCore.getPlugin();
if (plugin != null) {
String option= JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_MESSAGE_SEND_ARGUMENTS_ALIGNMENT);
try {
if ((Integer.parseInt(option) & Integer.parseInt(DefaultCodeFormatterConstants.FORMATTER_INDENT_ON_COLUMN)) != 0)
return true;
else
return false;
} catch (NumberFormatException e) {
// ignore and return default
}
}
return false; // sensible default
}
private int prefMethodCallIndent() {
Plugin plugin= JavaCore.getPlugin();
if (plugin != null) {
String option= JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_MESSAGE_SEND_ARGUMENTS_ALIGNMENT);
try {
if ((Integer.parseInt(option) & Integer.parseInt(DefaultCodeFormatterConstants.FORMATTER_INDENT_BY_ONE)) != 0)
return 1;
else
return prefContinuationIndent();
} catch (NumberFormatException e) {
// ignore and return default
}
}
return 1; // sensible default
}
private boolean prefParenthesisDeepIndent() {
if (true)
return false;
Plugin plugin= JavaCore.getPlugin();
if (plugin != null) {
String option= JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_CONTINUATION_INDENTATION);
try {
if ((Integer.parseInt(option) & Integer.parseInt(DefaultCodeFormatterConstants.FORMATTER_INDENT_ON_COLUMN)) != 0)
return true;
else
return false;
} catch (NumberFormatException e) {
// ignore and return default
}
}
return false; // sensible default
}
private int prefParenthesisIndent() {
return prefContinuationIndent();
}
private int prefBlockIndent() {
return 1; // sensible default
}
private int prefContinuationIndent() {
Plugin plugin= JavaCore.getPlugin();
if (plugin != null) {
String option= JavaCore.getOption(DefaultCodeFormatterConstants.FORMATTER_CONTINUATION_INDENTATION);
try {
return Integer.parseInt(option);
} catch (NumberFormatException e) {
// ignore and return default
}
}
return 2; // sensible default
}
}
|
49,658 |
Bug 49658 Incorrect decorator for inner classes of an interface [render]
|
public interface I { class IC {} } In Package Explorere and Members IC shows up with a blue triangle (package private). It is of course public. When public is added it shows up with no decorator. In any case it is questionalbe both here and when IC is a member of a class wether the decorator should be abasent in the latter case or whether it should be the gree circle.
|
resolved fixed
|
bcb8cb0
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-26T11:23:10Z | 2004-01-08T00:00:00Z |
org.eclipse.jdt.ui/ui
| |
49,658 |
Bug 49658 Incorrect decorator for inner classes of an interface [render]
|
public interface I { class IC {} } In Package Explorere and Members IC shows up with a blue triangle (package private). It is of course public. When public is added it shows up with no decorator. In any case it is questionalbe both here and when IC is a member of a class wether the decorator should be abasent in the latter case or whether it should be the gree circle.
|
resolved fixed
|
bcb8cb0
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-26T11:23:10Z | 2004-01-08T00:00:00Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/contentassist/JavaTypeCompletionProcessor.java
| |
49,658 |
Bug 49658 Incorrect decorator for inner classes of an interface [render]
|
public interface I { class IC {} } In Package Explorere and Members IC shows up with a blue triangle (package private). It is of course public. When public is added it shows up with no decorator. In any case it is questionalbe both here and when IC is a member of a class wether the decorator should be abasent in the latter case or whether it should be the gree circle.
|
resolved fixed
|
bcb8cb0
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-26T11:23:10Z | 2004-01-08T00:00:00Z |
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.text.edits.TextEditGroup;
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.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 TextEditGroup 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 TextEditGroup getSelectionDescription() {
return fSelectionDescription;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal#getLinkedRanges()
*/
protected TextEditGroup[] getLinkedRanges() {
if (fLinkedPositions != null && !fLinkedPositions.isEmpty()) {
return (TextEditGroup[]) fLinkedPositions.toArray(new TextEditGroup[fLinkedPositions.size()]);
}
return null;
}
public TextEditGroup markAsSelection(ASTRewrite rewrite, ASTNode node) {
fSelectionDescription= new TextEditGroup("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, 1, res.length - 1, 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 TextEditGroup markAsLinked(ASTRewrite rewrite, ASTNode node, boolean isFirst, String kind) {
TextEditGroup description= new TextEditGroup(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(TextEditGroup 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;}
}
}
|
49,658 |
Bug 49658 Incorrect decorator for inner classes of an interface [render]
|
public interface I { class IC {} } In Package Explorere and Members IC shows up with a blue triangle (package private). It is of course public. When public is added it shows up with no decorator. In any case it is questionalbe both here and when IC is a member of a class wether the decorator should be abasent in the latter case or whether it should be the gree circle.
|
resolved fixed
|
bcb8cb0
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-26T11:23:10Z | 2004-01-08T00:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/ResultCollector.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text.java;
import java.util.ArrayList;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jdt.core.CompletionRequestorAdapter;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.ui.JavaElementImageDescriptor;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.corext.util.TypeFilter;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.viewsupport.ImageDescriptorRegistry;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider;
/**
* Bin to collect the proposal of the infrastructure on code assist in a java text.
*/
public class ResultCollector extends CompletionRequestorAdapter {
private final static char[] METHOD_WITH_ARGUMENTS_TRIGGERS= new char[] { '(', '-', ' ' };
private final static char[] METHOD_TRIGGERS= new char[] { ';', ',', '.', '\t', '[', ' ' };
private final static char[] TYPE_TRIGGERS= new char[] { '.', '\t', '[', '(', ' ' };
private final static char[] VAR_TRIGGER= new char[] { '\t', ' ', '=', ';', '.' };
protected IJavaProject fJavaProject;
protected ICompilationUnit fCompilationUnit; // set when imports can be added
protected int fCodeAssistOffset;
protected int fContextOffset;
protected ITextViewer fTextViewer;
private ArrayList fFields=
new ArrayList(),
fKeywords= new ArrayList(10),
fLabels= new ArrayList(10),
fMethods= new ArrayList(),
fModifiers= new ArrayList(10),
fPackages= new ArrayList(),
fTypes= new ArrayList(),
fVariables= new ArrayList();
private IProblem fLastProblem;
private ImageDescriptorRegistry fRegistry= JavaPlugin.getImageDescriptorRegistry();
private ArrayList[] fResults = new ArrayList[] {
fPackages, fLabels, fModifiers, fKeywords, fTypes, fMethods, fFields, fVariables
};
private int fUserReplacementLength;
/*
* Is eating code assist enabled or disabled? PR #3666
* When eating is enabled, JavaCompletionProposal must be revisited: PR #5533
*/
private boolean fPreventEating= true;
/*
* @see ICompletionRequestor#acceptClass
*/
public void acceptClass(char[] packageName, char[] typeName, char[] completionName, int modifiers, int start, int end, int relevance) {
if (TypeFilter.isFiltered(packageName)) {
return;
}
ImageDescriptor descriptor= JavaElementImageProvider.getTypeImageDescriptor(false, false, modifiers);
if (Flags.isDeprecated(modifiers))
descriptor= getDeprecatedDescriptor(descriptor);
ProposalInfo info= new ProposalInfo(fJavaProject, packageName, typeName);
fTypes.add(createTypeCompletion(start, end, new String(completionName), descriptor, new String(typeName), new String(packageName), info, relevance));
}
/*
* @see ICompletionRequestor#acceptError
*/
public void acceptError(IProblem error) {
fLastProblem= error;
}
/*
* @see ICompletionRequestor#acceptField
*/
public void acceptField(
char[] declaringTypePackageName, char[] declaringTypeName, char[] name,
char[] typePackageName, char[] typeName, char[] completionName,
int modifiers, int start, int end, int relevance) {
if (TypeFilter.isFiltered(declaringTypePackageName)) {
return;
}
ImageDescriptor descriptor= getFieldDescriptor(modifiers);
StringBuffer nameBuffer= new StringBuffer();
nameBuffer.append(name);
if (typeName.length > 0) {
nameBuffer.append(" "); //$NON-NLS-1$
nameBuffer.append(typeName);
}
if (declaringTypeName != null && declaringTypeName.length > 0) {
nameBuffer.append(" - "); //$NON-NLS-1$
nameBuffer.append(declaringTypeName);
}
JavaCompletionProposal proposal= createCompletion(start, end, new String(completionName), descriptor, nameBuffer.toString(), relevance);
proposal.setProposalInfo(new ProposalInfo(fJavaProject, declaringTypePackageName, declaringTypeName, name));
proposal.setTriggerCharacters(VAR_TRIGGER);
fFields.add(proposal);
}
/*
* @see ICompletionRequestor#acceptInterface
*/
public void acceptInterface(char[] packageName, char[] typeName, char[] completionName, int modifiers, int start, int end, int relevance) {
if (TypeFilter.isFiltered(packageName)) {
return;
}
ImageDescriptor descriptor= JavaElementImageProvider.getTypeImageDescriptor(true, false, modifiers);
if (Flags.isDeprecated(modifiers))
descriptor= getDeprecatedDescriptor(descriptor);
ProposalInfo info= new ProposalInfo(fJavaProject, packageName, typeName);
fTypes.add(createTypeCompletion(start, end, new String(completionName), descriptor, new String(typeName), new String(packageName), info, relevance));
}
/*
* @see ICompletionRequestor#acceptAnonymousType
*/
public void acceptAnonymousType(char[] superTypePackageName, char[] superTypeName, char[][] parameterPackageNames, char[][] parameterTypeNames, char[][] parameterNames,
char[] completionName, int modifiers, int completionStart, int completionEnd, int relevance) {
if (TypeFilter.isFiltered(superTypePackageName)) {
return;
}
JavaCompletionProposal proposal= createAnonymousTypeCompletion(superTypePackageName, superTypeName, parameterTypeNames, parameterNames, completionName, completionStart, completionEnd, relevance);
proposal.setProposalInfo(new ProposalInfo(fJavaProject, superTypePackageName, superTypeName));
fTypes.add(proposal);
}
/*
* @see ICompletionRequestor#acceptKeyword
*/
public void acceptKeyword(char[] keyword, int start, int end, int relevance) {
String kw= new String(keyword);
fKeywords.add(createCompletion(start, end, kw, null, kw, relevance));
}
/*
* @see ICompletionRequestor#acceptLabel
*/
public void acceptLabel(char[] labelName, int start, int end, int relevance) {
String ln= new String(labelName);
fLabels.add(createCompletion(start, end, ln, null, ln, relevance));
}
/*
* @see ICompletionRequestor#acceptLocalVariable
*/
public void acceptLocalVariable(char[] name, char[] typePackageName, char[] typeName, int modifiers, int start, int end, int relevance) {
StringBuffer buf= new StringBuffer();
buf.append(name);
if (typeName != null) {
buf.append(" "); //$NON-NLS-1$
buf.append(typeName);
}
JavaCompletionProposal proposal= createCompletion(start, end, new String(name), JavaPluginImages.DESC_OBJS_LOCAL_VARIABLE, buf.toString(), relevance);
proposal.setTriggerCharacters(VAR_TRIGGER);
fVariables.add(proposal);
}
protected String getParameterSignature(char[][] parameterTypeNames, char[][] parameterNames) {
StringBuffer buf = new StringBuffer();
if (parameterTypeNames != null) {
for (int i = 0; i < parameterTypeNames.length; i++) {
if (i > 0) {
buf.append(',');
buf.append(' ');
}
buf.append(parameterTypeNames[i]);
if (parameterNames != null && parameterNames[i] != null) {
buf.append(' ');
buf.append(parameterNames[i]);
}
}
}
return buf.toString();
}
/*
* @see ICompletionRequestor#acceptMethod
*/
public void acceptMethod(char[] declaringTypePackageName, char[] declaringTypeName, char[] name,
char[][] parameterPackageNames, char[][] parameterTypeNames, char[][] parameterNames,
char[] returnTypePackageName, char[] returnTypeName, char[] completionName, int modifiers,
int start, int end, int relevance) {
if (completionName == null)
return;
if (TypeFilter.isFiltered(declaringTypePackageName)) {
return;
}
JavaCompletionProposal proposal= createMethodCallCompletion(declaringTypeName, name, parameterPackageNames, parameterTypeNames, parameterNames, returnTypeName, completionName, modifiers, start, end, relevance);
boolean isConstructor= returnTypeName == null ? true : returnTypeName.length == 0;
proposal.setProposalInfo(new ProposalInfo(fJavaProject, declaringTypePackageName, declaringTypeName, name, parameterPackageNames, parameterTypeNames, isConstructor));
boolean hasOpeningBracket= completionName.length == 0 || (completionName.length > 0 && completionName[completionName.length - 1] == ')');
ProposalContextInformation contextInformation= null;
if (hasOpeningBracket && parameterTypeNames.length > 0) {
contextInformation= new ProposalContextInformation();
contextInformation.setInformationDisplayString(getParameterSignature(parameterTypeNames, parameterNames));
contextInformation.setContextDisplayString(proposal.getDisplayString());
contextInformation.setImage(proposal.getImage());
int position= (completionName.length == 0) ? fContextOffset : -1;
contextInformation.setContextInformationPosition(position);
proposal.setContextInformation(contextInformation);
}
boolean userMustCompleteParameters= (contextInformation != null && completionName.length > 0);
char[] triggers= userMustCompleteParameters ? METHOD_WITH_ARGUMENTS_TRIGGERS : METHOD_TRIGGERS;
proposal.setTriggerCharacters(triggers);
if (userMustCompleteParameters) {
// set the cursor before the closing bracket
proposal.setCursorPosition(completionName.length - 1);
}
fMethods.add(proposal);
}
/*
* @see ICompletionRequestor#acceptModifier
*/
public void acceptModifier(char[] modifier, int start, int end, int relevance) {
String mod= new String(modifier);
fModifiers.add(createCompletion(start, end, mod, null, mod, relevance));
}
/*
* @see ICompletionRequestor#acceptPackage
*/
public void acceptPackage(char[] packageName, char[] completionName, int start, int end, int relevance) {
if (TypeFilter.isFiltered(packageName)) {
return;
}
fPackages.add(createCompletion(start, end, new String(completionName), JavaPluginImages.DESC_OBJS_PACKAGE, new String(packageName), relevance));
}
/*
* @see ICompletionRequestor#acceptType
*/
public void acceptType(char[] packageName, char[] typeName, char[] completionName, int start, int end, int relevance) {
if (TypeFilter.isFiltered(packageName)) {
return;
}
ProposalInfo info= new ProposalInfo(fJavaProject, packageName, typeName);
fTypes.add(createTypeCompletion(start, end, new String(completionName), JavaPluginImages.DESC_OBJS_CLASS, new String(typeName), new String(packageName), info, relevance));
}
/*
* @see ICodeCompletionRequestor#acceptMethodDeclaration
*/
public void acceptMethodDeclaration(char[] declaringTypePackageName, char[] declaringTypeName, char[] name, char[][] parameterPackageNames, char[][] parameterTypeNames, char[][] parameterNames, char[] returnTypePackageName, char[] returnTypeName, char[] completionName, int modifiers, int start, int end, int relevance) {
StringBuffer displayString= getMethodDisplayString(declaringTypeName, name, parameterTypeNames, parameterNames, returnTypeName);
StringBuffer typeName= new StringBuffer();
if (declaringTypePackageName.length > 0) {
typeName.append(declaringTypePackageName);
typeName.append('.');
}
typeName.append(declaringTypeName);
String[] paramTypes= new String[parameterTypeNames.length];
for (int i= 0; i < parameterTypeNames.length; i++) {
paramTypes[i]= Signature.createTypeSignature(parameterTypeNames[i], true);
}
JavaCompletionProposal proposal= new MethodStubCompletionProposal(fJavaProject, fCompilationUnit, typeName.toString(), new String(name), paramTypes, start, getLength(start, end), displayString.toString(), new String(completionName));
proposal.setImage(getImage(getMemberDescriptor(modifiers)));
proposal.setProposalInfo(new ProposalInfo(fJavaProject, declaringTypePackageName, declaringTypeName, name, parameterPackageNames, parameterTypeNames, returnTypeName.length == 0));
proposal.setRelevance(relevance);
fMethods.add(proposal);
}
/*
* @see ICodeCompletionRequestor#acceptVariableName
*/
public void acceptVariableName(char[] typePackageName, char[] typeName, char[] name, char[] completionName, int start, int end, int relevance) {
// XXX: To be revised
StringBuffer buf= new StringBuffer();
buf.append(name);
if (typeName != null && typeName.length > 0) {
buf.append(" - "); //$NON-NLS-1$
buf.append(typeName);
}
JavaCompletionProposal proposal= createCompletion(start, end, new String(completionName), null, buf.toString(), relevance);
proposal.setTriggerCharacters(VAR_TRIGGER);
fVariables.add(proposal);
}
public String getErrorMessage() {
if (fLastProblem != null)
return fLastProblem.getMessage();
return ""; //$NON-NLS-1$
}
public JavaCompletionProposal[] getResults() {
// return unsorted
int totLen= 0;
for (int i= 0; i < fResults.length; i++) {
totLen += fResults[i].size();
}
JavaCompletionProposal[] result= new JavaCompletionProposal[totLen];
int k= 0;
for (int i= 0; i < fResults.length; i++) {
ArrayList curr= fResults[i];
int currLen= curr.size();
for (int j= 0; j < currLen; j++) {
JavaCompletionProposal proposal= (JavaCompletionProposal) curr.get(j);
// for equal relevance, take categories
proposal.setRelevance(proposal.getRelevance() * 16 + i);
result[k++]= proposal;
}
}
return result;
}
public JavaCompletionProposal[] getKeywordCompletions() {
return (JavaCompletionProposal[]) fKeywords.toArray(new JavaCompletionProposal[fKeywords.size()]);
}
private StringBuffer getMethodDisplayString(char[] declaringTypeName, char[] name, char[][] parameterTypeNames, char[][] parameterNames, char[] returnTypeName) {
StringBuffer nameBuffer= new StringBuffer();
nameBuffer.append(name);
nameBuffer.append('(');
if (parameterTypeNames != null && parameterTypeNames.length > 0) {
nameBuffer.append(getParameterSignature(parameterTypeNames, parameterNames));
}
nameBuffer.append(')');
if (returnTypeName != null && returnTypeName.length > 0) {
nameBuffer.append(" "); //$NON-NLS-1$
nameBuffer.append(returnTypeName);
}
if (declaringTypeName != null && declaringTypeName.length > 0) {
nameBuffer.append(" - "); //$NON-NLS-1$
nameBuffer.append(declaringTypeName);
}
return nameBuffer;
}
protected JavaCompletionProposal createMethodCallCompletion(char[] declaringTypeName, char[] name, char[][] parameterTypePackageNames, char[][] parameterTypeNames, char[][] parameterNames, char[] returnTypeName, char[] completionName, int modifiers, int start, int end, int relevance) {
ImageDescriptor descriptor= getMemberDescriptor(modifiers);
StringBuffer nameBuffer= getMethodDisplayString(declaringTypeName, name, parameterTypeNames, parameterNames, returnTypeName);
return createCompletion(start, end, new String(completionName), descriptor, nameBuffer.toString(), relevance);
}
protected JavaCompletionProposal createAnonymousTypeCompletion(char[] declaringTypePackageName, char[] declaringTypeName, char[][] parameterTypeNames, char[][] parameterNames, char[] completionName, int start, int end, int relevance) {
StringBuffer declTypeBuf= new StringBuffer();
if (declaringTypePackageName.length > 0) {
declTypeBuf.append(declaringTypePackageName);
declTypeBuf.append('.');
}
declTypeBuf.append(declaringTypeName);
StringBuffer nameBuffer= new StringBuffer();
nameBuffer.append(declaringTypeName);
nameBuffer.append('(');
if (parameterTypeNames.length > 0) {
nameBuffer.append(getParameterSignature(parameterTypeNames, parameterNames));
}
nameBuffer.append(')');
nameBuffer.append(" "); //$NON-NLS-1$
nameBuffer.append(JavaTextMessages.getString("ResultCollector.anonymous_type")); //$NON-NLS-1$
int length= end - start;
return new AnonymousTypeCompletionProposal(fJavaProject, fCompilationUnit, start, length, new String(completionName), nameBuffer.toString(), declTypeBuf.toString(), relevance);
}
protected JavaCompletionProposal createTypeCompletion(int start, int end, String completion, ImageDescriptor descriptor, String typeName, String containerName, ProposalInfo proposalInfo, int relevance) {
String fullName= JavaModelUtil.concatenateName(containerName, typeName); // containername can be null
StringBuffer buf= new StringBuffer(Signature.getSimpleName(fullName));
String typeQualifier= Signature.getQualifier(fullName);
if (typeQualifier.length() > 0) {
buf.append(" - "); //$NON-NLS-1$
buf.append(typeQualifier);
} else if (containerName != null) {
buf.append(JavaTextMessages.getString("ResultCollector.default_package")); //$NON-NLS-1$
}
String name= buf.toString();
ICompilationUnit cu= null;
if (containerName != null && fCompilationUnit != null) {
if (completion.equals(fullName)) {
cu= fCompilationUnit;
}
}
JavaCompletionProposal proposal= new JavaTypeCompletionProposal(completion, cu, start, getLength(start, end), getImage(descriptor), name, relevance, typeName, containerName);
proposal.setProposalInfo(proposalInfo);
proposal.setTriggerCharacters(TYPE_TRIGGERS);
return proposal;
}
protected ImageDescriptor getMemberDescriptor(int modifiers) {
ImageDescriptor desc= JavaElementImageProvider.getMethodImageDescriptor(false, modifiers);
if (Flags.isDeprecated(modifiers))
desc= getDeprecatedDescriptor(desc);
if (Flags.isStatic(modifiers))
desc= getStaticDescriptor(desc);
return desc;
}
protected ImageDescriptor getFieldDescriptor(int modifiers) {
ImageDescriptor desc= JavaElementImageProvider.getFieldImageDescriptor(false, modifiers);
if (Flags.isDeprecated(modifiers))
desc= getDeprecatedDescriptor(desc);
if (Flags.isStatic(modifiers))
desc= getStaticDescriptor(desc);
return desc;
}
protected ImageDescriptor getDeprecatedDescriptor(ImageDescriptor descriptor) {
Point size= new Point(16, 16);
return new JavaElementImageDescriptor(descriptor, JavaElementImageDescriptor.WARNING, size);
}
protected ImageDescriptor getStaticDescriptor(ImageDescriptor descriptor) {
Point size= new Point(16, 16);
return new JavaElementImageDescriptor(descriptor, JavaElementImageDescriptor.STATIC, size);
}
protected JavaCompletionProposal createCompletion(int start, int end, String completion, ImageDescriptor descriptor, String name, int relevance) {
return new JavaCompletionProposal(completion, start, getLength(start, end), getImage(descriptor), name, relevance, fTextViewer);
}
private int getLength(int start, int end) {
int length;
if (fUserReplacementLength == -1) {
length= fPreventEating ? fCodeAssistOffset - start : end - start;
} else {
length= fUserReplacementLength;
// extend length to begin at start
if (start < fCodeAssistOffset) {
length+= fCodeAssistOffset - start;
}
}
return length;
}
private Image getImage(ImageDescriptor descriptor) {
return (descriptor == null) ? null : fRegistry.get(descriptor);
}
/**
* Specifies the context of the code assist operation.
* @param codeAssistOffset The Offset at which the code assist will be called.
* Used to modify the offsets of the created proposals. ('Non Eating')
* @param contextOffset The offset at which the context presumable start or -1.
* @param jproject The Java project to which the underlying source belongs.
* Needed to find types referred.
* @param cu The compilation unit that is edited. Used to add import statements.
* Can be <code>null</code> if no import statements should be added.
*/
public void reset(int codeAssistOffset, int contextOffset, IJavaProject jproject, ICompilationUnit cu) {
fJavaProject= jproject;
fCompilationUnit= cu;
fCodeAssistOffset= codeAssistOffset;
fContextOffset= contextOffset;
fUserReplacementLength= -1;
fLastProblem= null;
for (int i= 0; i < fResults.length; i++)
fResults[i].clear();
}
/**
* Specifies the context of the code assist operation.
* @param codeAssistOffset The Offset on which the code assist will be called.
* Used to modify the offsets of the created proposals. ('Non Eating')
* @param jproject The Java project to which the underlying source belongs.
* Needed to find types referred.
* @param cu The compilation unit that is edited. Used to add import statements.
* Can be <code>null</code> if no import statements should be added.
*/
public void reset(int codeAssistOffset, IJavaProject jproject, ICompilationUnit cu) {
reset(codeAssistOffset, -1, jproject, cu);
}
/**
* Sets the text viewer.
*/
public void setViewer(ITextViewer viewer) {
fTextViewer= viewer;
}
/**
* If the replacement length is set, it overrides the length returned from
* the content assist infrastructure.
* Use this setting if code assist is called with a none empty selection.
*/
public void setReplacementLength(int length) {
fUserReplacementLength= length;
}
/**
* If set, proposals created will not remove characters after the code assist position
* @param preventEating The preventEating to set
*/
public void setPreventEating(boolean preventEating) {
fPreventEating= preventEating;
}
}
|
49,658 |
Bug 49658 Incorrect decorator for inner classes of an interface [render]
|
public interface I { class IC {} } In Package Explorere and Members IC shows up with a blue triangle (package private). It is of course public. When public is added it shows up with no decorator. In any case it is questionalbe both here and when IC is a member of a class wether the decorator should be abasent in the latter case or whether it should be the gree circle.
|
resolved fixed
|
bcb8cb0
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-26T11:23:10Z | 2004-01-08T00:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/HierarchyLabelProvider.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.typehierarchy;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Display;
import org.eclipse.jface.resource.CompositeImageDescriptor;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.ui.JavaElementImageDescriptor;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.viewsupport.AppearanceAwareLabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider;
/**
* Label provider for the hierarchy viewers. Types in the hierarchy that are not belonging to the
* input scope are rendered differntly.
*/
public class HierarchyLabelProvider extends AppearanceAwareLabelProvider {
private static class FocusDescriptor extends CompositeImageDescriptor {
private ImageDescriptor fBase;
public FocusDescriptor(ImageDescriptor base) {
fBase= base;
}
protected void drawCompositeImage(int width, int height) {
drawImage(fBase.getImageData(), 0, 0);
drawImage(JavaPluginImages.DESC_OVR_FOCUS.getImageData(), 0, 0);
}
protected Point getSize() {
return JavaElementImageProvider.BIG_SIZE;
}
public int hashCode() {
return fBase.hashCode();
}
public boolean equals(Object object) {
return object != null && FocusDescriptor.class.equals(object.getClass()) && ((FocusDescriptor)object).fBase.equals(fBase);
}
}
private Color fGrayedColor;
private Color fSpecialColor;
private ViewerFilter fFilter;
private TypeHierarchyLifeCycle fHierarchy;
public HierarchyLabelProvider(TypeHierarchyLifeCycle lifeCycle) {
super(DEFAULT_TEXTFLAGS, DEFAULT_IMAGEFLAGS);
fHierarchy= lifeCycle;
fFilter= null;
addLabelDecorator(new HierarchyOverrideIndicatorLabelDecorator(lifeCycle));
}
/**
* @return Returns the filter.
*/
public ViewerFilter getFilter() {
return fFilter;
}
/**
* @param filter The filter to set.
*/
public void setFilter(ViewerFilter filter) {
fFilter= filter;
}
protected boolean isDifferentScope(IType type) {
if (fFilter != null && !fFilter.select(null, null, type)) {
return true;
}
IJavaElement input= fHierarchy.getInputElement();
if (input == null || input.getElementType() == IJavaElement.TYPE) {
return false;
}
IJavaElement parent= type.getAncestor(input.getElementType());
if (input.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
if (parent == null || parent.getElementName().equals(input.getElementName())) {
return false;
}
} else if (input.equals(parent)) {
return false;
}
return true;
}
/* (non-Javadoc)
* @see ILabelProvider#getText
*/
public String getText(Object element) {
String text= super.getText(element);
return decorateText(text, element);
}
/* (non-Javadoc)
* @see ILabelProvider#getImage
*/
public Image getImage(Object element) {
Image result= null;
if (element instanceof IType) {
ImageDescriptor desc= getTypeImageDescriptor((IType) element);
if (desc != null) {
if (element.equals(fHierarchy.getInputElement())) {
desc= new FocusDescriptor(desc);
}
result= JavaPlugin.getImageDescriptorRegistry().get(desc);
}
} else {
result= fImageLabelProvider.getImageLabel(element, evaluateImageFlags(element));
}
return decorateImage(result, element);
}
private ImageDescriptor getTypeImageDescriptor(IType type) {
ITypeHierarchy hierarchy= fHierarchy.getHierarchy();
if (hierarchy == null) {
return new JavaElementImageDescriptor(JavaPluginImages.DESC_OBJS_CLASS, 0, JavaElementImageProvider.BIG_SIZE);
}
IType originalType= (IType) JavaModelUtil.toOriginal(type);
int flags= hierarchy.getCachedFlags(originalType);
if (flags == -1) {
return new JavaElementImageDescriptor(JavaPluginImages.DESC_OBJS_CLASS, 0, JavaElementImageProvider.BIG_SIZE);
}
boolean isInterface= Flags.isInterface(flags);
boolean isInner= (type.getDeclaringType() != null);
ImageDescriptor desc;
if (isDifferentScope(type)) {
desc= isInterface ? JavaPluginImages.DESC_OBJS_INTERFACEALT : JavaPluginImages.DESC_OBJS_CLASSALT;
} else {
desc= JavaElementImageProvider.getTypeImageDescriptor(isInterface, isInner, flags);
}
int adornmentFlags= 0;
if (Flags.isFinal(flags)) {
adornmentFlags |= JavaElementImageDescriptor.FINAL;
}
if (Flags.isAbstract(flags) && !isInterface) {
adornmentFlags |= JavaElementImageDescriptor.ABSTRACT;
}
if (Flags.isStatic(flags)) {
adornmentFlags |= JavaElementImageDescriptor.STATIC;
}
return new JavaElementImageDescriptor(desc, adornmentFlags, JavaElementImageProvider.BIG_SIZE);
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.IColorProvider#getForeground(java.lang.Object)
*/
public Color getForeground(Object element) {
if (element instanceof IMethod) {
if (fSpecialColor == null) {
fSpecialColor= Display.getCurrent().getSystemColor(SWT.COLOR_DARK_BLUE);
}
return fSpecialColor;
} else if (element instanceof IType && isDifferentScope((IType) element)) {
if (fGrayedColor == null) {
fGrayedColor= Display.getCurrent().getSystemColor(SWT.COLOR_DARK_GRAY);
}
return fGrayedColor;
}
return null;
}
}
|
49,658 |
Bug 49658 Incorrect decorator for inner classes of an interface [render]
|
public interface I { class IC {} } In Package Explorere and Members IC shows up with a blue triangle (package private). It is of course public. When public is added it shows up with no decorator. In any case it is questionalbe both here and when IC is a member of a class wether the decorator should be abasent in the latter case or whether it should be the gree circle.
|
resolved fixed
|
bcb8cb0
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-26T11:23:10Z | 2004-01-08T00:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/viewsupport/JavaElementImageProvider.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.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IPath;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.util.Assert;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.model.IWorkbenchAdapter;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.JavaElementImageDescriptor;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.JavaUIMessages;
/**
* Default strategy of the Java plugin for the construction of Java element icons.
*/
public class JavaElementImageProvider {
/**
* Flags for the JavaImageLabelProvider:
* Generate images with overlays.
*/
public final static int OVERLAY_ICONS= 0x1;
/**
* Generate small sized images.
*/
public final static int SMALL_ICONS= 0x2;
/**
* Use the 'light' style for rendering types.
*/
public final static int LIGHT_TYPE_ICONS= 0x4;
public static final Point SMALL_SIZE= new Point(16, 16);
public static final Point BIG_SIZE= new Point(22, 16);
private static ImageDescriptor DESC_OBJ_PROJECT_CLOSED;
private static ImageDescriptor DESC_OBJ_PROJECT;
{
ISharedImages images= JavaPlugin.getDefault().getWorkbench().getSharedImages();
DESC_OBJ_PROJECT_CLOSED= images.getImageDescriptor(ISharedImages.IMG_OBJ_PROJECT_CLOSED);
DESC_OBJ_PROJECT= images.getImageDescriptor(ISharedImages.IMG_OBJ_PROJECT);
}
private ImageDescriptorRegistry fRegistry;
public JavaElementImageProvider() {
fRegistry= null; // lazy initialization
}
/**
* Returns the icon for a given element. The icon depends on the element type
* and element properties. If configured, overlay icons are constructed for
* <code>ISourceReference</code>s.
* @param flags Flags as defined by the JavaImageLabelProvider
*/
public Image getImageLabel(Object element, int flags) {
return getImageLabel(computeDescriptor(element, flags));
}
private Image getImageLabel(ImageDescriptor descriptor){
if (descriptor == null)
return null;
return getRegistry().get(descriptor);
}
private ImageDescriptorRegistry getRegistry() {
if (fRegistry == null) {
fRegistry= JavaPlugin.getImageDescriptorRegistry();
}
return fRegistry;
}
private ImageDescriptor computeDescriptor(Object element, int flags){
if (element instanceof IJavaElement) {
return getJavaImageDescriptor((IJavaElement) element, flags);
} else if (element instanceof IFile) {
IFile file= (IFile) element;
if ("java".equals(file.getFileExtension())) { //$NON-NLS-1$
return getCUResourceImageDescriptor(file, flags); // image for a CU not on the build path
}
return getWorkbenchImageDescriptor(file, flags);
} else if (element instanceof IAdaptable) {
return getWorkbenchImageDescriptor((IAdaptable) element, flags);
}
return null;
}
private static boolean showOverlayIcons(int flags) {
return (flags & OVERLAY_ICONS) != 0;
}
private static boolean useSmallSize(int flags) {
return (flags & SMALL_ICONS) != 0;
}
private static boolean useLightIcons(int flags) {
return (flags & LIGHT_TYPE_ICONS) != 0;
}
/**
* Returns an image descriptor for a compilatio unit not on the class path.
* The descriptor includes overlays, if specified.
*/
public ImageDescriptor getCUResourceImageDescriptor(IFile file, int flags) {
Point size= useSmallSize(flags) ? SMALL_SIZE : BIG_SIZE;
return new JavaElementImageDescriptor(JavaPluginImages.DESC_OBJS_CUNIT_RESOURCE, 0, size);
}
/**
* Returns an image descriptor for a java element. The descriptor includes overlays, if specified.
*/
public ImageDescriptor getJavaImageDescriptor(IJavaElement element, int flags) {
int adornmentFlags= computeJavaAdornmentFlags(element, flags);
Point size= useSmallSize(flags) ? SMALL_SIZE : BIG_SIZE;
return new JavaElementImageDescriptor(getBaseImageDescriptor(element, flags), adornmentFlags, size);
}
/**
* Returns an image descriptor for a IAdaptable. The descriptor includes overlays, if specified (only error ticks apply).
* Returns <code>null</code> if no image could be found.
*/
public ImageDescriptor getWorkbenchImageDescriptor(IAdaptable adaptable, int flags) {
IWorkbenchAdapter wbAdapter= (IWorkbenchAdapter) adaptable.getAdapter(IWorkbenchAdapter.class);
if (wbAdapter == null) {
return null;
}
ImageDescriptor descriptor= wbAdapter.getImageDescriptor(adaptable);
if (descriptor == null) {
return null;
}
Point size= useSmallSize(flags) ? SMALL_SIZE : BIG_SIZE;
return new JavaElementImageDescriptor(descriptor, 0, size);
}
// ---- Computation of base image key -------------------------------------------------
/**
* Returns an image descriptor for a java element. This is the base image, no overlays.
*/
public ImageDescriptor getBaseImageDescriptor(IJavaElement element, int renderFlags) {
try {
switch (element.getElementType()) {
case IJavaElement.INITIALIZER:
return JavaPluginImages.DESC_MISC_PRIVATE; // 23479
case IJavaElement.METHOD:
IMember member= (IMember) element;
return getMethodImageDescriptor(member.getDeclaringType().isInterface(), member.getFlags());
case IJavaElement.FIELD:
IField field= (IField) element;
return getFieldImageDescriptor(field.getDeclaringType().isInterface(), field.getFlags());
case IJavaElement.LOCAL_VARIABLE:
return JavaPluginImages.DESC_OBJS_LOCAL_VARIABLE;
case IJavaElement.PACKAGE_DECLARATION:
return JavaPluginImages.DESC_OBJS_PACKDECL;
case IJavaElement.IMPORT_DECLARATION:
return JavaPluginImages.DESC_OBJS_IMPDECL;
case IJavaElement.IMPORT_CONTAINER:
return JavaPluginImages.DESC_OBJS_IMPCONT;
case IJavaElement.TYPE: {
IType type= (IType) element;
boolean isInterface= type.isInterface();
if (useLightIcons(renderFlags)) {
return isInterface ? JavaPluginImages.DESC_OBJS_INTERFACEALT : JavaPluginImages.DESC_OBJS_CLASSALT;
}
boolean isInner= type.getDeclaringType() != null;
return getTypeImageDescriptor(isInterface, isInner, type.getFlags());
}
case IJavaElement.PACKAGE_FRAGMENT_ROOT: {
IPackageFragmentRoot root= (IPackageFragmentRoot) element;
if (root.isArchive()) {
IPath attach= root.getSourceAttachmentPath();
if (root.isExternal()) {
if (attach == null) {
return JavaPluginImages.DESC_OBJS_EXTJAR;
} else {
return JavaPluginImages.DESC_OBJS_EXTJAR_WSRC;
}
} else {
if (attach == null) {
return JavaPluginImages.DESC_OBJS_JAR;
} else {
return JavaPluginImages.DESC_OBJS_JAR_WSRC;
}
}
} else {
return JavaPluginImages.DESC_OBJS_PACKFRAG_ROOT;
}
}
case IJavaElement.PACKAGE_FRAGMENT:
return getPackageFragmentIcon(element, renderFlags);
case IJavaElement.COMPILATION_UNIT:
return JavaPluginImages.DESC_OBJS_CUNIT;
case IJavaElement.CLASS_FILE:
/* this is too expensive for large packages
try {
IClassFile cfile= (IClassFile)element;
if (cfile.isClass())
return JavaPluginImages.IMG_OBJS_CFILECLASS;
return JavaPluginImages.IMG_OBJS_CFILEINT;
} catch(JavaModelException e) {
// fall through;
}*/
return JavaPluginImages.DESC_OBJS_CFILE;
case IJavaElement.JAVA_PROJECT:
IJavaProject jp= (IJavaProject)element;
if (jp.getProject().isOpen()) {
IProject project= jp.getProject();
IWorkbenchAdapter adapter= (IWorkbenchAdapter)project.getAdapter(IWorkbenchAdapter.class);
if (adapter != null) {
ImageDescriptor result= adapter.getImageDescriptor(project);
if (result != null)
return result;
}
return DESC_OBJ_PROJECT;
}
return DESC_OBJ_PROJECT_CLOSED;
case IJavaElement.JAVA_MODEL:
return JavaPluginImages.DESC_OBJS_JAVA_MODEL;
}
Assert.isTrue(false, JavaUIMessages.getString("JavaImageLabelprovider.assert.wrongImage")); //$NON-NLS-1$
return null; //$NON-NLS-1$
} catch (JavaModelException e) {
if (e.isDoesNotExist())
return JavaPluginImages.DESC_OBJS_UNKNOWN;
JavaPlugin.log(e);
return JavaPluginImages.DESC_OBJS_GHOST;
}
}
protected ImageDescriptor getPackageFragmentIcon(IJavaElement element, int renderFlags) throws JavaModelException {
IPackageFragment fragment= (IPackageFragment)element;
boolean containsJavaElements= false;
try {
containsJavaElements= fragment.hasChildren();
} catch(JavaModelException e) {
// assuming no children;
}
if(!containsJavaElements && (fragment.getNonJavaResources().length > 0))
return JavaPluginImages.DESC_OBJS_EMPTY_PACKAGE_RESOURCES;
else if (!containsJavaElements)
return JavaPluginImages.DESC_OBJS_EMPTY_PACKAGE;
return JavaPluginImages.DESC_OBJS_PACKAGE;
}
public void dispose() {
}
// ---- Methods to compute the adornments flags ---------------------------------
private int computeJavaAdornmentFlags(IJavaElement element, int renderFlags) {
int flags= 0;
if (showOverlayIcons(renderFlags) && element instanceof IMember) {
try {
IMember member= (IMember) element;
if (element.getElementType() == IJavaElement.METHOD && ((IMethod)element).isConstructor())
flags |= JavaElementImageDescriptor.CONSTRUCTOR;
int modifiers= member.getFlags();
if (Flags.isAbstract(modifiers) && confirmAbstract(member))
flags |= JavaElementImageDescriptor.ABSTRACT;
if (Flags.isFinal(modifiers) || isInterfaceField(member))
flags |= JavaElementImageDescriptor.FINAL;
if (Flags.isSynchronized(modifiers) && confirmSynchronized(member))
flags |= JavaElementImageDescriptor.SYNCHRONIZED;
if (Flags.isStatic(modifiers) || isInterfaceField(member))
flags |= JavaElementImageDescriptor.STATIC;
if (member.getElementType() == IJavaElement.TYPE) {
if (JavaModelUtil.hasMainMethod((IType) member)) {
flags |= JavaElementImageDescriptor.RUNNABLE;
}
}
} catch (JavaModelException e) {
// do nothing. Can't compute runnable adornment or get flags
}
}
return flags;
}
private static boolean confirmAbstract(IMember element) throws JavaModelException {
// never show the abstract symbol on interfaces or members in interfaces
if (element.getElementType() == IJavaElement.TYPE) {
return ((IType) element).isClass();
}
return element.getDeclaringType().isClass();
}
private static boolean isInterfaceField(IMember element) throws JavaModelException {
// always show the final && static symbol on interface fields
if (element.getElementType() == IJavaElement.FIELD) {
return element.getDeclaringType().isInterface();
}
return false;
}
private static boolean confirmSynchronized(IJavaElement member) {
// Synchronized types are allowed but meaningless.
return member.getElementType() != IJavaElement.TYPE;
}
public static ImageDescriptor getMethodImageDescriptor(boolean isInInterface, int flags) {
if (Flags.isPublic(flags) || isInInterface)
return JavaPluginImages.DESC_MISC_PUBLIC;
if (Flags.isProtected(flags))
return JavaPluginImages.DESC_MISC_PROTECTED;
if (Flags.isPrivate(flags))
return JavaPluginImages.DESC_MISC_PRIVATE;
return JavaPluginImages.DESC_MISC_DEFAULT;
}
public static ImageDescriptor getFieldImageDescriptor(boolean isInInterface, int flags) {
if (Flags.isPublic(flags) || isInInterface)
return JavaPluginImages.DESC_FIELD_PUBLIC;
if (Flags.isProtected(flags))
return JavaPluginImages.DESC_FIELD_PROTECTED;
if (Flags.isPrivate(flags))
return JavaPluginImages.DESC_FIELD_PRIVATE;
return JavaPluginImages.DESC_FIELD_DEFAULT;
}
public static ImageDescriptor getTypeImageDescriptor(boolean isInterface, boolean isInner, int flags) {
if (isInner) {
if (isInterface) {
return getInnerInterfaceImageDescriptor(flags);
} else {
return getInnerClassImageDescriptor(flags);
}
} else {
if (isInterface) {
return getInterfaceImageDescriptor(flags);
} else {
return getClassImageDescriptor(flags);
}
}
}
private static ImageDescriptor getClassImageDescriptor(int flags) {
if (Flags.isPublic(flags) || Flags.isProtected(flags) || Flags.isPrivate(flags))
return JavaPluginImages.DESC_OBJS_CLASS;
else
return JavaPluginImages.DESC_OBJS_CLASS_DEFAULT;
}
private static ImageDescriptor getInnerClassImageDescriptor(int flags) {
if (Flags.isPublic(flags))
return JavaPluginImages.DESC_OBJS_INNER_CLASS_PUBLIC;
else if (Flags.isPrivate(flags))
return JavaPluginImages.DESC_OBJS_INNER_CLASS_PRIVATE;
else if (Flags.isProtected(flags))
return JavaPluginImages.DESC_OBJS_INNER_CLASS_PROTECTED;
else
return JavaPluginImages.DESC_OBJS_INNER_CLASS_DEFAULT;
}
private static ImageDescriptor getInterfaceImageDescriptor(int flags) {
if (Flags.isPublic(flags) || Flags.isProtected(flags) || Flags.isPrivate(flags))
return JavaPluginImages.DESC_OBJS_INTERFACE;
else
return JavaPluginImages.DESC_OBJS_INTERFACE_DEFAULT;
}
private static ImageDescriptor getInnerInterfaceImageDescriptor(int flags) {
if (Flags.isPublic(flags))
return JavaPluginImages.DESC_OBJS_INNER_INTERFACE_PUBLIC;
else if (Flags.isPrivate(flags))
return JavaPluginImages.DESC_OBJS_INNER_INTERFACE_PRIVATE;
else if (Flags.isProtected(flags))
return JavaPluginImages.DESC_OBJS_INNER_INTERFACE_PROTECTED;
else
return JavaPluginImages.DESC_OBJS_INTERFACE_DEFAULT;
}
}
|
50,100 |
Bug 50100 [Performance] Huge performance issue with problem decorators
|
Using 0106 build, it takes minutes to update the markers for a compilation unit containing 250 problems (maximum limit). Each time I save the unit, the UI dies for several minutes. There is a running job in the background that I cannot identify. This is something new. I was not that bad with M5. I set it as critical, because it makes the editor unusable.
|
resolved fixed
|
5fc0fa9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-26T14:23:48Z | 2004-01-15T20: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:
case IJavaElement.LOCAL_VARIABLE:
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(cu, 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 (pos != null && (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);
}
}
}
|
50,658 |
Bug 50658 3 type constraint tests failing
|
20040126 TypeConstraintTests.testConstraints4 TypeConstraintTests.testConstraints8 TypeConstraintTests.testConstraints19 are failing. I disabled them for now as the refactoring tests suites are unaffected.
|
resolved fixed
|
38cd8fd
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-27T07:41:30Z | 2004-01-27T07:53:20Z |
org.eclipse.jdt.ui.tests.refactoring/test
| |
50,658 |
Bug 50658 3 type constraint tests failing
|
20040126 TypeConstraintTests.testConstraints4 TypeConstraintTests.testConstraints8 TypeConstraintTests.testConstraints19 are failing. I disabled them for now as the refactoring tests suites are unaffected.
|
resolved fixed
|
38cd8fd
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-27T07:41:30Z | 2004-01-27T07:53:20Z |
cases/org/eclipse/jdt/ui/tests/typeconstraints/TypeConstraintTests.java
| |
50,212 |
Bug 50212 [formatting] Repeated insertion of new line when formatting javadoc comment
|
Formatting the following javadoc comment multiple times results in the insertion of a new line before 'test' *each* time: /** * <pre></pre> * test */
|
verified fixed
|
d65091a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-27T09:47:29Z | 2004-01-19T13:46:40Z |
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, ICommentAttributes {
/** 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 fClear;
/** 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;
fClear= IPreferenceStore.TRUE.equals(fStrategy.getPreferences().get(PreferenceConstants.FORMATTER_COMMENT_CLEARBLANKLINES));
final ISourceViewer viewer= strategy.getViewer();
final StyledText text= viewer.getTextWidget();
fDocument= viewer.getDocument();
if (text != null && !text.isDisposed()) {
fGraphics= new GC(text);
fGraphics.setFont(text.getFont());
fTabs= text.getTabs();
} else {
fGraphics= null;
fTabs= 4;
}
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(new CommentRange(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 final void append(final CommentRange range) {
fRanges.addLast(range);
}
/**
* Applies the formatted comment region to the underlying document.
*
* @param indentation
* Indentation of the formatted comment region
* @param width
* The maximal width of text in this comment region measured in
* average character widths
*/
protected void applyRegion(final String indentation, final int width) {
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, width);
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, width);
}
}
/**
* Applies the changed content to the underlying document
*
* @param change
* Text content to apply to the underlying document
* @param position
* Offset measured in comment region coordinates where to apply
* the changed content
* @param count
* Length of the content to be changed
*/
protected final void applyText(final String change, final int position, final int count) {
try {
final int base= getOffset() + position;
final String content= fDocument.get(base, count);
if (!change.equals(content))
fDocument.replace(getOffset() + position, count, 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 width
* The maximal width 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 width) {
return space == 0 || space + next.getLength() < width;
}
/**
* 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 String probe= getText(0, CommentLine.NON_FORMAT_START_PREFIX.length());
if (probe.startsWith(CommentLine.NON_FORMAT_START_PREFIX))
return;
final Map preferences= fStrategy.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);
fDocument.addPositionCategory(COMMENT_POSITION_CATEGORY);
final IPositionUpdater positioner= new DefaultPositionUpdater(COMMENT_POSITION_CATEGORY);
fDocument.addPositionUpdater(positioner);
try {
initializeRegion();
markRegion();
wrapRegion(margin);
applyRegion(indentation, margin);
finalizeRegion(indentation);
} finally {
if (fGraphics != null && !fGraphics.isDisposed())
fGraphics.dispose();
try {
fDocument.removePositionCategory(COMMENT_POSITION_CATEGORY);
fDocument.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
*/
protected final CommentFormattingStrategy getStrategy() {
return fStrategy;
}
/**
* Returns the text of this comment region in the indicated range.
*
* @param position
* The offset of the comment range to retrieve in comment region
* coordinates
* @param count
* 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 position, final int count) {
String content= ""; //$NON-NLS-1$
try {
content= fDocument.get(getOffset() + position, count);
} 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 {
fDocument.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 isClearLines() {
return fClear;
}
/**
* 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 index= 0; index < token.length(); index++) {
if (!Character.isLetterOrDigit(token.charAt(index)))
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 final String stringToIndent(final String reference, final boolean tabs) {
int space= 1;
int pixels= reference.length();
if (fGraphics != null) {
pixels= stringToPixels(reference);
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 final int stringToLength(final String reference) {
int tabs= 0;
int count= reference.length();
for (int index= 0; index < count; index++) {
if (reference.charAt(index) == '\t')
tabs++;
}
count += tabs * (fTabs - 1);
return count;
}
/**
* 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 final int stringToPixels(final String reference) {
final StringBuffer buffer= new StringBuffer();
char character= 0;
for (int index= 0; index < reference.length(); index++) {
character= reference.charAt(index);
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 width
* The maximal width of text in this comment region measured in
* average character widths
*/
protected void wrapRegion(final int width) {
fLines.clear();
int index= 0;
boolean adapted= false;
CommentLine successor= null;
CommentLine predecessor= null;
CommentRange previous= null;
CommentRange next= null;
while (!fRanges.isEmpty()) {
index= 0;
adapted= false;
predecessor= successor;
successor= CommentObjectFactory.createLine(this);
fLines.add(successor);
while (!fRanges.isEmpty()) {
next= (CommentRange)fRanges.getFirst();
if (canAppend(successor, previous, next, index, width)) {
if (!adapted && predecessor != null) {
successor.adapt(predecessor);
adapted= true;
}
fRanges.removeFirst();
successor.append(next);
index += (next.getLength() + 1);
previous= next;
} else
break;
}
}
}
}
|
50,212 |
Bug 50212 [formatting] Repeated insertion of new line when formatting javadoc comment
|
Formatting the following javadoc comment multiple times results in the insertion of a new line before 'test' *each* time: /** * <pre></pre> * test */
|
verified fixed
|
d65091a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-27T09:47:29Z | 2004-01-19T13:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/comment/MultiCommentRegion.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.ListIterator;
import java.util.Map;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.TypedPosition;
import org.eclipse.jdt.ui.PreferenceConstants;
/**
* Multi-comment region in a source code document.
*
* @since 3.0
*/
public class MultiCommentRegion extends CommentRegion implements ICommentTagConstants {
/** Should root tag parameter descriptions be indented after the tag? */
private final boolean fIndentDescriptions;
/** Should root tag parameter descriptions be indented? */
private final boolean fIndentRoots;
/** Should description of parameters go to the next line? */
private final boolean fParameterNewLine;
/** Should root tags be separated from description? */
private boolean fSeparateRoots;
/**
* Creates a new multi-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 MultiCommentRegion(final CommentFormattingStrategy strategy, final TypedPosition position, final String delimiter) {
super(strategy, position, delimiter);
final Map preferences= strategy.getPreferences();
fIndentRoots= IPreferenceStore.TRUE.equals(preferences.get(PreferenceConstants.FORMATTER_COMMENT_INDENTROOTTAGS));
fIndentDescriptions= IPreferenceStore.TRUE.equals(preferences.get(PreferenceConstants.FORMATTER_COMMENT_INDENTPARAMETERDESCRIPTION));
fSeparateRoots= IPreferenceStore.TRUE.equals(preferences.get(PreferenceConstants.FORMATTER_COMMENT_SEPARATEROOTTAGS));
fParameterNewLine= IPreferenceStore.TRUE.equals(preferences.get(PreferenceConstants.FORMATTER_COMMENT_NEWLINEFORPARAMETER));
}
/*
* @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 position, int count) {
final boolean blank= next.hasAttribute(COMMENT_BLANKLINE);
// TODO does not work for TestCase.java: <br>1) is not wrapped
if (next.getLength() <= 2 && !blank && !isCommentWord(next))
return true;
if (fParameterNewLine && line.hasAttribute(COMMENT_PARAMETER) && line.getSize() > 1)
return false;
if (previous != null) {
if (previous.hasAttribute(COMMENT_ROOT))
return true;
if (position != 0 && (blank || previous.hasAttribute(COMMENT_BLANKLINE) || next.hasAttribute(COMMENT_PARAMETER) || next.hasAttribute(COMMENT_ROOT) || next.hasAttribute(COMMENT_SEPARATOR) || next.hasAttribute(COMMENT_NEWLINE) || previous.hasAttribute(COMMENT_BREAK) || previous.hasAttribute(COMMENT_SEPARATOR)))
return false;
if (next.hasAttribute(COMMENT_IMMUTABLE) && previous.hasAttribute(COMMENT_IMMUTABLE))
return true;
}
if (fIndentRoots && !line.hasAttribute(COMMENT_ROOT) && !line.hasAttribute(COMMENT_PARAMETER))
count -= stringToLength(line.getIndentation());
return super.canAppend(line, previous, next, position, count);
}
/*
* @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(CommentLine predecessor, CommentLine successor, CommentRange previous, CommentRange next, String indentation) {
final String delimiter= super.getDelimiter(predecessor, successor, previous, next, indentation);
if (previous != null) {
if (previous.hasAttribute(COMMENT_IMMUTABLE | COMMENT_SEPARATOR) && !next.hasAttribute(COMMENT_CODE) && !successor.hasAttribute(COMMENT_BLANKLINE))
return delimiter + delimiter;
else if (previous.hasAttribute(COMMENT_CODE) && !next.hasAttribute(COMMENT_CODE))
return getDelimiter();
// remove any asterix borders inside code sections
else if (previous.hasAttribute(COMMENT_CODE) && next.hasAttribute(COMMENT_CODE))
return getDelimiter();
else if ((next.hasAttribute(COMMENT_IMMUTABLE | COMMENT_SEPARATOR) || ((fSeparateRoots || !isClearLines()) && previous.hasAttribute(COMMENT_PARAGRAPH))) && !successor.hasAttribute(COMMENT_BLANKLINE))
return delimiter + delimiter;
else if (fIndentRoots && !predecessor.hasAttribute(COMMENT_ROOT) && !predecessor.hasAttribute(COMMENT_PARAMETER) && !predecessor.hasAttribute(COMMENT_BLANKLINE))
return delimiter + stringToIndent(predecessor.getIndentation(), 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(COMMENT_CODE) && previous.hasAttribute(COMMENT_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 root tag parameter descriptions be indented after the tag?
*
* @return <code>true</code> iff the descriptions should be indented after,
* <code>false</code> otherwise.
*/
protected final boolean isIndentDescriptions() {
return fIndentDescriptions;
}
/**
* Should root tag parameter descriptions be indented?
*
* @return <code>true</code> iff the root tags should be indented,
* <code>false</code> otherwise.
*/
protected final boolean isIndentRoots() {
return fIndentRoots;
}
/**
* Marks the comment ranges confined by html tags.
*/
protected void markHtmlRanges() {
// Do nothing
}
/**
* Marks the comment range with its html tag attributes.
*
* @param range
* The comment range to mark
* @param token
* Token associated with the comment range
*/
protected void markHtmlTag(final CommentRange range, final String token) {
// Do nothing
}
/**
* Marks the comment range with its javadoc tag attributes.
*
* @param range
* The comment range to mark
* @param token
* Token associated with the comment range
*/
protected void markJavadocTag(final CommentRange range, final String token) {
range.markPrefixTag(COMMENT_ROOT_TAGS, COMMENT_TAG_PREFIX, token, COMMENT_ROOT);
}
/*
* @see org.eclipse.jdt.internal.ui.text.comment.CommentRegion#markRegion()
*/
protected final void markRegion() {
int count= 0;
boolean paragraph= false;
String token= null;
CommentRange range= null;
CommentRange blank= null;
for (final ListIterator iterator= getRanges().listIterator(); iterator.hasNext();) {
range= (CommentRange)iterator.next();
count= range.getLength();
if (count > 0) {
token= getText(range.getOffset(), count).toLowerCase();
markJavadocTag(range, token);
if (!paragraph && (range.hasAttribute(COMMENT_ROOT) || range.hasAttribute(COMMENT_PARAMETER))) {
iterator.previous();
while (iterator.hasPrevious()) {
blank= (CommentRange)iterator.previous();
if (blank.hasAttribute(COMMENT_BLANKLINE))
iterator.remove();
else
break;
}
range.setAttribute(COMMENT_PARAGRAPH);
paragraph= true;
}
markHtmlTag(range, token);
}
}
markHtmlRanges();
}
}
|
50,745 |
Bug 50745 [misc] StringIndexOutOfBoundsException while indenting
|
Note: I had plenty of compile and syntax errors in my source (-> refactoring using regexprs and other brute force methods). But all the parens/braces/brackets were matched, so I nevertheless expected the indenter to produce valid output. !MESSAGE Action for command 'org.eclipse.jdt.ui.edit.text.java.indent' failed to execute properly. !STACK 0 java.lang.StringIndexOutOfBoundsException: String index out of range: 0 at java.lang.StringBuffer.charAt(StringBuffer.java:283) at org.eclipse.jdt.internal.ui.actions.IndentAction.indentLine(IndentAction.java:257) at org.eclipse.jdt.internal.ui.actions.IndentAction.access$1(IndentAction.java:211) at org.eclipse.jdt.internal.ui.actions.IndentAction$1.run(IndentAction.java:133) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:84) at org.eclipse.jdt.internal.ui.actions.IndentAction.run(IndentAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:881) at org.eclipse.ui.internal.commands.ActionHandler.execute(ActionHandler.java:40) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.executeCommand(WorkbenchKeyboard.java:414) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.press(WorkbenchKeyboard.java:778) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.processKeyEvent(WorkbenchKeyboard.java:815) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.filterKeySequenceBindings(WorkbenchKeyboard.java:505) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.access$2(WorkbenchKeyboard.java:444) at org.eclipse.ui.internal.keys.WorkbenchKeyboard$1.handleEvent(WorkbenchKeyboard.java:233) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Display.filterEvent(Display.java:699) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:832) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:857) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:842) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1716) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1712) at org.eclipse.swt.widgets.Control.WM_CHAR(Control.java:3037) at org.eclipse.swt.widgets.Control.windowProc(Control.java:2940) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2865) at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:1371) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:2019) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1530) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1506) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:265) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:47) at org.eclipse.core.internal.runtime.PlatformActivator$1.run(PlatformActivator.java:248) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:85) 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:279) at org.eclipse.core.launcher.Main.run(Main.java:742) at org.eclipse.core.launcher.Main.main(Main.java:581) Action for command 'org.eclipse.jdt.ui.edit.text.java.indent' failed to execute properly.
|
verified fixed
|
fce0c2a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-28T10:27:06Z | 2004-01-28T08:53:20Z |
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.jface.text.source.ISourceViewer;
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.javaeditor.JavaEditor;
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
* @param isTabAction whether the action should insert tabs if over the indentation
*/
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() || !validateEditorInputState())
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;
fCaretOffset= -1;
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, "", e)); //$NON-NLS-1$
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, newLength;
if (fIsTabAction) {
newOffset= fCaretOffset;
newLength= 0;
} else if (nLines > 1) {
newOffset= offset;
newLength= end.getOffset() - offset;
} else {
newOffset= fCaretOffset;
newLength= 0;
}
// always reset the selection if anything was replaced
// but not when we had a singleline nontab invocation
if (newOffset != -1 && (hasChanged || newOffset != offset || newLength != length))
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, "ConcurrentModification in IndentAction", e)); //$NON-NLS-1$
} 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();
}
}
/**
* Selects the given range on the editor.
*
* @param newOffset the selection offset
* @param newLength the selection range
*/
private void selectAndReveal(int newOffset, int newLength) {
Assert.isTrue(newOffset >= 0);
Assert.isTrue(newLength >= 0);
ITextEditor editor= getTextEditor();
if (editor instanceof JavaEditor) {
ISourceViewer viewer= ((JavaEditor)editor).getViewer();
if (viewer != null)
viewer.setSelectedRange(newOffset, newLength);
} else
// this is too intrusive, but will never get called anyway
getTextEditor().selectAndReveal(newOffset, newLength);
}
/**
* 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();
int wsStart= offset; // where we start searching for non-WS; after the "//" in single line comments
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;
int start= 0;
if (line > 0) {
IRegion previousLine= document.getLineInformation(line - 1);
start= previousLine.getOffset() + previousLine.getLength();
}
DocumentCommand command= new DocumentCommand() {};
command.text= "\n"; //$NON-NLS-1$
command.offset= start;
new JavaDocAutoIndentStrategy(IJavaPartitions.JAVA_PARTITIONING).customizeDocumentCommand(document, command);
int to= 1;
while (to < command.text.length() && Character.isWhitespace(command.text.charAt(to)))
to++;
indent= command.text.substring(1, to);
} else if (partition.getOffset() == offset && type.equals(IJavaPartitions.JAVA_SINGLE_LINE_COMMENT)) {
// line comment starting at position 0 -> indent inside
int slashes= 2;
while (slashes < document.getLength() - 1 && document.get(offset + slashes, 2).equals("//")) //$NON-NLS-1$
slashes+= 2;
wsStart= offset + slashes;
StringBuffer computed= indenter.computeIndentation(offset);
int tabSize= JavaPlugin.getDefault().getPreferenceStore().getInt(PreferenceConstants.EDITOR_TAB_WIDTH);
while (slashes > 0) {
char c= computed.charAt(0);
if (c == '\t')
if (slashes > tabSize)
slashes-= tabSize;
else
break;
else if (c == ' ')
slashes--;
else break;
computed.deleteCharAt(0);
}
indent= document.get(offset, wsStart - offset) + computed;
}
}
// standard java indentation
if (indent == null) {
StringBuffer computed= indenter.computeIndentation(offset);
if (computed != null)
indent= computed.toString();
else
indent= new String();
}
// change document:
// get current white space
int lineLength= currentLine.getLength();
int end= scanner.findNonWhitespaceForwardInAnyPartition(wsStart, 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
if (caret >= offset && caret <= end)
fCaretOffset= offset + indent.length();
else
fCaretOffset= -1;
// 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();
}
}
|
46,935 |
Bug 46935 Change method signature: More comfort for entering types [refactoring]
|
20031119 In the 'Refactoring > Change Method Signature' dialog, entering the return type as well as entering parameter type is very cumbersome. - No browse to choose a type - No combo for 'int', 'void' ect - Not clear how imports are handled. Do I have to enter qualified types to get imports, or will this result in qualified names in the code? - No validation as you type in for parameter fields. As this is a refactoring it looks strange that you can enter a non-existing file name. I would suggest that always fully qualified type are shown and that the refactoring creates imports but uses simple names.
|
resolved fixed
|
35d8e13
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-30T08:53:51Z | 2003-11-19T11:06:40Z |
org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature/canModify/A_testImport01_in.java
| |
46,935 |
Bug 46935 Change method signature: More comfort for entering types [refactoring]
|
20031119 In the 'Refactoring > Change Method Signature' dialog, entering the return type as well as entering parameter type is very cumbersome. - No browse to choose a type - No combo for 'int', 'void' ect - Not clear how imports are handled. Do I have to enter qualified types to get imports, or will this result in qualified names in the code? - No validation as you type in for parameter fields. As this is a refactoring it looks strange that you can enter a non-existing file name. I would suggest that always fully qualified type are shown and that the refactoring creates imports but uses simple names.
|
resolved fixed
|
35d8e13
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-30T08:53:51Z | 2003-11-19T11:06:40Z |
org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature/canModify/A_testImport01_out.java
| |
46,935 |
Bug 46935 Change method signature: More comfort for entering types [refactoring]
|
20031119 In the 'Refactoring > Change Method Signature' dialog, entering the return type as well as entering parameter type is very cumbersome. - No browse to choose a type - No combo for 'int', 'void' ect - Not clear how imports are handled. Do I have to enter qualified types to get imports, or will this result in qualified names in the code? - No validation as you type in for parameter fields. As this is a refactoring it looks strange that you can enter a non-existing file name. I would suggest that always fully qualified type are shown and that the refactoring creates imports but uses simple names.
|
resolved fixed
|
35d8e13
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-30T08:53:51Z | 2003-11-19T11:06:40Z |
org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature/canModify/A_testImport02_in.java
| |
46,935 |
Bug 46935 Change method signature: More comfort for entering types [refactoring]
|
20031119 In the 'Refactoring > Change Method Signature' dialog, entering the return type as well as entering parameter type is very cumbersome. - No browse to choose a type - No combo for 'int', 'void' ect - Not clear how imports are handled. Do I have to enter qualified types to get imports, or will this result in qualified names in the code? - No validation as you type in for parameter fields. As this is a refactoring it looks strange that you can enter a non-existing file name. I would suggest that always fully qualified type are shown and that the refactoring creates imports but uses simple names.
|
resolved fixed
|
35d8e13
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-30T08:53:51Z | 2003-11-19T11:06:40Z |
org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature/canModify/A_testImport02_out.java
| |
46,935 |
Bug 46935 Change method signature: More comfort for entering types [refactoring]
|
20031119 In the 'Refactoring > Change Method Signature' dialog, entering the return type as well as entering parameter type is very cumbersome. - No browse to choose a type - No combo for 'int', 'void' ect - Not clear how imports are handled. Do I have to enter qualified types to get imports, or will this result in qualified names in the code? - No validation as you type in for parameter fields. As this is a refactoring it looks strange that you can enter a non-existing file name. I would suggest that always fully qualified type are shown and that the refactoring creates imports but uses simple names.
|
resolved fixed
|
35d8e13
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-30T08:53:51Z | 2003-11-19T11:06:40Z |
org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature/canModify/A_testImport03_in.java
| |
46,935 |
Bug 46935 Change method signature: More comfort for entering types [refactoring]
|
20031119 In the 'Refactoring > Change Method Signature' dialog, entering the return type as well as entering parameter type is very cumbersome. - No browse to choose a type - No combo for 'int', 'void' ect - Not clear how imports are handled. Do I have to enter qualified types to get imports, or will this result in qualified names in the code? - No validation as you type in for parameter fields. As this is a refactoring it looks strange that you can enter a non-existing file name. I would suggest that always fully qualified type are shown and that the refactoring creates imports but uses simple names.
|
resolved fixed
|
35d8e13
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-30T08:53:51Z | 2003-11-19T11:06:40Z |
org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature/canModify/A_testImport03_out.java
| |
46,935 |
Bug 46935 Change method signature: More comfort for entering types [refactoring]
|
20031119 In the 'Refactoring > Change Method Signature' dialog, entering the return type as well as entering parameter type is very cumbersome. - No browse to choose a type - No combo for 'int', 'void' ect - Not clear how imports are handled. Do I have to enter qualified types to get imports, or will this result in qualified names in the code? - No validation as you type in for parameter fields. As this is a refactoring it looks strange that you can enter a non-existing file name. I would suggest that always fully qualified type are shown and that the refactoring creates imports but uses simple names.
|
resolved fixed
|
35d8e13
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-30T08:53:51Z | 2003-11-19T11:06:40Z |
org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature/canModify/A_testImport04_in.java
| |
46,935 |
Bug 46935 Change method signature: More comfort for entering types [refactoring]
|
20031119 In the 'Refactoring > Change Method Signature' dialog, entering the return type as well as entering parameter type is very cumbersome. - No browse to choose a type - No combo for 'int', 'void' ect - Not clear how imports are handled. Do I have to enter qualified types to get imports, or will this result in qualified names in the code? - No validation as you type in for parameter fields. As this is a refactoring it looks strange that you can enter a non-existing file name. I would suggest that always fully qualified type are shown and that the refactoring creates imports but uses simple names.
|
resolved fixed
|
35d8e13
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-30T08:53:51Z | 2003-11-19T11:06:40Z |
org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature/canModify/A_testImport04_out.java
| |
46,935 |
Bug 46935 Change method signature: More comfort for entering types [refactoring]
|
20031119 In the 'Refactoring > Change Method Signature' dialog, entering the return type as well as entering parameter type is very cumbersome. - No browse to choose a type - No combo for 'int', 'void' ect - Not clear how imports are handled. Do I have to enter qualified types to get imports, or will this result in qualified names in the code? - No validation as you type in for parameter fields. As this is a refactoring it looks strange that you can enter a non-existing file name. I would suggest that always fully qualified type are shown and that the refactoring creates imports but uses simple names.
|
resolved fixed
|
35d8e13
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-30T08:53:51Z | 2003-11-19T11:06:40Z |
org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature/cannotModify/A_testFailImport01.java
| |
46,935 |
Bug 46935 Change method signature: More comfort for entering types [refactoring]
|
20031119 In the 'Refactoring > Change Method Signature' dialog, entering the return type as well as entering parameter type is very cumbersome. - No browse to choose a type - No combo for 'int', 'void' ect - Not clear how imports are handled. Do I have to enter qualified types to get imports, or will this result in qualified names in the code? - No validation as you type in for parameter fields. As this is a refactoring it looks strange that you can enter a non-existing file name. I would suggest that always fully qualified type are shown and that the refactoring creates imports but uses simple names.
|
resolved fixed
|
35d8e13
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-30T08:53:51Z | 2003-11-19T11:06:40Z |
org.eclipse.jdt.ui.tests.refactoring/test
| |
46,935 |
Bug 46935 Change method signature: More comfort for entering types [refactoring]
|
20031119 In the 'Refactoring > Change Method Signature' dialog, entering the return type as well as entering parameter type is very cumbersome. - No browse to choose a type - No combo for 'int', 'void' ect - Not clear how imports are handled. Do I have to enter qualified types to get imports, or will this result in qualified names in the code? - No validation as you type in for parameter fields. As this is a refactoring it looks strange that you can enter a non-existing file name. I would suggest that always fully qualified type are shown and that the refactoring creates imports but uses simple names.
|
resolved fixed
|
35d8e13
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-30T08:53:51Z | 2003-11-19T11:06:40Z |
cases/org/eclipse/jdt/ui/tests/refactoring/ChangeSignatureTests.java
| |
46,935 |
Bug 46935 Change method signature: More comfort for entering types [refactoring]
|
20031119 In the 'Refactoring > Change Method Signature' dialog, entering the return type as well as entering parameter type is very cumbersome. - No browse to choose a type - No combo for 'int', 'void' ect - Not clear how imports are handled. Do I have to enter qualified types to get imports, or will this result in qualified names in the code? - No validation as you type in for parameter fields. As this is a refactoring it looks strange that you can enter a non-existing file name. I would suggest that always fully qualified type are shown and that the refactoring creates imports but uses simple names.
|
resolved fixed
|
35d8e13
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-30T08:53:51Z | 2003-11-19T11:06:40Z |
org.eclipse.jdt.ui/core
| |
46,935 |
Bug 46935 Change method signature: More comfort for entering types [refactoring]
|
20031119 In the 'Refactoring > Change Method Signature' dialog, entering the return type as well as entering parameter type is very cumbersome. - No browse to choose a type - No combo for 'int', 'void' ect - Not clear how imports are handled. Do I have to enter qualified types to get imports, or will this result in qualified names in the code? - No validation as you type in for parameter fields. As this is a refactoring it looks strange that you can enter a non-existing file name. I would suggest that always fully qualified type are shown and that the refactoring creates imports but uses simple names.
|
resolved fixed
|
35d8e13
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-30T08:53:51Z | 2003-11-19T11:06:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ChangeSignatureRefactoring.java
| |
31,818 |
Bug 31818 [navigation] Open Type Hierarchy loses selection
|
build I20030211 - open a CU (e.g. BookmarkNavigator.java) - position the cursor between methods - F4 - it opens the type hierarchy on the class, but also changes the text editor's selection to select the class name It should not affect the text editor selection.
|
resolved fixed
|
f433653
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-30T11:41:31Z | 2003-02-13T21:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/TypeHierarchyViewPart.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.typehierarchy;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.ViewForm;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.ScrollBar;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.AbstractTreeViewer;
import org.eclipse.jface.viewers.IBasicPropertyConstants;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPartListener2;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchPartReference;
import org.eclipse.ui.IWorkingSetManager;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.IShowInSource;
import org.eclipse.ui.part.IShowInTargetList;
import org.eclipse.ui.part.PageBook;
import org.eclipse.ui.part.ShowInContext;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.ITypeHierarchyViewPart;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.actions.CCPActionGroup;
import org.eclipse.jdt.ui.actions.GenerateActionGroup;
import org.eclipse.jdt.ui.actions.JavaSearchActionGroup;
import org.eclipse.jdt.ui.actions.OpenEditorActionGroup;
import org.eclipse.jdt.ui.actions.OpenViewActionGroup;
import org.eclipse.jdt.ui.actions.RefactorActionGroup;
import org.eclipse.jdt.internal.corext.util.AllTypesCache;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.AddMethodStubAction;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.actions.NewWizardsActionGroup;
import org.eclipse.jdt.internal.ui.actions.SelectAllAction;
import org.eclipse.jdt.internal.ui.dnd.DelegatingDropAdapter;
import org.eclipse.jdt.internal.ui.dnd.JdtViewerDragAdapter;
import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer;
import org.eclipse.jdt.internal.ui.dnd.TransferDragSourceListener;
import org.eclipse.jdt.internal.ui.dnd.TransferDropTargetListener;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.packageview.SelectionTransferDragAdapter;
import org.eclipse.jdt.internal.ui.preferences.MembersOrderPreferenceCache;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
import org.eclipse.jdt.internal.ui.viewsupport.JavaUILabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater;
import org.eclipse.jdt.internal.ui.workingsets.WorkingSetFilterActionGroup;
/**
* view showing the supertypes/subtypes of its input.
*/
public class TypeHierarchyViewPart extends ViewPart implements ITypeHierarchyViewPart, IViewPartInputProvider {
public static final int VIEW_ID_TYPE= 2;
public static final int VIEW_ID_SUPER= 0;
public static final int VIEW_ID_SUB= 1;
public static final int VIEW_ORIENTATION_VERTICAL= 0;
public static final int VIEW_ORIENTATION_HORIZONTAL= 1;
public static final int VIEW_ORIENTATION_SINGLE= 2;
private static final String DIALOGSTORE_HIERARCHYVIEW= "TypeHierarchyViewPart.hierarchyview"; //$NON-NLS-1$
private static final String DIALOGSTORE_VIEWORIENTATION= "TypeHierarchyViewPart.orientation"; //$NON-NLS-1$
private static final String TAG_INPUT= "input"; //$NON-NLS-1$
private static final String TAG_VIEW= "view"; //$NON-NLS-1$
private static final String TAG_ORIENTATION= "orientation"; //$NON-NLS-1$
private static final String TAG_RATIO= "ratio"; //$NON-NLS-1$
private static final String TAG_SELECTION= "selection"; //$NON-NLS-1$
private static final String TAG_VERTICAL_SCROLL= "vertical_scroll"; //$NON-NLS-1$
private static final String GROUP_FOCUS= "group.focus"; //$NON-NLS-1$
// the selected type in the hierarchy view
private IType fSelectedType;
// input element or null
private IJavaElement fInputElement;
// history of input elements. No duplicates
private ArrayList fInputHistory;
private IMemento fMemento;
private IDialogSettings fDialogSettings;
private TypeHierarchyLifeCycle fHierarchyLifeCycle;
private ITypeHierarchyLifeCycleListener fTypeHierarchyLifeCycleListener;
private IPropertyChangeListener fPropertyChangeListener;
private SelectionProviderMediator fSelectionProviderMediator;
private ISelectionChangedListener fSelectionChangedListener;
private IPartListener2 fPartListener;
private int fCurrentOrientation;
private boolean fLinkingEnabled;
private boolean fIsVisible;
private boolean fNeedRefresh;
private boolean fIsEnableMemberFilter;
private boolean fIsRefreshRunnablePosted;
private int fCurrentViewerIndex;
private TypeHierarchyViewer[] fAllViewers;
private MethodsViewer fMethodsViewer;
private SashForm fTypeMethodsSplitter;
private PageBook fViewerbook;
private PageBook fPagebook;
private Label fNoHierarchyShownLabel;
private Label fEmptyTypesViewer;
private ViewForm fTypeViewerViewForm;
private ViewForm fMethodViewerViewForm;
private CLabel fMethodViewerPaneLabel;
private JavaUILabelProvider fPaneLabelProvider;
private ToggleViewAction[] fViewActions;
private ToggleLinkingAction fToggleLinkingAction;
private HistoryDropDownAction fHistoryDropDownAction;
private ToggleOrientationAction[] fToggleOrientationActions;
private EnableMemberFilterAction fEnableMemberFilterAction;
private ShowQualifiedTypeNamesAction fShowQualifiedTypeNamesAction;
private AddMethodStubAction fAddStubAction;
private FocusOnTypeAction fFocusOnTypeAction;
private FocusOnSelectionAction fFocusOnSelectionAction;
private CompositeActionGroup fActionGroups;
private CCPActionGroup fCCPActionGroup;
private SelectAllAction fSelectAllAction;
private WorkingSetFilterActionGroup fWorkingSetActionGroup;
public TypeHierarchyViewPart() {
fSelectedType= null;
fInputElement= null;
fIsVisible= false;
fIsRefreshRunnablePosted= false;
boolean isReconciled= PreferenceConstants.UPDATE_WHILE_EDITING.equals(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.UPDATE_JAVA_VIEWS));
fHierarchyLifeCycle= new TypeHierarchyLifeCycle();
fHierarchyLifeCycle.setReconciled(isReconciled);
fTypeHierarchyLifeCycleListener= new ITypeHierarchyLifeCycleListener() {
public void typeHierarchyChanged(TypeHierarchyLifeCycle typeHierarchy, IType[] changedTypes) {
doTypeHierarchyChanged(typeHierarchy, changedTypes);
}
};
fHierarchyLifeCycle.addChangedListener(fTypeHierarchyLifeCycleListener);
fPropertyChangeListener= new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
doPropertyChange(event);
}
};
PreferenceConstants.getPreferenceStore().addPropertyChangeListener(fPropertyChangeListener);
fIsEnableMemberFilter= false;
fInputHistory= new ArrayList();
fAllViewers= null;
fViewActions= new ToggleViewAction[] {
new ToggleViewAction(this, VIEW_ID_TYPE),
new ToggleViewAction(this, VIEW_ID_SUPER),
new ToggleViewAction(this, VIEW_ID_SUB)
};
fDialogSettings= JavaPlugin.getDefault().getDialogSettings();
fHistoryDropDownAction= new HistoryDropDownAction(this);
fHistoryDropDownAction.setEnabled(false);
fToggleOrientationActions= new ToggleOrientationAction[] {
new ToggleOrientationAction(this, VIEW_ORIENTATION_VERTICAL),
new ToggleOrientationAction(this, VIEW_ORIENTATION_HORIZONTAL),
new ToggleOrientationAction(this, VIEW_ORIENTATION_SINGLE)
};
fEnableMemberFilterAction= new EnableMemberFilterAction(this, false);
fShowQualifiedTypeNamesAction= new ShowQualifiedTypeNamesAction(this, false);
fFocusOnTypeAction= new FocusOnTypeAction(this);
fPaneLabelProvider= new JavaUILabelProvider();
fAddStubAction= new AddMethodStubAction();
fFocusOnSelectionAction= new FocusOnSelectionAction(this);
fPartListener= new IPartListener2() {
public void partVisible(IWorkbenchPartReference ref) {
IWorkbenchPart part= ref.getPart(false);
if (part == TypeHierarchyViewPart.this) {
visibilityChanged(true);
}
}
public void partHidden(IWorkbenchPartReference ref) {
IWorkbenchPart part= ref.getPart(false);
if (part == TypeHierarchyViewPart.this) {
visibilityChanged(false);
}
}
public void partActivated(IWorkbenchPartReference ref) {
IWorkbenchPart part= ref.getPart(false);
if (part instanceof IEditorPart)
editorActivated((IEditorPart) part);
}
public void partInputChanged(IWorkbenchPartReference ref) {
IWorkbenchPart part= ref.getPart(false);
if (part instanceof IEditorPart)
editorActivated((IEditorPart) part);
}
public void partBroughtToTop(IWorkbenchPartReference ref) {}
public void partClosed(IWorkbenchPartReference ref) {}
public void partDeactivated(IWorkbenchPartReference ref) {}
public void partOpened(IWorkbenchPartReference ref) {}
};
fSelectionChangedListener= new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
doSelectionChanged(event);
}
};
fLinkingEnabled= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.LINK_TYPEHIERARCHY_TO_EDITOR);
}
/**
* Method doPropertyChange.
* @param event
*/
protected void doPropertyChange(PropertyChangeEvent event) {
String property= event.getProperty();
if (fMethodsViewer != null) {
if (MembersOrderPreferenceCache.isMemberOrderProperty(event.getProperty())) {
fMethodsViewer.refresh();
}
}
if (IWorkingSetManager.CHANGE_WORKING_SET_CONTENT_CHANGE.equals(property)) {
updateHierarchyViewer(true);
} else if (IWorkingSetManager.CHANGE_WORKING_SET_NAME_CHANGE.equals(property)) {
}
}
/**
* Adds the entry if new. Inserted at the beginning of the history entries list.
*/
private void addHistoryEntry(IJavaElement entry) {
if (fInputHistory.contains(entry)) {
fInputHistory.remove(entry);
}
fInputHistory.add(0, entry);
fHistoryDropDownAction.setEnabled(true);
}
private void updateHistoryEntries() {
for (int i= fInputHistory.size() - 1; i >= 0; i--) {
IJavaElement type= (IJavaElement) fInputHistory.get(i);
if (!type.exists()) {
fInputHistory.remove(i);
}
}
fHistoryDropDownAction.setEnabled(!fInputHistory.isEmpty());
}
/**
* Goes to the selected entry, without updating the order of history entries.
*/
public void gotoHistoryEntry(IJavaElement entry) {
if (fInputHistory.contains(entry)) {
updateInput(entry);
}
}
/**
* Gets all history entries.
*/
public IJavaElement[] getHistoryEntries() {
if (fInputHistory.size() > 0) {
updateHistoryEntries();
}
return (IJavaElement[]) fInputHistory.toArray(new IJavaElement[fInputHistory.size()]);
}
/**
* Sets the history entries
*/
public void setHistoryEntries(IJavaElement[] elems) {
fInputHistory.clear();
for (int i= 0; i < elems.length; i++) {
fInputHistory.add(elems[i]);
}
updateHistoryEntries();
}
/**
* Selects an member in the methods list or in the current hierarchy.
*/
public void selectMember(IMember member) {
if (member.getElementType() != IJavaElement.TYPE) {
// methods are working copies
if (fHierarchyLifeCycle.isReconciled()) {
member= JavaModelUtil.toWorkingCopy(member);
}
Control methodControl= fMethodsViewer.getControl();
if (methodControl != null && !methodControl.isDisposed()) {
methodControl.setFocus();
}
fMethodsViewer.setSelection(new StructuredSelection(member), true);
} else {
Control viewerControl= getCurrentViewer().getControl();
if (viewerControl != null && !viewerControl.isDisposed()) {
viewerControl.setFocus();
}
// types are originals
member= JavaModelUtil.toOriginal(member);
if (!member.equals(fSelectedType)) {
getCurrentViewer().setSelection(new StructuredSelection(member), true);
}
}
}
/**
* @deprecated
*/
public IType getInput() {
if (fInputElement instanceof IType) {
return (IType) fInputElement;
}
return null;
}
/**
* Sets the input to a new type
* @deprecated
*/
public void setInput(IType type) {
setInputElement(type);
}
/**
* Returns the input element of the type hierarchy.
* Can be of type <code>IType</code> or <code>IPackageFragment</code>
*/
public IJavaElement getInputElement() {
return fInputElement;
}
/**
* Sets the input to a new element.
*/
public void setInputElement(IJavaElement element) {
if (element != null) {
if (element instanceof IMember) {
if (element.getElementType() != IJavaElement.TYPE) {
element= ((IMember) element).getDeclaringType();
}
element= JavaModelUtil.toOriginal((IMember) element);
if (!element.exists()) {
MessageDialog.openError(getSite().getShell(), TypeHierarchyMessages.getString("TypeHierarchyViewPart.error.title"), TypeHierarchyMessages.getString("TypeHierarchyViewPart.error.message")); //$NON-NLS-1$ //$NON-NLS-2$
return;
}
} else {
int kind= element.getElementType();
if (kind != IJavaElement.JAVA_PROJECT && kind != IJavaElement.PACKAGE_FRAGMENT_ROOT && kind != IJavaElement.PACKAGE_FRAGMENT) {
element= null;
JavaPlugin.logErrorMessage("Invalid type hierarchy input type.");//$NON-NLS-1$
}
}
}
if (element != null && !element.equals(fInputElement)) {
addHistoryEntry(element);
}
updateInput(element);
}
/**
* Changes the input to a new type
*/
private void updateInput(IJavaElement inputElement) {
IJavaElement prevInput= fInputElement;
// Make sure the UI got repainted before we execute a long running
// operation. This can be removed if we refresh the hierarchy in a
// separate thread.
// Work-araound for http://dev.eclipse.org/bugs/show_bug.cgi?id=30881
processOutstandingEvents();
if (inputElement == null) {
clearInput();
} else {
fInputElement= inputElement;
try {
fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(inputElement, JavaPlugin.getActiveWorkbenchWindow());
// fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(inputElement, getSite().getWorkbenchWindow());
} catch (InvocationTargetException e) {
ExceptionHandler.handle(e, getSite().getShell(), TypeHierarchyMessages.getString("TypeHierarchyViewPart.exception.title"), TypeHierarchyMessages.getString("TypeHierarchyViewPart.exception.message")); //$NON-NLS-1$ //$NON-NLS-2$
clearInput();
return;
} catch (InterruptedException e) {
return;
}
if (inputElement.getElementType() != IJavaElement.TYPE) {
setView(VIEW_ID_TYPE);
}
// turn off member filtering
setMemberFilter(null);
fIsEnableMemberFilter= false;
if (!inputElement.equals(prevInput)) {
updateHierarchyViewer(true);
}
IType root= getSelectableType(inputElement);
internalSelectType(root, true);
updateMethodViewer(root);
updateToolbarButtons();
updateTitle();
enableMemberFilter(false);
fPagebook.showPage(fTypeMethodsSplitter);
}
}
private void processOutstandingEvents() {
Display display= getDisplay();
if (display != null && !display.isDisposed())
display.update();
}
private void clearInput() {
fInputElement= null;
fHierarchyLifeCycle.freeHierarchy();
updateHierarchyViewer(false);
updateToolbarButtons();
}
/*
* @see IWorbenchPart#setFocus
*/
public void setFocus() {
fPagebook.setFocus();
}
/*
* @see IWorkbenchPart#dispose
*/
public void dispose() {
fHierarchyLifeCycle.freeHierarchy();
fHierarchyLifeCycle.removeChangedListener(fTypeHierarchyLifeCycleListener);
fPaneLabelProvider.dispose();
if (fMethodsViewer != null) {
fMethodsViewer.dispose();
}
if (fPropertyChangeListener != null) {
JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(fPropertyChangeListener);
fPropertyChangeListener= null;
}
getSite().getPage().removePartListener(fPartListener);
if (fActionGroups != null)
fActionGroups.dispose();
if (fWorkingSetActionGroup != null) {
fWorkingSetActionGroup.dispose();
}
super.dispose();
}
/**
* Answer the property defined by key.
*/
public Object getAdapter(Class key) {
if (key == IShowInSource.class) {
return getShowInSource();
}
if (key == IShowInTargetList.class) {
return new IShowInTargetList() {
public String[] getShowInTargetIds() {
return new String[] { JavaUI.ID_PACKAGES, IPageLayout.ID_RES_NAV };
}
};
}
return super.getAdapter(key);
}
private Control createTypeViewerControl(Composite parent) {
fViewerbook= new PageBook(parent, SWT.NULL);
KeyListener keyListener= createKeyListener();
// Create the viewers
TypeHierarchyViewer superTypesViewer= new SuperTypeHierarchyViewer(fViewerbook, fHierarchyLifeCycle, this);
initializeTypesViewer(superTypesViewer, keyListener, IContextMenuConstants.TARGET_ID_SUPERTYPES_VIEW);
TypeHierarchyViewer subTypesViewer= new SubTypeHierarchyViewer(fViewerbook, fHierarchyLifeCycle, this);
initializeTypesViewer(subTypesViewer, keyListener, IContextMenuConstants.TARGET_ID_SUBTYPES_VIEW);
TypeHierarchyViewer vajViewer= new TraditionalHierarchyViewer(fViewerbook, fHierarchyLifeCycle, this);
initializeTypesViewer(vajViewer, keyListener, IContextMenuConstants.TARGET_ID_HIERARCHY_VIEW);
fAllViewers= new TypeHierarchyViewer[3];
fAllViewers[VIEW_ID_SUPER]= superTypesViewer;
fAllViewers[VIEW_ID_SUB]= subTypesViewer;
fAllViewers[VIEW_ID_TYPE]= vajViewer;
int currViewerIndex;
try {
currViewerIndex= fDialogSettings.getInt(DIALOGSTORE_HIERARCHYVIEW);
if (currViewerIndex < 0 || currViewerIndex > 2) {
currViewerIndex= VIEW_ID_TYPE;
}
} catch (NumberFormatException e) {
currViewerIndex= VIEW_ID_TYPE;
}
fEmptyTypesViewer= new Label(fViewerbook, SWT.LEFT);
for (int i= 0; i < fAllViewers.length; i++) {
fAllViewers[i].setInput(fAllViewers[i]);
}
// force the update
fCurrentViewerIndex= -1;
setView(currViewerIndex);
return fViewerbook;
}
private KeyListener createKeyListener() {
return new KeyAdapter() {
public void keyReleased(KeyEvent event) {
if (event.stateMask == 0) {
if (event.keyCode == SWT.F5) {
ITypeHierarchy hierarchy= fHierarchyLifeCycle.getHierarchy();
if (hierarchy != null) {
fHierarchyLifeCycle.typeHierarchyChanged(hierarchy);
doTypeHierarchyChangedOnViewers(null);
}
updateHierarchyViewer(false);
return;
} else if (event.character == SWT.DEL) {
if (fCCPActionGroup.getDeleteAction().isEnabled())
fCCPActionGroup.getDeleteAction().run();
return;
}
}
}
};
}
private void initializeTypesViewer(final TypeHierarchyViewer typesViewer, KeyListener keyListener, String cotextHelpId) {
typesViewer.getControl().setVisible(false);
typesViewer.getControl().addKeyListener(keyListener);
typesViewer.initContextMenu(new IMenuListener() {
public void menuAboutToShow(IMenuManager menu) {
fillTypesViewerContextMenu(typesViewer, menu);
}
}, cotextHelpId, getSite());
typesViewer.addPostSelectionChangedListener(fSelectionChangedListener);
typesViewer.setQualifiedTypeName(isShowQualifiedTypeNames());
typesViewer.setWorkingSetFilter(fWorkingSetActionGroup.getWorkingSetFilter());
}
private Control createMethodViewerControl(Composite parent) {
fMethodsViewer= new MethodsViewer(parent, fHierarchyLifeCycle, this);
fMethodsViewer.initContextMenu(new IMenuListener() {
public void menuAboutToShow(IMenuManager menu) {
fillMethodsViewerContextMenu(menu);
}
}, IContextMenuConstants.TARGET_ID_MEMBERS_VIEW, getSite());
fMethodsViewer.addPostSelectionChangedListener(fSelectionChangedListener);
Control control= fMethodsViewer.getTable();
control.addKeyListener(createKeyListener());
control.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
fSelectAllAction.setEnabled(true);
}
public void focusLost(FocusEvent e) {
fSelectAllAction.setEnabled(false);
}
});
return control;
}
private void initDragAndDrop() {
Transfer[] transfers= new Transfer[] { LocalSelectionTransfer.getInstance() };
int ops= DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_LINK;
for (int i= 0; i < fAllViewers.length; i++) {
addDragAdapters(fAllViewers[i], ops, transfers);
addDropAdapters(fAllViewers[i], ops | DND.DROP_DEFAULT, transfers);
}
addDragAdapters(fMethodsViewer, ops, transfers);
//dnd on empty hierarchy
DropTarget dropTarget = new DropTarget(fNoHierarchyShownLabel, ops | DND.DROP_DEFAULT);
dropTarget.setTransfer(transfers);
dropTarget.addDropListener(new TypeHierarchyTransferDropAdapter(this, fAllViewers[0]));
}
private void addDropAdapters(AbstractTreeViewer viewer, int ops, Transfer[] transfers){
TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] {
new TypeHierarchyTransferDropAdapter(this, viewer)
};
viewer.addDropSupport(ops, transfers, new DelegatingDropAdapter(dropListeners));
}
private void addDragAdapters(StructuredViewer viewer, int ops, Transfer[] transfers) {
TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] {
new SelectionTransferDragAdapter(viewer)
};
viewer.addDragSupport(ops, transfers, new JdtViewerDragAdapter(viewer, dragListeners));
}
/**
* Returns the inner component in a workbench part.
* @see IWorkbenchPart#createPartControl(Composite)
*/
public void createPartControl(Composite container) {
fPagebook= new PageBook(container, SWT.NONE);
fWorkingSetActionGroup= new WorkingSetFilterActionGroup(JavaUI.ID_TYPE_HIERARCHY, container.getShell(), fPropertyChangeListener);
// page 1 of pagebook (viewers)
fTypeMethodsSplitter= new SashForm(fPagebook, SWT.VERTICAL);
fTypeMethodsSplitter.setVisible(false);
fTypeViewerViewForm= new ViewForm(fTypeMethodsSplitter, SWT.NONE);
Control typeViewerControl= createTypeViewerControl(fTypeViewerViewForm);
fTypeViewerViewForm.setContent(typeViewerControl);
fMethodViewerViewForm= new ViewForm(fTypeMethodsSplitter, SWT.NONE);
fTypeMethodsSplitter.setWeights(new int[] {35, 65});
Control methodViewerPart= createMethodViewerControl(fMethodViewerViewForm);
fMethodViewerViewForm.setContent(methodViewerPart);
fMethodViewerPaneLabel= new CLabel(fMethodViewerViewForm, SWT.NONE);
fMethodViewerViewForm.setTopLeft(fMethodViewerPaneLabel);
ToolBar methodViewerToolBar= new ToolBar(fMethodViewerViewForm, SWT.FLAT | SWT.WRAP);
fMethodViewerViewForm.setTopCenter(methodViewerToolBar);
// page 2 of pagebook (no hierarchy label)
fNoHierarchyShownLabel= new Label(fPagebook, SWT.TOP + SWT.LEFT + SWT.WRAP);
fNoHierarchyShownLabel.setText(TypeHierarchyMessages.getString("TypeHierarchyViewPart.empty")); //$NON-NLS-1$
initDragAndDrop();
MenuManager menu= new MenuManager();
menu.add(fFocusOnTypeAction);
fNoHierarchyShownLabel.setMenu(menu.createContextMenu(fNoHierarchyShownLabel));
fPagebook.showPage(fNoHierarchyShownLabel);
int orientation;
try {
orientation= fDialogSettings.getInt(DIALOGSTORE_VIEWORIENTATION);
if (orientation < 0 || orientation > 2) {
orientation= VIEW_ORIENTATION_VERTICAL;
}
} catch (NumberFormatException e) {
orientation= VIEW_ORIENTATION_VERTICAL;
}
// force the update
fCurrentOrientation= -1;
// will fill the main tool bar
setOrientation(orientation);
if (fMemento != null) { // restore state before creating action
restoreLinkingEnabled(fMemento);
}
fToggleLinkingAction= new ToggleLinkingAction(this);
// set the filter menu items
IActionBars actionBars= getViewSite().getActionBars();
IMenuManager viewMenu= actionBars.getMenuManager();
for (int i= 0; i < fViewActions.length; i++) {
viewMenu.add(fViewActions[i]);
}
viewMenu.add(new Separator());
fWorkingSetActionGroup.contributeToMenu(viewMenu);
viewMenu.add(new Separator());
IMenuManager layoutSubMenu= new MenuManager(TypeHierarchyMessages.getString("TypeHierarchyViewPart.layout.submenu")); //$NON-NLS-1$
viewMenu.add(layoutSubMenu);
for (int i= 0; i < fToggleOrientationActions.length; i++) {
layoutSubMenu.add(fToggleOrientationActions[i]);
}
viewMenu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
viewMenu.add(fShowQualifiedTypeNamesAction);
viewMenu.add(fToggleLinkingAction);
// fill the method viewer toolbar
ToolBarManager lowertbmanager= new ToolBarManager(methodViewerToolBar);
lowertbmanager.add(fEnableMemberFilterAction);
lowertbmanager.add(new Separator());
fMethodsViewer.contributeToToolBar(lowertbmanager);
lowertbmanager.update(true);
// selection provider
int nHierarchyViewers= fAllViewers.length;
Viewer[] trackedViewers= new Viewer[nHierarchyViewers + 1];
for (int i= 0; i < nHierarchyViewers; i++) {
trackedViewers[i]= fAllViewers[i];
}
trackedViewers[nHierarchyViewers]= fMethodsViewer;
fSelectionProviderMediator= new SelectionProviderMediator(trackedViewers);
IStatusLineManager slManager= getViewSite().getActionBars().getStatusLineManager();
fSelectionProviderMediator.addSelectionChangedListener(new StatusBarUpdater(slManager));
getSite().setSelectionProvider(fSelectionProviderMediator);
getSite().getPage().addPartListener(fPartListener);
// see http://bugs.eclipse.org/bugs/show_bug.cgi?id=33657
IJavaElement input= null; //determineInputElement();
if (fMemento != null) {
restoreState(fMemento, input);
} else if (input != null) {
setInputElement(input);
} else {
setViewerVisibility(false);
}
WorkbenchHelp.setHelp(fPagebook, IJavaHelpContextIds.TYPE_HIERARCHY_VIEW);
fActionGroups= new CompositeActionGroup(new ActionGroup[] {
new NewWizardsActionGroup(this.getSite()),
new OpenEditorActionGroup(this),
new OpenViewActionGroup(this),
fCCPActionGroup= new CCPActionGroup(this),
new GenerateActionGroup(this),
new RefactorActionGroup(this),
new JavaSearchActionGroup(this)
});
fActionGroups.fillActionBars(actionBars);
fSelectAllAction= new SelectAllAction(fMethodsViewer);
actionBars.setGlobalActionHandler(ActionFactory.SELECT_ALL.getId(), fSelectAllAction);
}
/**
* called from ToggleOrientationAction.
* @param orientation VIEW_ORIENTATION_SINGLE, VIEW_ORIENTATION_HORIZONTAL or VIEW_ORIENTATION_VERTICAL
*/
public void setOrientation(int orientation) {
if (fCurrentOrientation != orientation) {
boolean methodViewerNeedsUpdate= false;
if (fMethodViewerViewForm != null && !fMethodViewerViewForm.isDisposed()
&& fTypeMethodsSplitter != null && !fTypeMethodsSplitter.isDisposed()) {
if (orientation == VIEW_ORIENTATION_SINGLE) {
fMethodViewerViewForm.setVisible(false);
enableMemberFilter(false);
updateMethodViewer(null);
} else {
if (fCurrentOrientation == VIEW_ORIENTATION_SINGLE) {
fMethodViewerViewForm.setVisible(true);
methodViewerNeedsUpdate= true;
}
boolean horizontal= orientation == VIEW_ORIENTATION_HORIZONTAL;
fTypeMethodsSplitter.setOrientation(horizontal ? SWT.HORIZONTAL : SWT.VERTICAL);
}
updateMainToolbar(orientation);
fTypeMethodsSplitter.layout();
}
for (int i= 0; i < fToggleOrientationActions.length; i++) {
fToggleOrientationActions[i].setChecked(orientation == fToggleOrientationActions[i].getOrientation());
}
fCurrentOrientation= orientation;
if (methodViewerNeedsUpdate) {
updateMethodViewer(fSelectedType);
}
fDialogSettings.put(DIALOGSTORE_VIEWORIENTATION, orientation);
}
}
private void updateMainToolbar(int orientation) {
IActionBars actionBars= getViewSite().getActionBars();
IToolBarManager tbmanager= actionBars.getToolBarManager();
if (orientation == VIEW_ORIENTATION_HORIZONTAL) {
clearMainToolBar(tbmanager);
ToolBar typeViewerToolBar= new ToolBar(fTypeViewerViewForm, SWT.FLAT | SWT.WRAP);
fillMainToolBar(new ToolBarManager(typeViewerToolBar));
fTypeViewerViewForm.setTopLeft(typeViewerToolBar);
} else {
fTypeViewerViewForm.setTopLeft(null);
fillMainToolBar(tbmanager);
}
}
private void fillMainToolBar(IToolBarManager tbmanager) {
tbmanager.removeAll();
tbmanager.add(fHistoryDropDownAction);
for (int i= 0; i < fViewActions.length; i++) {
tbmanager.add(fViewActions[i]);
}
tbmanager.update(false);
}
private void clearMainToolBar(IToolBarManager tbmanager) {
tbmanager.removeAll();
tbmanager.update(false);
}
/**
* Creates the context menu for the hierarchy viewers
*/
private void fillTypesViewerContextMenu(TypeHierarchyViewer viewer, IMenuManager menu) {
JavaPlugin.createStandardGroups(menu);
menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, new Separator(GROUP_FOCUS));
// viewer entries
viewer.contributeToContextMenu(menu);
if (fFocusOnSelectionAction.canActionBeAdded())
menu.appendToGroup(GROUP_FOCUS, fFocusOnSelectionAction);
menu.appendToGroup(GROUP_FOCUS, fFocusOnTypeAction);
fActionGroups.setContext(new ActionContext(getSite().getSelectionProvider().getSelection()));
fActionGroups.fillContextMenu(menu);
fActionGroups.setContext(null);
}
/**
* Creates the context menu for the method viewer
*/
private void fillMethodsViewerContextMenu(IMenuManager menu) {
JavaPlugin.createStandardGroups(menu);
// viewer entries
fMethodsViewer.contributeToContextMenu(menu);
if (fSelectedType != null && fAddStubAction.init(fSelectedType, fMethodsViewer.getSelection())) {
menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, fAddStubAction);
}
fActionGroups.setContext(new ActionContext(getSite().getSelectionProvider().getSelection()));
fActionGroups.fillContextMenu(menu);
fActionGroups.setContext(null);
}
/**
* Toggles between the empty viewer page and the hierarchy
*/
private void setViewerVisibility(boolean showHierarchy) {
if (showHierarchy) {
fViewerbook.showPage(getCurrentViewer().getControl());
} else {
fViewerbook.showPage(fEmptyTypesViewer);
}
}
/**
* Sets the member filter. <code>null</code> disables member filtering.
*/
private void setMemberFilter(IMember[] memberFilter) {
Assert.isNotNull(fAllViewers);
for (int i= 0; i < fAllViewers.length; i++) {
fAllViewers[i].setMemberFilter(memberFilter);
}
}
private IType getSelectableType(IJavaElement elem) {
if (elem.getElementType() != IJavaElement.TYPE) {
return null; //(IType) getCurrentViewer().getTreeRootType();
} else {
return (IType) elem;
}
}
private void internalSelectType(IMember elem, boolean reveal) {
TypeHierarchyViewer viewer= getCurrentViewer();
viewer.removePostSelectionChangedListener(fSelectionChangedListener);
viewer.setSelection(elem != null ? new StructuredSelection(elem) : StructuredSelection.EMPTY, reveal);
viewer.addPostSelectionChangedListener(fSelectionChangedListener);
}
/**
* When the input changed or the hierarchy pane becomes visible,
* <code>updateHierarchyViewer<code> brings up the correct view and refreshes
* the current tree
*/
private void updateHierarchyViewer(final boolean doExpand) {
if (fInputElement == null) {
fPagebook.showPage(fNoHierarchyShownLabel);
} else {
if (getCurrentViewer().containsElements() != null) {
Runnable runnable= new Runnable() {
public void run() {
getCurrentViewer().updateContent(doExpand); // refresh
}
};
BusyIndicator.showWhile(getDisplay(), runnable);
if (!isChildVisible(fViewerbook, getCurrentViewer().getControl())) {
setViewerVisibility(true);
}
} else {
fEmptyTypesViewer.setText(TypeHierarchyMessages.getFormattedString("TypeHierarchyViewPart.nodecl", fInputElement.getElementName())); //$NON-NLS-1$
setViewerVisibility(false);
}
}
}
private void updateMethodViewer(final IType input) {
if (!fIsEnableMemberFilter && fCurrentOrientation != VIEW_ORIENTATION_SINGLE) {
if (input == fMethodsViewer.getInput()) {
if (input != null) {
Runnable runnable= new Runnable() {
public void run() {
fMethodsViewer.refresh(); // refresh
}
};
BusyIndicator.showWhile(getDisplay(), runnable);
}
} else {
if (input != null) {
fMethodViewerPaneLabel.setText(fPaneLabelProvider.getText(input));
fMethodViewerPaneLabel.setImage(fPaneLabelProvider.getImage(input));
} else {
fMethodViewerPaneLabel.setText(""); //$NON-NLS-1$
fMethodViewerPaneLabel.setImage(null);
}
Runnable runnable= new Runnable() {
public void run() {
fMethodsViewer.setInput(input); // refresh
}
};
BusyIndicator.showWhile(getDisplay(), runnable);
}
}
}
protected void doSelectionChanged(SelectionChangedEvent e) {
if (e.getSelectionProvider() == fMethodsViewer) {
methodSelectionChanged(e.getSelection());
} else {
typeSelectionChanged(e.getSelection());
}
}
private void methodSelectionChanged(ISelection sel) {
if (sel instanceof IStructuredSelection) {
List selected= ((IStructuredSelection)sel).toList();
int nSelected= selected.size();
if (fIsEnableMemberFilter) {
IMember[] memberFilter= null;
if (nSelected > 0) {
memberFilter= new IMember[nSelected];
selected.toArray(memberFilter);
}
setMemberFilter(memberFilter);
updateHierarchyViewer(true);
updateTitle();
internalSelectType(fSelectedType, true);
}
if (nSelected == 1) {
revealElementInEditor(selected.get(0), fMethodsViewer);
}
}
}
private void typeSelectionChanged(ISelection sel) {
if (sel instanceof IStructuredSelection) {
List selected= ((IStructuredSelection)sel).toList();
int nSelected= selected.size();
if (nSelected != 0) {
List types= new ArrayList(nSelected);
for (int i= nSelected-1; i >= 0; i--) {
Object elem= selected.get(i);
if (elem instanceof IType && !types.contains(elem)) {
types.add(elem);
}
}
if (types.size() == 1) {
fSelectedType= (IType) types.get(0);
updateMethodViewer(fSelectedType);
} else if (types.size() == 0) {
// method selected, no change
}
if (nSelected == 1) {
revealElementInEditor(selected.get(0), getCurrentViewer());
}
} else {
fSelectedType= null;
updateMethodViewer(null);
}
}
}
private void revealElementInEditor(Object elem, Viewer originViewer) {
// only allow revealing when the type hierarchy is the active pagae
// no revealing after selection events due to model changes
if (getSite().getPage().getActivePart() != this) {
return;
}
if (fSelectionProviderMediator.getViewerInFocus() != originViewer) {
return;
}
IEditorPart editorPart= EditorUtility.isOpenInEditor(elem);
if (editorPart != null && (elem instanceof IJavaElement)) {
getSite().getPage().removePartListener(fPartListener);
getSite().getPage().bringToTop(editorPart);
EditorUtility.revealInEditor(editorPart, (IJavaElement) elem);
getSite().getPage().addPartListener(fPartListener);
}
}
private Display getDisplay() {
if (fPagebook != null && !fPagebook.isDisposed()) {
return fPagebook.getDisplay();
}
return null;
}
private boolean isChildVisible(Composite pb, Control child) {
Control[] children= pb.getChildren();
for (int i= 0; i < children.length; i++) {
if (children[i] == child && children[i].isVisible())
return true;
}
return false;
}
private void updateTitle() {
String viewerTitle= getCurrentViewer().getTitle();
String tooltip;
String title;
if (fInputElement != null) {
String[] args= new String[] { viewerTitle, JavaElementLabels.getElementLabel(fInputElement, JavaElementLabels.ALL_DEFAULT) };
title= TypeHierarchyMessages.getFormattedString("TypeHierarchyViewPart.title", args); //$NON-NLS-1$
tooltip= TypeHierarchyMessages.getFormattedString("TypeHierarchyViewPart.tooltip", args); //$NON-NLS-1$
} else {
title= viewerTitle;
tooltip= viewerTitle;
}
setTitle(title);
setTitleToolTip(tooltip);
}
private void updateToolbarButtons() {
boolean isType= fInputElement instanceof IType;
for (int i= 0; i < fViewActions.length; i++) {
ToggleViewAction action= fViewActions[i];
if (action.getViewerIndex() == VIEW_ID_TYPE) {
action.setEnabled(fInputElement != null);
} else {
action.setEnabled(isType);
}
}
}
/**
* Sets the current view (see view id)
* called from ToggleViewAction. Must be called after creation of the viewpart.
*/
public void setView(int viewerIndex) {
Assert.isNotNull(fAllViewers);
if (viewerIndex < fAllViewers.length && fCurrentViewerIndex != viewerIndex) {
fCurrentViewerIndex= viewerIndex;
updateHierarchyViewer(true);
if (fInputElement != null) {
ISelection currSelection= getCurrentViewer().getSelection();
if (currSelection == null || currSelection.isEmpty()) {
internalSelectType(getSelectableType(fInputElement), false);
currSelection= getCurrentViewer().getSelection();
}
if (!fIsEnableMemberFilter) {
typeSelectionChanged(currSelection);
}
}
updateTitle();
fDialogSettings.put(DIALOGSTORE_HIERARCHYVIEW, viewerIndex);
getCurrentViewer().getTree().setFocus();
}
for (int i= 0; i < fViewActions.length; i++) {
ToggleViewAction action= fViewActions[i];
action.setChecked(fCurrentViewerIndex == action.getViewerIndex());
}
}
/**
* Gets the curret active view index.
*/
public int getViewIndex() {
return fCurrentViewerIndex;
}
private TypeHierarchyViewer getCurrentViewer() {
return fAllViewers[fCurrentViewerIndex];
}
/**
* called from EnableMemberFilterAction.
* Must be called after creation of the viewpart.
*/
public void enableMemberFilter(boolean on) {
if (on != fIsEnableMemberFilter) {
fIsEnableMemberFilter= on;
if (!on) {
IType methodViewerInput= (IType) fMethodsViewer.getInput();
setMemberFilter(null);
updateHierarchyViewer(true);
updateTitle();
if (methodViewerInput != null && getCurrentViewer().isElementShown(methodViewerInput)) {
// avoid that the method view changes content by selecting the previous input
internalSelectType(methodViewerInput, true);
} else if (fSelectedType != null) {
// choose a input that exists
internalSelectType(fSelectedType, true);
updateMethodViewer(fSelectedType);
}
} else {
methodSelectionChanged(fMethodsViewer.getSelection());
}
}
fEnableMemberFilterAction.setChecked(on);
}
/**
* called from ShowQualifiedTypeNamesAction. Must be called after creation
* of the viewpart.
*/
public void showQualifiedTypeNames(boolean on) {
if (fAllViewers == null) {
return;
}
for (int i= 0; i < fAllViewers.length; i++) {
fAllViewers[i].setQualifiedTypeName(on);
}
}
private boolean isShowQualifiedTypeNames() {
return fShowQualifiedTypeNamesAction.isChecked();
}
/**
* Called from ITypeHierarchyLifeCycleListener.
* Can be called from any thread
*/
protected void doTypeHierarchyChanged(final TypeHierarchyLifeCycle typeHierarchy, final IType[] changedTypes) {
if (!fIsVisible) {
fNeedRefresh= true;
return;
}
if (fIsRefreshRunnablePosted) {
return;
}
Display display= getDisplay();
if (display != null) {
fIsRefreshRunnablePosted= true;
display.asyncExec(new Runnable() {
public void run() {
try {
if (fPagebook != null && !fPagebook.isDisposed()) {
doTypeHierarchyChangedOnViewers(changedTypes);
}
} finally {
fIsRefreshRunnablePosted= false;
}
}
});
}
}
protected void doTypeHierarchyChangedOnViewers(IType[] changedTypes) {
if (fHierarchyLifeCycle.getHierarchy() == null || !fHierarchyLifeCycle.getHierarchy().exists()) {
clearInput();
} else {
if (changedTypes == null) {
// hierarchy change
try {
fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(fInputElement, getSite().getWorkbenchWindow());
} catch (InvocationTargetException e) {
ExceptionHandler.handle(e, getSite().getShell(), TypeHierarchyMessages.getString("TypeHierarchyViewPart.exception.title"), TypeHierarchyMessages.getString("TypeHierarchyViewPart.exception.message")); //$NON-NLS-1$ //$NON-NLS-2$
clearInput();
return;
} catch (InterruptedException e) {
return;
}
fMethodsViewer.refresh();
updateHierarchyViewer(false);
} else {
// elements in hierarchy modified
Object methodViewerInput= fMethodsViewer.getInput();
fMethodsViewer.refresh();
fMethodViewerPaneLabel.setText(fPaneLabelProvider.getText(methodViewerInput));
fMethodViewerPaneLabel.setImage(fPaneLabelProvider.getImage(methodViewerInput));
if (getCurrentViewer().isMethodFiltering()) {
if (changedTypes.length == 1) {
getCurrentViewer().refresh(changedTypes[0]);
} else {
updateHierarchyViewer(false);
}
} else {
getCurrentViewer().update(changedTypes, new String[] { IBasicPropertyConstants.P_TEXT, IBasicPropertyConstants.P_IMAGE } );
}
}
}
}
/*
* @see IViewPart#init
*/
public void init(IViewSite site, IMemento memento) throws PartInitException {
super.init(site, memento);
fMemento= memento;
}
/*
* @see ViewPart#saveState(IMemento)
*/
public void saveState(IMemento memento) {
if (fPagebook == null) {
// part has not been created
if (fMemento != null) { //Keep the old state;
memento.putMemento(fMemento);
}
return;
}
if (fInputElement != null) {
String handleIndentifier= fInputElement.getHandleIdentifier();
if (fInputElement instanceof IType) {
ITypeHierarchy hierarchy= fHierarchyLifeCycle.getHierarchy();
if (hierarchy != null && hierarchy.getSubtypes((IType) fInputElement).length > 1000) {
// for startup performance reasons do not try to recover huge hierarchies
handleIndentifier= null;
}
}
memento.putString(TAG_INPUT, handleIndentifier);
}
memento.putInteger(TAG_VIEW, getViewIndex());
memento.putInteger(TAG_ORIENTATION, fCurrentOrientation);
int weigths[]= fTypeMethodsSplitter.getWeights();
int ratio= (weigths[0] * 1000) / (weigths[0] + weigths[1]);
memento.putInteger(TAG_RATIO, ratio);
ScrollBar bar= getCurrentViewer().getTree().getVerticalBar();
int position= bar != null ? bar.getSelection() : 0;
memento.putInteger(TAG_VERTICAL_SCROLL, position);
IJavaElement selection= (IJavaElement)((IStructuredSelection) getCurrentViewer().getSelection()).getFirstElement();
if (selection != null) {
memento.putString(TAG_SELECTION, selection.getHandleIdentifier());
}
fWorkingSetActionGroup.saveState(memento);
fMethodsViewer.saveState(memento);
saveLinkingEnabled(memento);
}
private void saveLinkingEnabled(IMemento memento) {
memento.putInteger(PreferenceConstants.LINK_TYPEHIERARCHY_TO_EDITOR, fLinkingEnabled ? 1 : 0);
}
/**
* Restores the type hierarchy settings from a memento.
*/
private void restoreState(IMemento memento, IJavaElement defaultInput) {
IJavaElement input= defaultInput;
fWorkingSetActionGroup.restoreState(memento);
String elementId= memento.getString(TAG_INPUT);
if (elementId != null) {
input= JavaCore.create(elementId);
if (input != null && !input.exists()) {
input= null;
}
if (!AllTypesCache.isIndexUpToDate()) {
input= null;
}
}
setInputElement(input);
Integer viewerIndex= memento.getInteger(TAG_VIEW);
if (viewerIndex != null) {
setView(viewerIndex.intValue());
}
Integer orientation= memento.getInteger(TAG_ORIENTATION);
if (orientation != null) {
setOrientation(orientation.intValue());
}
Integer ratio= memento.getInteger(TAG_RATIO);
if (ratio != null) {
fTypeMethodsSplitter.setWeights(new int[] { ratio.intValue(), 1000 - ratio.intValue() });
}
ScrollBar bar= getCurrentViewer().getTree().getVerticalBar();
if (bar != null) {
Integer vScroll= memento.getInteger(TAG_VERTICAL_SCROLL);
if (vScroll != null) {
bar.setSelection(vScroll.intValue());
}
}
//String selectionId= memento.getString(TAG_SELECTION);
// do not restore type hierarchy contents
// if (selectionId != null) {
// IJavaElement elem= JavaCore.create(selectionId);
// if (getCurrentViewer().isElementShown(elem) && elem instanceof IMember) {
// internalSelectType((IMember)elem, false);
// }
// }
fMethodsViewer.restoreState(memento);
}
private void restoreLinkingEnabled(IMemento memento) {
Integer val= memento.getInteger(PreferenceConstants.LINK_TYPEHIERARCHY_TO_EDITOR);
if (val != null) {
fLinkingEnabled= val.intValue() != 0;
}
}
/**
* view part becomes visible
*/
protected void visibilityChanged(boolean isVisible) {
fIsVisible= isVisible;
if (isVisible && fNeedRefresh) {
doTypeHierarchyChangedOnViewers(null);
}
fNeedRefresh= false;
}
/**
* Link selection to active editor.
*/
protected void editorActivated(IEditorPart editor) {
if (!isLinkingEnabled()) {
return;
}
if (fInputElement == null) {
// no type hierarchy shown
return;
}
IJavaElement elem= (IJavaElement)editor.getEditorInput().getAdapter(IJavaElement.class);
try {
TypeHierarchyViewer currentViewer= getCurrentViewer();
if (elem instanceof IClassFile) {
IType type= ((IClassFile)elem).getType();
if (currentViewer.isElementShown(type)) {
internalSelectType(type, true);
updateMethodViewer(type);
}
} else if (elem instanceof ICompilationUnit) {
IType[] allTypes= ((ICompilationUnit)elem).getAllTypes();
for (int i= 0; i < allTypes.length; i++) {
if (currentViewer.isElementShown(allTypes[i])) {
internalSelectType(allTypes[i], true);
updateMethodViewer(allTypes[i]);
return;
}
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput()
*/
public Object getViewPartInput() {
return fInputElement;
}
/**
* Returns the <code>IShowInSource</code> for this view.
*/
protected IShowInSource getShowInSource() {
return new IShowInSource() {
public ShowInContext getShowInContext() {
return new ShowInContext(
null,
getSite().getSelectionProvider().getSelection());
}
};
}
boolean isLinkingEnabled() {
return fLinkingEnabled;
}
public void setLinkingEnabled(boolean enabled) {
fLinkingEnabled= enabled;
PreferenceConstants.getPreferenceStore().setValue(PreferenceConstants.LINK_TYPEHIERARCHY_TO_EDITOR, enabled);
if (enabled) {
IEditorPart editor = getSite().getPage().getActiveEditor();
if (editor != null) {
editorActivated(editor);
}
}
}
public void clearNeededRefresh() {
fNeedRefresh= false;
}
}
|
31,818 |
Bug 31818 [navigation] Open Type Hierarchy loses selection
|
build I20030211 - open a CU (e.g. BookmarkNavigator.java) - position the cursor between methods - F4 - it opens the type hierarchy on the class, but also changes the text editor's selection to select the class name It should not affect the text editor selection.
|
resolved fixed
|
f433653
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-30T11:41:31Z | 2003-02-13T21:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/util/OpenTypeHierarchyUtil.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.util;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.util.Assert;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.WorkbenchException;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
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.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaUIMessages;
import org.eclipse.jdt.internal.ui.actions.OpenActionUtil;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.typehierarchy.TypeHierarchyViewPart;
public class OpenTypeHierarchyUtil {
private OpenTypeHierarchyUtil() {
}
public static TypeHierarchyViewPart open(IJavaElement element, IWorkbenchWindow window) {
IJavaElement[] candidates= getCandidates(element);
if (candidates != null) {
return open(candidates, window);
}
return null;
}
public static TypeHierarchyViewPart open(IJavaElement[] candidates, IWorkbenchWindow window) {
Assert.isTrue(candidates != null && candidates.length != 0);
IJavaElement input= null;
if (candidates.length > 1) {
String title= JavaUIMessages.getString("OpenTypeHierarchyUtil.selectionDialog.title"); //$NON-NLS-1$
String message= JavaUIMessages.getString("OpenTypeHierarchyUtil.selectionDialog.message"); //$NON-NLS-1$
input= OpenActionUtil.selectJavaElement(candidates, window.getShell(), title, message);
} else {
input= candidates[0];
}
if (input == null)
return null;
try {
if (PreferenceConstants.OPEN_TYPE_HIERARCHY_IN_PERSPECTIVE.equals(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.OPEN_TYPE_HIERARCHY))) {
return openInPerspective(window, input);
} else {
return openInViewPart(window, input);
}
} catch (WorkbenchException e) {
ExceptionHandler.handle(e, window.getShell(),
JavaUIMessages.getString("OpenTypeHierarchyUtil.error.open_perspective"), //$NON-NLS-1$
e.getMessage());
} catch (JavaModelException e) {
ExceptionHandler.handle(e, window.getShell(),
JavaUIMessages.getString("OpenTypeHierarchyUtil.error.open_editor"), //$NON-NLS-1$
e.getMessage());
}
return null;
}
private static TypeHierarchyViewPart openInViewPart(IWorkbenchWindow window, IJavaElement input) {
IWorkbenchPage page= window.getActivePage();
try {
TypeHierarchyViewPart result= (TypeHierarchyViewPart) page.findView(JavaUI.ID_TYPE_HIERARCHY);
if (result != null) {
result.clearNeededRefresh(); // avoid refresh of old hierarchy on 'becomes visible'
}
result= (TypeHierarchyViewPart) page.showView(JavaUI.ID_TYPE_HIERARCHY);
result.setInputElement(input);
if (input instanceof IMember) {
result.selectMember((IMember) input);
openEditor(input, false);
}
return result;
} catch (CoreException e) {
ExceptionHandler.handle(e, window.getShell(),
JavaUIMessages.getString("OpenTypeHierarchyUtil.error.open_view"), e.getMessage()); //$NON-NLS-1$
}
return null;
}
private static TypeHierarchyViewPart openInPerspective(IWorkbenchWindow window, IJavaElement input) throws WorkbenchException, JavaModelException {
IWorkbench workbench= JavaPlugin.getDefault().getWorkbench();
// The problem is that the input element can be a working copy. So we first convert it to the original element if
// it exists.
IJavaElement perspectiveInput= input;
if (input instanceof IMember) {
input= JavaModelUtil.toOriginal((IMember)input);
if (input.getElementType() != IJavaElement.TYPE) {
perspectiveInput= ((IMember)input).getDeclaringType();
} else {
perspectiveInput= input;
}
}
IWorkbenchPage page= workbench.showPerspective(JavaUI.ID_HIERARCHYPERSPECTIVE, window, perspectiveInput);
TypeHierarchyViewPart part= (TypeHierarchyViewPart) page.findView(JavaUI.ID_TYPE_HIERARCHY);
if (part != null) {
part.clearNeededRefresh(); // avoid refresh of old hierarchy on 'becomes visible'
}
part= (TypeHierarchyViewPart) page.showView(JavaUI.ID_TYPE_HIERARCHY);
part.setInputElement(perspectiveInput);
if (input instanceof IMember) {
part.selectMember((IMember) input);
openEditor(input, false);
}
return part;
}
private static void openEditor(Object input, boolean activate) throws PartInitException, JavaModelException {
IEditorPart part= EditorUtility.openInEditor(input, activate);
if (input instanceof IJavaElement)
EditorUtility.revealInEditor(part, (IJavaElement) input);
}
/**
* Converts the input to a possible input candidates
*/
public static IJavaElement[] getCandidates(Object input) {
if (!(input instanceof IJavaElement)) {
return null;
}
try {
IJavaElement elem= (IJavaElement) input;
switch (elem.getElementType()) {
case IJavaElement.INITIALIZER:
case IJavaElement.METHOD:
case IJavaElement.FIELD:
case IJavaElement.TYPE:
case IJavaElement.PACKAGE_FRAGMENT_ROOT:
case IJavaElement.JAVA_PROJECT:
return new IJavaElement[] { elem };
case IJavaElement.PACKAGE_FRAGMENT:
if (((IPackageFragment)elem).containsJavaResources())
return new IJavaElement[] {elem};
break;
case IJavaElement.PACKAGE_DECLARATION:
return new IJavaElement[] { elem.getAncestor(IJavaElement.PACKAGE_FRAGMENT) };
case IJavaElement.IMPORT_DECLARATION:
IImportDeclaration decl= (IImportDeclaration) elem;
if (decl.isOnDemand()) {
elem= JavaModelUtil.findTypeContainer(elem.getJavaProject(), Signature.getQualifier(elem.getElementName()));
} else {
elem= elem.getJavaProject().findType(elem.getElementName());
}
if (elem == null)
return null;
return new IJavaElement[] {elem};
case IJavaElement.CLASS_FILE:
return new IJavaElement[] { ((IClassFile)input).getType() };
case IJavaElement.COMPILATION_UNIT: {
ICompilationUnit cu= (ICompilationUnit) elem.getAncestor(IJavaElement.COMPILATION_UNIT);
if (cu != null) {
IType[] types= cu.getTypes();
if (types.length > 0) {
return types;
}
}
break;
}
default:
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
return null;
}
}
|
50,768 |
Bug 50768 [navigation] outline popup cannot be scrolled
|
I20040128 If I open the content outline popup on a class with a large number of methods (such as core.internal.resources.Workspace.java), it fills the height of the screen, and there is no way to scroll down in the list (no scrollbars, and arrow down does not cause it to scroll).
|
verified fixed
|
16240c9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-01-30T15:41:46Z | 2004-01-28T17:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/text/JavaSourceViewerConfiguration.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.text;
import java.util.Vector;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.DefaultInformationControl;
import org.eclipse.jface.text.DefaultTextDoubleClickStrategy;
import org.eclipse.jface.text.IAutoIndentStrategy;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IInformationControl;
import org.eclipse.jface.text.IInformationControlCreator;
import org.eclipse.jface.text.ITextDoubleClickStrategy;
import org.eclipse.jface.text.ITextHover;
import org.eclipse.jface.text.ITextViewerExtension2;
import org.eclipse.jface.text.contentassist.ContentAssistant;
import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
import org.eclipse.jface.text.contentassist.IContentAssistant;
import org.eclipse.jface.text.formatter.ContentFormatter2;
import org.eclipse.jface.text.formatter.IContentFormatter;
import org.eclipse.jface.text.formatter.IFormattingStrategy;
import org.eclipse.jface.text.information.IInformationPresenter;
import org.eclipse.jface.text.information.IInformationProvider;
import org.eclipse.jface.text.information.InformationPresenter;
import org.eclipse.jface.text.presentation.IPresentationReconciler;
import org.eclipse.jface.text.presentation.PresentationReconciler;
import org.eclipse.jface.text.reconciler.IReconciler;
import org.eclipse.jface.text.rules.DefaultDamagerRepairer;
import org.eclipse.jface.text.rules.RuleBasedScanner;
import org.eclipse.jface.text.source.IAnnotationHover;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.actions.IJavaEditorActionDefinitionIds;
import org.eclipse.jdt.internal.corext.util.CodeFormatterUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.ContentAssistPreference;
import org.eclipse.jdt.internal.ui.text.HTMLTextPresenter;
import org.eclipse.jdt.internal.ui.text.IJavaPartitions;
import org.eclipse.jdt.internal.ui.text.JavaAnnotationHover;
import org.eclipse.jdt.internal.ui.text.JavaElementProvider;
import org.eclipse.jdt.internal.ui.text.JavaOutlineInformationControl;
import org.eclipse.jdt.internal.ui.text.JavaReconciler;
import org.eclipse.jdt.internal.ui.text.comment.CommentFormattingStrategy;
import org.eclipse.jdt.internal.ui.text.comment.JavaDocRegion;
import org.eclipse.jdt.internal.ui.text.comment.JavaSnippetFormattingStrategy;
import org.eclipse.jdt.internal.ui.text.java.JavaAutoIndentStrategy;
import org.eclipse.jdt.internal.ui.text.java.JavaCompletionProcessor;
import org.eclipse.jdt.internal.ui.text.java.JavaDoubleClickSelector;
import org.eclipse.jdt.internal.ui.text.java.JavaFormattingStrategy;
import org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy;
import org.eclipse.jdt.internal.ui.text.java.JavaStringAutoIndentStrategy;
import org.eclipse.jdt.internal.ui.text.java.JavaStringDoubleClickSelector;
import org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverDescriptor;
import org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy;
import org.eclipse.jdt.internal.ui.text.java.hover.JavaInformationProvider;
import org.eclipse.jdt.internal.ui.text.javadoc.JavaDocAutoIndentStrategy;
import org.eclipse.jdt.internal.ui.text.javadoc.JavaDocCompletionProcessor;
import org.eclipse.jdt.internal.ui.typehierarchy.HierarchyInformationControl;
/**
* Configuration for a source viewer which shows Java code.
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*/
public class JavaSourceViewerConfiguration extends SourceViewerConfiguration {
/**
* Preference key used to look up display tab width.
*
* @since 2.0
*/
public final static String PREFERENCE_TAB_WIDTH= PreferenceConstants.EDITOR_TAB_WIDTH;
/**
* Preference key for inserting spaces rather than tabs.
*
* @since 2.0
*/
public final static String SPACES_FOR_TABS= PreferenceConstants.EDITOR_SPACES_FOR_TABS;
private JavaTextTools fJavaTextTools;
private ITextEditor fTextEditor;
private String fDocumentPartitioning;
/**
* Creates a new Java source viewer configuration for viewers in the given editor
* using the given Java tools and the specified document partitioning.
*
* @param tools the Java text tools to be used
* @param editor the editor in which the configured viewer(s) will reside
* @param partitioning the document partitioning for this configuration
* @see JavaTextTools
* @since 3.0
*/
public JavaSourceViewerConfiguration(JavaTextTools tools, ITextEditor editor, String partitioning) {
fJavaTextTools= tools;
fTextEditor= editor;
fDocumentPartitioning= partitioning;
}
/**
* Creates a new Java source viewer configuration for viewers in the given editor
* using the given Java tools.
*
* @param tools the Java text tools to be used
* @param editor the editor in which the configured viewer(s) will reside
* @see JavaTextTools
*/
public JavaSourceViewerConfiguration(JavaTextTools tools, ITextEditor editor) {
this(tools, editor, null);
}
/**
* Returns the Java source code scanner for this configuration.
*
* @return the Java source code scanner
*/
protected RuleBasedScanner getCodeScanner() {
return fJavaTextTools.getCodeScanner();
}
/**
* Returns the Java multiline comment scanner for this configuration.
*
* @return the Java multiline comment scanner
* @since 2.0
*/
protected RuleBasedScanner getMultilineCommentScanner() {
return fJavaTextTools.getMultilineCommentScanner();
}
/**
* Returns the Java singleline comment scanner for this configuration.
*
* @return the Java singleline comment scanner
* @since 2.0
*/
protected RuleBasedScanner getSinglelineCommentScanner() {
return fJavaTextTools.getSinglelineCommentScanner();
}
/**
* Returns the Java string scanner for this configuration.
*
* @return the Java string scanner
* @since 2.0
*/
protected RuleBasedScanner getStringScanner() {
return fJavaTextTools.getStringScanner();
}
/**
* Returns the JavaDoc scanner for this configuration.
*
* @return the JavaDoc scanner
*/
protected RuleBasedScanner getJavaDocScanner() {
return fJavaTextTools.getJavaDocScanner();
}
/**
* Returns the color manager for this configuration.
*
* @return the color manager
*/
protected IColorManager getColorManager() {
return fJavaTextTools.getColorManager();
}
/**
* Returns the editor in which the configured viewer(s) will reside.
*
* @return the enclosing editor
*/
protected ITextEditor getEditor() {
return fTextEditor;
}
/**
* Returns the preference store used by this configuration to initialize
* the individual bits and pieces.
*
* @return the preference store used to initialize this configuration
*
* @since 2.0
*/
public IPreferenceStore getPreferenceStore() {
return fJavaTextTools.getPreferenceStore();
}
/*
* @see SourceViewerConfiguration#getPresentationReconciler(ISourceViewer)
*/
public IPresentationReconciler getPresentationReconciler(ISourceViewer sourceViewer) {
PresentationReconciler reconciler= new PresentationReconciler();
reconciler.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer));
DefaultDamagerRepairer dr= new DefaultDamagerRepairer(getCodeScanner());
reconciler.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE);
reconciler.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE);
dr= new DefaultDamagerRepairer(getJavaDocScanner());
reconciler.setDamager(dr, IJavaPartitions.JAVA_DOC);
reconciler.setRepairer(dr, IJavaPartitions.JAVA_DOC);
dr= new DefaultDamagerRepairer(getMultilineCommentScanner());
reconciler.setDamager(dr, IJavaPartitions.JAVA_MULTI_LINE_COMMENT);
reconciler.setRepairer(dr, IJavaPartitions.JAVA_MULTI_LINE_COMMENT);
dr= new DefaultDamagerRepairer(getSinglelineCommentScanner());
reconciler.setDamager(dr, IJavaPartitions.JAVA_SINGLE_LINE_COMMENT);
reconciler.setRepairer(dr, IJavaPartitions.JAVA_SINGLE_LINE_COMMENT);
dr= new DefaultDamagerRepairer(getStringScanner());
reconciler.setDamager(dr, IJavaPartitions.JAVA_STRING);
reconciler.setRepairer(dr, IJavaPartitions.JAVA_STRING);
dr= new DefaultDamagerRepairer(getStringScanner());
reconciler.setDamager(dr, IJavaPartitions.JAVA_CHARACTER);
reconciler.setRepairer(dr, IJavaPartitions.JAVA_CHARACTER);
return reconciler;
}
/*
* @see SourceViewerConfiguration#getContentAssistant(ISourceViewer)
*/
public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) {
if (getEditor() != null) {
ContentAssistant assistant= new ContentAssistant();
assistant.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer));
IContentAssistProcessor processor= new JavaCompletionProcessor(getEditor());
assistant.setContentAssistProcessor(processor, 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(processor, IJavaPartitions.JAVA_STRING);
assistant.setContentAssistProcessor(processor, IJavaPartitions.JAVA_SINGLE_LINE_COMMENT);
assistant.setContentAssistProcessor(new JavaDocCompletionProcessor(getEditor()), IJavaPartitions.JAVA_DOC);
ContentAssistPreference.configure(assistant, getPreferenceStore());
assistant.setContextInformationPopupOrientation(ContentAssistant.CONTEXT_INFO_ABOVE);
assistant.setInformationControlCreator(getInformationControlCreator(sourceViewer));
return assistant;
}
return null;
}
/*
* @see SourceViewerConfiguration#getReconciler(ISourceViewer)
*/
public IReconciler getReconciler(ISourceViewer sourceViewer) {
if (getEditor() != null && getEditor().isEditable()) {
JavaReconciler reconciler= new JavaReconciler(getEditor(), new JavaReconcilingStrategy(getEditor()), false);
reconciler.setProgressMonitor(new NullProgressMonitor());
reconciler.setDelay(500);
return reconciler;
}
return null;
}
/*
* @see SourceViewerConfiguration#getAutoIndentStrategy(ISourceViewer, String)
*/
public IAutoIndentStrategy getAutoIndentStrategy(ISourceViewer sourceViewer, String contentType) {
if (IJavaPartitions.JAVA_DOC.equals(contentType) ||
IJavaPartitions.JAVA_MULTI_LINE_COMMENT.equals(contentType))
return new JavaDocAutoIndentStrategy(getConfiguredDocumentPartitioning(sourceViewer));
else if (IJavaPartitions.JAVA_STRING.equals(contentType))
return new JavaStringAutoIndentStrategy(getConfiguredDocumentPartitioning(sourceViewer));
return new JavaAutoIndentStrategy(getConfiguredDocumentPartitioning(sourceViewer));
}
/*
* @see SourceViewerConfiguration#getDoubleClickStrategy(ISourceViewer, String)
*/
public ITextDoubleClickStrategy getDoubleClickStrategy(ISourceViewer sourceViewer, String contentType) {
if (IJavaPartitions.JAVA_DOC.equals(contentType) ||
IJavaPartitions.JAVA_MULTI_LINE_COMMENT.equals(contentType) ||
IJavaPartitions.JAVA_SINGLE_LINE_COMMENT.equals(contentType))
return new DefaultTextDoubleClickStrategy();
else if (IJavaPartitions.JAVA_STRING.equals(contentType) ||
IJavaPartitions.JAVA_CHARACTER.equals(contentType))
return new JavaStringDoubleClickSelector(getConfiguredDocumentPartitioning(sourceViewer));
return new JavaDoubleClickSelector();
}
/*
* @see SourceViewerConfiguration#getDefaultPrefixes(ISourceViewer, String)
* @since 2.0
*/
public String[] getDefaultPrefixes(ISourceViewer sourceViewer, String contentType) {
return new String[] { "//", "" }; //$NON-NLS-1$ //$NON-NLS-2$
}
/*
* @see SourceViewerConfiguration#getIndentPrefixes(ISourceViewer, String)
*/
public String[] getIndentPrefixes(ISourceViewer sourceViewer, String contentType) {
Vector vector= new Vector();
// prefix[0] is either '\t' or ' ' x tabWidth, depending on useSpaces
int tabWidth= CodeFormatterUtil.getTabWidth();
boolean useSpaces= getPreferenceStore().getBoolean(SPACES_FOR_TABS);
for (int i= 0; i <= tabWidth; i++) {
StringBuffer prefix= new StringBuffer();
if (useSpaces) {
for (int j= 0; j + i < tabWidth; j++)
prefix.append(' ');
if (i != 0)
prefix.append('\t');
} else {
for (int j= 0; j < i; j++)
prefix.append(' ');
if (i != tabWidth)
prefix.append('\t');
}
vector.add(prefix.toString());
}
vector.add(""); //$NON-NLS-1$
return (String[]) vector.toArray(new String[vector.size()]);
}
/*
* @see SourceViewerConfiguration#getTabWidth(ISourceViewer)
*/
public int getTabWidth(ISourceViewer sourceViewer) {
return getPreferenceStore().getInt(PREFERENCE_TAB_WIDTH);
}
/*
* @see SourceViewerConfiguration#getAnnotationHover(ISourceViewer)
*/
public IAnnotationHover getAnnotationHover(ISourceViewer sourceViewer) {
return new JavaAnnotationHover(JavaAnnotationHover.VERTICAL_RULER_HOVER);
}
/*
* @see SourceViewerConfiguration#getOverviewRulerAnnotationHover(ISourceViewer)
* @since 3.0
*/
public IAnnotationHover getOverviewRulerAnnotationHover(ISourceViewer sourceViewer) {
return new JavaAnnotationHover(JavaAnnotationHover.OVERVIEW_RULER_HOVER);
}
/*
* @see SourceViewerConfiguration#getConfiguredTextHoverStateMasks(ISourceViewer, String)
* @since 2.1
*/
public int[] getConfiguredTextHoverStateMasks(ISourceViewer sourceViewer, String contentType) {
JavaEditorTextHoverDescriptor[] hoverDescs= JavaPlugin.getDefault().getJavaEditorTextHoverDescriptors();
int stateMasks[]= new int[hoverDescs.length];
int stateMasksLength= 0;
for (int i= 0; i < hoverDescs.length; i++) {
if (hoverDescs[i].isEnabled()) {
int j= 0;
int stateMask= hoverDescs[i].getStateMask();
while (j < stateMasksLength) {
if (stateMasks[j] == stateMask)
break;
j++;
}
if (j == stateMasksLength)
stateMasks[stateMasksLength++]= stateMask;
}
}
if (stateMasksLength == hoverDescs.length)
return stateMasks;
int[] shortenedStateMasks= new int[stateMasksLength];
System.arraycopy(stateMasks, 0, shortenedStateMasks, 0, stateMasksLength);
return shortenedStateMasks;
}
/*
* @see SourceViewerConfiguration#getTextHover(ISourceViewer, String, int)
* @since 2.1
*/
public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType, int stateMask) {
JavaEditorTextHoverDescriptor[] hoverDescs= JavaPlugin.getDefault().getJavaEditorTextHoverDescriptors();
int i= 0;
while (i < hoverDescs.length) {
if (hoverDescs[i].isEnabled() && hoverDescs[i].getStateMask() == stateMask)
return new JavaEditorTextHoverProxy(hoverDescs[i], getEditor());
i++;
}
return null;
}
/*
* @see SourceViewerConfiguration#getTextHover(ISourceViewer, String)
*/
public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType) {
return getTextHover(sourceViewer, contentType, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK);
}
/*
* @see SourceViewerConfiguration#getConfiguredContentTypes(ISourceViewer)
*/
public String[] getConfiguredContentTypes(ISourceViewer sourceViewer) {
return new String[] {
IDocument.DEFAULT_CONTENT_TYPE,
IJavaPartitions.JAVA_DOC,
IJavaPartitions.JAVA_MULTI_LINE_COMMENT,
IJavaPartitions.JAVA_SINGLE_LINE_COMMENT,
IJavaPartitions.JAVA_STRING,
IJavaPartitions.JAVA_CHARACTER
};
}
/*
* @see org.eclipse.jface.text.source.SourceViewerConfiguration#getConfiguredDocumentPartitioning(org.eclipse.jface.text.source.ISourceViewer)
*/
public String getConfiguredDocumentPartitioning(ISourceViewer sourceViewer) {
if (fDocumentPartitioning != null)
return fDocumentPartitioning;
return super.getConfiguredDocumentPartitioning(sourceViewer);
}
/*
* @see SourceViewerConfiguration#getContentFormatter(ISourceViewer)
*/
public IContentFormatter getContentFormatter(ISourceViewer sourceViewer) {
final ContentFormatter2 formatter= new ContentFormatter2();
formatter.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer));
IFormattingStrategy strategy= new JavaFormattingStrategy(sourceViewer);
formatter.setFormattingStrategy(strategy);
formatter.setFormattingStrategy(strategy, IDocument.DEFAULT_CONTENT_TYPE);
formatter.setFormattingStrategy(new CommentFormattingStrategy(formatter, sourceViewer), IJavaPartitions.JAVA_DOC);
formatter.setFormattingStrategy(new CommentFormattingStrategy(formatter, sourceViewer), IJavaPartitions.JAVA_SINGLE_LINE_COMMENT);
formatter.setFormattingStrategy(new CommentFormattingStrategy(formatter, sourceViewer), IJavaPartitions.JAVA_MULTI_LINE_COMMENT);
formatter.setFormattingStrategy(new JavaSnippetFormattingStrategy(sourceViewer), JavaDocRegion.JAVA_SNIPPET_PARTITION);
return formatter;
}
/*
* @see SourceViewerConfiguration#getInformationControlCreator(ISourceViewer)
* @since 2.0
*/
public IInformationControlCreator getInformationControlCreator(ISourceViewer sourceViewer) {
return new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell parent) {
return new DefaultInformationControl(parent, SWT.NONE, new HTMLTextPresenter(true));
}
};
}
/**
* Returns the information presenter control creator. The creator is a factory creating the
* presenter controls for the given source viewer. This implementation always returns a creator
* for <code>DefaultInformationControl</code> instances.
*
* @param sourceViewer the source viewer to be configured by this configuration
* @return an information control creator
* @since 2.1
*/
private IInformationControlCreator getInformationPresenterControlCreator(ISourceViewer sourceViewer) {
return new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell parent) {
int shellStyle= SWT.RESIZE;
int style= SWT.V_SCROLL | SWT.H_SCROLL;
return new DefaultInformationControl(parent, shellStyle, style, new HTMLTextPresenter(false));
// return new HoverBrowserControl(parent);
}
};
}
/**
* Returns the outline presenter control creator. The creator is a factory creating outline
* presenter controls for the given source viewer. This implementation always returns a creator
* for <code>JavaOutlineInformationControl</code> instances.
*
* @param sourceViewer the source viewer to be configured by this configuration
* @return an information control creator
* @since 2.1
*/
private IInformationControlCreator getOutlinePresenterControlCreator(ISourceViewer sourceViewer, final String commandId) {
return new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell parent) {
int shellStyle= SWT.RESIZE;
int treeStyle= SWT.V_SCROLL | SWT.H_SCROLL;
return new JavaOutlineInformationControl(parent, shellStyle, treeStyle, commandId);
}
};
}
private IInformationControlCreator getHierarchyPresenterControlCreator(ISourceViewer sourceViewer) {
return new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell parent) {
int shellStyle= SWT.RESIZE;
int treeStyle= SWT.V_SCROLL | SWT.H_SCROLL;
return new HierarchyInformationControl(parent, shellStyle, treeStyle);
}
};
}
/*
* @see SourceViewerConfiguration#getInformationPresenter(ISourceViewer)
* @since 2.0
*/
public IInformationPresenter getInformationPresenter(ISourceViewer sourceViewer) {
InformationPresenter presenter= new InformationPresenter(getInformationPresenterControlCreator(sourceViewer));
presenter.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer));
IInformationProvider provider= new JavaInformationProvider(getEditor());
presenter.setInformationProvider(provider, IDocument.DEFAULT_CONTENT_TYPE);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_DOC);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_CHARACTER);
presenter.setSizeConstraints(60, 10, true, true);
return presenter;
}
/**
* Returns the outline presenter which will determine and shown
* information requested for the current cursor position.
*
* @param sourceViewer the source viewer to be configured by this configuration
* @param doCodeResolve a boolean which specifies whether code resolve should be used to compute the Java element
* @return an information presenter
* @since 2.1
*/
public IInformationPresenter getOutlinePresenter(ISourceViewer sourceViewer, boolean doCodeResolve) {
InformationPresenter presenter;
if (doCodeResolve)
presenter= new InformationPresenter(getOutlinePresenterControlCreator(sourceViewer, IJavaEditorActionDefinitionIds.OPEN_STRUCTURE));
else
presenter= new InformationPresenter(getOutlinePresenterControlCreator(sourceViewer, IJavaEditorActionDefinitionIds.SHOW_OUTLINE));
presenter.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer));
presenter.setAnchor(InformationPresenter.ANCHOR_GLOBAL);
IInformationProvider provider= new JavaElementProvider(getEditor(), doCodeResolve);
presenter.setInformationProvider(provider, IDocument.DEFAULT_CONTENT_TYPE);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_DOC);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_MULTI_LINE_COMMENT);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_SINGLE_LINE_COMMENT);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_STRING);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_CHARACTER);
presenter.setSizeConstraints(40, 20, true, false);
return presenter;
}
public IInformationPresenter getHierarchyPresenter(ISourceViewer sourceViewer, boolean doCodeResolve) {
InformationPresenter presenter= new InformationPresenter(getHierarchyPresenterControlCreator(sourceViewer));
presenter.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer));
presenter.setAnchor(InformationPresenter.ANCHOR_GLOBAL);
IInformationProvider provider= new JavaElementProvider(getEditor(), doCodeResolve);
presenter.setInformationProvider(provider, IDocument.DEFAULT_CONTENT_TYPE);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_DOC);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_MULTI_LINE_COMMENT);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_SINGLE_LINE_COMMENT);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_STRING);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_CHARACTER);
presenter.setSizeConstraints(50, 20, true, false);
return presenter;
}
}
|
46,753 |
Bug 46753 [misc] Typing should not be blocked by background activity
|
Build 20031111 1. Open an editor 2. Start a CVS background activity (e.g. Synchronize several projects) 3. Start typing in the editor Observe: The whole UI freezes and what you typed is not shown in the editor until the end of the backgroung activity
|
verified fixed
|
f10329d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-02-03T18:24:55Z | 2003-11-17T06:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/filebuffers/CompilationUnitDocumentProvider2.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.javaeditor.filebuffers;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IMarkerDelta;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
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.Assert;
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.IAnnotationAccessExtension;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.IAnnotationModelListener;
import org.eclipse.jface.text.source.IAnnotationModelListenerExtension;
import org.eclipse.jface.text.source.IAnnotationPresentation;
import org.eclipse.ui.editors.text.EditorsUI;
import org.eclipse.ui.editors.text.TextFileDocumentProvider;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.texteditor.AbstractMarkerAnnotationModel;
import org.eclipse.ui.texteditor.AnnotationPreference;
import org.eclipse.ui.texteditor.AnnotationPreferenceLookup;
import org.eclipse.ui.texteditor.MarkerAnnotation;
import org.eclipse.ui.texteditor.MarkerUtilities;
import org.eclipse.ui.texteditor.ResourceMarkerAnnotationModel;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IProblemRequestor;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.text.spelling.SpellReconcileStrategy.SpellProblem;
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, IAnnotationPresentation {
private static final String SPELLING_ANNOTATION_TYPE= "org.eclipse.ui.workbench.texteditor.spelling";
//XXX: To be fully correct these constants should be non-static
/**
* The layer in which task problem annotations are located.
*/
private static final int TASK_LAYER;
/**
* The layer in which info problem annotations are located.
*/
private static final int INFO_LAYER;
/**
* The layer in which warning problem annotations representing are located.
*/
private static final int WARNING_LAYER;
/**
* The layer in which error problem annotations representing are located.
*/
private static final int ERROR_LAYER;
static {
AnnotationPreferenceLookup lookup= EditorsUI.getAnnotationPreferenceLookup();
TASK_LAYER= computeLayer("org.eclipse.ui.workbench.texteditor.task", lookup); //$NON-NLS-1$
INFO_LAYER= computeLayer("org.eclipse.jdt.ui.info", lookup); //$NON-NLS-1$
WARNING_LAYER= computeLayer("org.eclipse.jdt.ui.warning", lookup); //$NON-NLS-1$
ERROR_LAYER= computeLayer("org.eclipse.jdt.ui.error", lookup); //$NON-NLS-1$
}
private static int computeLayer(String annotationType, AnnotationPreferenceLookup lookup) {
Annotation annotation= new Annotation(annotationType, false, null);
AnnotationPreference preference= lookup.getAnnotationPreference(annotation);
if (preference != null)
return preference.getPresentationLayer() + 1;
else
return IAnnotationAccessExtension.DEFAULT_LAYER + 1;
}
private 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 int fLayer= IAnnotationAccessExtension.DEFAULT_LAYER;
public ProblemAnnotation(IProblem problem, ICompilationUnit cu) {
fProblem= problem;
fCompilationUnit= cu;
if (SpellProblem.Spelling == fProblem.getID()) {
setType(SPELLING_ANNOTATION_TYPE);
fLayer= WARNING_LAYER;
} else if (IProblem.Task == fProblem.getID()) {
setType(JavaMarkerAnnotation.TASK_ANNOTATION_TYPE);
fLayer= TASK_LAYER;
} else if (fProblem.isWarning()) {
setType(JavaMarkerAnnotation.WARNING_ANNOTATION_TYPE);
fLayer= WARNING_LAYER;
} else if (fProblem.isError()) {
setType(JavaMarkerAnnotation.ERROR_ANNOTATION_TYPE);
fLayer= ERROR_LAYER;
} else {
setType(JavaMarkerAnnotation.INFO_ANNOTATION_TYPE);
fLayer= INFO_LAYER;
}
}
/*
* @see org.eclipse.jface.text.source.IAnnotationPresentation#getLayer()
*/
public int getLayer() {
return fLayer;
}
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 (JavaMarkerAnnotation.ERROR_ANNOTATION_TYPE.equals(getType()))
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 getText() {
return fProblem.getMessage();
}
/*
* @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() {
String type= getType();
return JavaMarkerAnnotation.WARNING_ANNOTATION_TYPE.equals(type) ||
JavaMarkerAnnotation.ERROR_ANNOTATION_TYPE.equals(type) ||
SPELLING_ANNOTATION_TYPE.equals(type);
}
/*
* @see IJavaAnnotation#hasOverlay()
*/
public boolean hasOverlay() {
return false;
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.IJavaAnnotation#getOverlay()
*/
public IJavaAnnotation getOverlay() {
return null;
}
/*
* @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;
}
/*
* @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 boolean fIncludesProblemAnnotationChanges= false;
public CompilationUnitAnnotationModel(IResource resource) {
super(resource);
}
public void setCompilationUnit(ICompilationUnit unit) {
fCompilationUnit= unit;
}
protected MarkerAnnotation createMarkerAnnotation(IMarker marker) {
String markerType= MarkerUtilities.getMarkerType(marker);
if (markerType != null && markerType.startsWith(JavaMarkerAnnotation.JAVA_MARKER_TYPE_PREFIX))
return new JavaMarkerAnnotation(marker);
return super.createMarkerAnnotation(marker);
}
/*
* @see org.eclipse.jface.text.source.AnnotationModel#createAnnotationModelEvent()
*/
protected AnnotationModelEvent createAnnotationModelEvent() {
return new CompilationUnitAnnotationModelEvent(this, getResource());
}
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 (fIncludesProblemAnnotationChanges) {
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);
overlayMarkers(position, annotation);
addAnnotation(annotation, position, false);
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);
}
} else {
}
}
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 org.eclipse.jface.text.source.AnnotationModel#fireModelChanged(org.eclipse.jface.text.source.AnnotationModelEvent)
*/
protected void fireModelChanged(AnnotationModelEvent event) {
if (event instanceof CompilationUnitAnnotationModelEvent) {
CompilationUnitAnnotationModelEvent e= (CompilationUnitAnnotationModelEvent) event;
fIncludesProblemAnnotationChanges= e.includesProblemMarkerAnnotationChanges();
}
super.fireModelChanged(event);
}
/*
* @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);
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) {
super.removeAllAnnotations(fireModelChanged);
fReverseMap.clear();
}
/*
* @see AnnotationModel#removeAnnotation(Annotation, boolean)
*/
protected void removeAnnotation(Annotation annotation, boolean fireModelChanged) {
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);
}
if (cuInfo.fModel != null)
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();
}
if (cuInfo.fModel != null)
cuInfo.fModel.removeAnnotationModelListener(fGlobalAnnotationModelListener);
}
super.disposeFileInfo(element, info);
}
protected void commitWorkingCopy(IProgressMonitor monitor, Object element, CompilationUnitInfo info, boolean overwrite) throws CoreException {
synchronized (info.fCopy) {
info.fCopy.reconcile();
}
IDocument document= info.fTextFileBuffer.getDocument();
ICompilationUnit original= (ICompilationUnit) info.fCopy.getOriginalElement();
IResource resource= original.getResource();
Assert.isTrue(resource instanceof IFile);
if (!resource.exists()) {
// underlying resource has been deleted, just recreate file, ignore the rest
createFileFromDocument(monitor, (IFile) resource, document);
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, document, 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.
if (info.fModel instanceof AbstractMarkerAnnotationModel) {
AbstractMarkerAnnotationModel model= (AbstractMarkerAnnotationModel) info.fModel;
model.updateMarkers(document);
}
if (fSavePolicy != null) {
ICompilationUnit unit= fSavePolicy.postSave(original);
if (unit != null && info.fModel instanceof AbstractMarkerAnnotationModel) {
IResource r= unit.getResource();
IMarker[] markers= r.findMarkers(IMarker.MARKER, true, IResource.DEPTH_ZERO);
if (markers != null && markers.length > 0) {
AbstractMarkerAnnotationModel model= (AbstractMarkerAnnotationModel) info.fModel;
for (int i= 0; i < markers.length; i++)
model.updateMarker(markers[i], document, null);
}
}
}
}
/*
* @see org.eclipse.ui.editors.text.TextFileDocumentProvider#createSaveOperation(java.lang.Object, org.eclipse.jface.text.IDocument, boolean)
*/
protected DocumentProviderOperation createSaveOperation(final Object element, final IDocument document, final boolean overwrite) throws CoreException {
final FileInfo info= getFileInfo(element);
if (info instanceof CompilationUnitInfo) {
return new DocumentProviderOperation() {
protected void execute(IProgressMonitor monitor) throws CoreException {
commitWorkingCopy(monitor, element, (CompilationUnitInfo) info, overwrite);
}
/*
* @see org.eclipse.ui.editors.text.TextFileDocumentProvider.DocumentProviderOperation#getSchedulingRule()
*/
public ISchedulingRule getSchedulingRule() {
if (info.fElement instanceof IFileEditorInput)
return ((IFileEditorInput)info.fElement).getFile().getParent();
else
return null;
}
};
}
return null;
}
/**
* 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();
}
}
|
28,716 |
Bug 28716 [misc] 'Goto Matching Bracket' fails when 'Show Source of Selected Element Only' is selected
|
When the 'Show Source of Selected Element Only' button is pressed and the editor is narrowed down to the selected method the Goto Matching Bracket action fails. It reports 'No Matching Bracket' found in the status bar. Invoking the same action on the same bracket when the editor shows the whole of the source file works as expected.
|
resolved fixed
|
68178cb
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-02-03T18:30:58Z | 2002-12-20T10:26: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.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
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.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Preferences;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
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.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
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.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
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.ITextPresentationListener;
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.TextPresentation;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.text.TextUtilities;
import org.eclipse.jface.text.information.IInformationProvider;
import org.eclipse.jface.text.information.IInformationProviderExtension2;
import org.eclipse.jface.text.information.InformationPresenter;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.AnnotationRulerColumn;
import org.eclipse.jface.text.source.CompositeRuler;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.IAnnotationModelExtension;
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.IEditorPart;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPartService;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.editors.text.DefaultEncodingSupport;
import org.eclipse.ui.editors.text.EditorsUI;
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.AnnotationPreference;
import org.eclipse.ui.texteditor.DefaultRangeIndicator;
import org.eclipse.ui.texteditor.ExtendedTextEditor;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.ui.texteditor.IEditorStatusLine;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
import org.eclipse.ui.texteditor.IUpdate;
import org.eclipse.ui.texteditor.MarkerAnnotation;
import org.eclipse.ui.texteditor.ResourceAction;
import org.eclipse.ui.texteditor.SourceViewerDecorationSupport;
import org.eclipse.ui.texteditor.TextEditorAction;
import org.eclipse.ui.texteditor.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.ILocalVariable;
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.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.CompilationUnit;
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.search.ExceptionOccurrencesFinder;
import org.eclipse.jdt.internal.ui.search.OccurrencesFinder;
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.text.java.hover.JavaExpandHover;
import org.eclipse.jdt.internal.ui.util.JavaUIHelp;
import org.eclipse.jdt.internal.ui.viewsupport.ISelectionListenerWithAST;
import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider;
import org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager;
/**
* 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 selectionProviderstyle
*/
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();
if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE))
synchronizeOutlinePage(element);
setSelection(element, false);
updateStatusLine();
}
}
/**
* 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, ITextPresentationListener {
/** 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);
((ITextViewerExtension4)sourceViewer).addTextPresentationListener(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);
((ITextViewerExtension4)sourceViewer).removeTextPresentationListener(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);
// Invalidate ==> remove applied text presentation
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();
}
try {
StyledText text= viewer.getTextWidget();
text.redrawRange(offset, length, false);
} 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;
}
}
public void applyTextPresentation(TextPresentation textPresentation) {
if (fActiveRegion == null)
return;
IRegion region= textPresentation.getExtent();
if (fActiveRegion.getOffset() + fActiveRegion.getLength() >= region.getOffset() && region.getOffset() + region.getLength() > fActiveRegion.getOffset())
textPresentation.mergeStyleRange(new StyleRange(fActiveRegion.getOffset(), fActiveRegion.getLength(), fColor, null));
}
private void highlightRegion(ISourceViewer viewer, IRegion region) {
if (region.equals(fActiveRegion))
return;
repairRepresentation();
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
// Underline
int offset= 0;
int length= 0;
if (viewer instanceof 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();
}
text.redrawRange(offset, length, false);
// Invalidate region ==> apply text presentation
fActiveRegion= region;
if (viewer instanceof ITextViewerExtension2)
((ITextViewerExtension2) viewer).invalidateTextPresentation(region.getOffset(), region.getLength());
else
viewer.invalidateTextPresentation();
}
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;
}
}
}
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();
}
}
}
}
/**
* Internal activation listener.
* @since 3.0
*/
private class ActivationListener extends ShellAdapter {
/*
* @see org.eclipse.swt.events.ShellAdapter#shellActivated(org.eclipse.swt.events.ShellEvent)
*/
public void shellActivated(ShellEvent e) {
if (fMarkOccurrenceAnnotations && isActivePart())
SelectionListenerWithASTManager.getDefault().forceSelectionChange(JavaEditor.this, (ITextSelection)getSelectionProvider().getSelection());
}
/*
* @see org.eclipse.swt.events.ShellAdapter#shellDeactivated(org.eclipse.swt.events.ShellEvent)
*/
public void shellDeactivated(ShellEvent e) {
removeOccurrenceAnnotations();
}
}
/** 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();
/**
* Indicates whether this editor is about to update any annotation views.
* @since 3.0
*/
private boolean fIsUpdatingAnnotationViews= false;
/**
* The marker that served as last target for a goto marker request.
* @since 3.0
*/
private IMarker fLastMarkerTarget= null;
protected CompositeActionGroup fActionGroups;
private CompositeActionGroup fContextMenuGroup;
/**
* Holds the current occurrence annotations.
* @since 3.0
*/
private Annotation[] fOccurrenceAnnotations= null;
/**
* Tells whether all occurrences of the element at the
* current caret location are automatically marked in
* this editor.
* @since 3.0
*/
private boolean fMarkOccurrenceAnnotations;
/**
* The internal shell activation listener for updating occurrences.
* @since 3.0
*/
private ActivationListener fActivationListener= new ActivationListener();
private ISelectionListenerWithAST fPostSelectionListenerWithAST;
private Job fOccurrencesFinderJob;
/**
* 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());
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
setPreferenceStore(store);
setKeyBindingScopes(new String[] { "org.eclipse.jdt.ui.javaEditorScope" }); //$NON-NLS-1$
fMarkOccurrenceAnnotations= store.getBoolean(PreferenceConstants.EDITOR_MARK_OCCURRENCES);
}
/*
* @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;
}
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= null;
if (reference instanceof ILocalVariable) {
IJavaElement je= ((ILocalVariable)reference).getParent();
if (je instanceof ISourceReference)
range= ((ISourceReference)je).getSourceRange();
} else
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 ILocalVariable) {
range= ((ILocalVariable)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() {
// cancel possible running computation
fMarkOccurrenceAnnotations= false;
uninstallOccurrencesFinder();
if (fActivationListener != null) {
Shell shell= getEditorSite().getShell();
if (shell != null && !shell.isDisposed())
shell.removeShellListener(fActivationListener);
fActivationListener= null;
}
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();
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});
ResourceAction 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);
action= new RemoveOccurrenceAnnotations(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.REMOVE_OCCURRENCE_ANNOTATIONS);
setAction("RemoveOccurrenceAnnotations", action); //$NON-NLS-1$
// add annotation actions
action= new JavaSelectMarkerRulerAction2(JavaEditorMessages.getResourceBundle(), "Editor.RulerAnnotationSelection.", this); //$NON-NLS-1$
setAction("AnnotationAction", action); //$NON-NLS-1$
}
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.selectionChanged();
return;
}
if (PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE.equals(property)) {
if (event.getNewValue() instanceof Boolean) {
Boolean disable= (Boolean) event.getNewValue();
configureInsertMode(OVERWRITE, !disable.booleanValue());
}
}
if (PreferenceConstants.EDITOR_MARK_OCCURRENCES.equals(property)) {
if (event.getNewValue() instanceof Boolean) {
boolean markOccurrenceAnnotations= ((Boolean)event.getNewValue()).booleanValue();
if (markOccurrenceAnnotations != fMarkOccurrenceAnnotations) {
fMarkOccurrenceAnnotations= markOccurrenceAnnotations;
if (!fMarkOccurrenceAnnotations)
uninstallOccurrencesFinder();
else
installOccurrencesFinder();
}
}
}
} finally {
super.handlePreferenceStoreChanged(event);
}
}
/**
* Initializes the given viewer's colors.
*
* @param viewer the viewer to be initialized
* @since 3.0
*/
protected void initializeViewerColors(ISourceViewer viewer) {
// is handled by JavaSourceViewer
}
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());
fEditorSelectionChangedListener= new EditorSelectionChangedListener();
fEditorSelectionChangedListener.install(getSelectionProvider());
if (isBrowserLikeLinks())
enableBrowserLikeLinks();
if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE))
configureInsertMode(OVERWRITE, false);
if (fMarkOccurrenceAnnotations)
installOccurrencesFinder();
getEditorSite().getShell().addShellListener(fActivationListener);
}
protected void configureSourceViewerDecorationSupport(SourceViewerDecorationSupport support) {
support.setCharacterPairMatcher(fBracketMatcher);
support.setMatchingCharacterPainterPreferenceKeys(MATCHING_BRACKETS, MATCHING_BRACKETS_COLOR);
super.configureSourceViewerDecorationSupport(support);
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#gotoMarker(org.eclipse.core.resources.IMarker)
*/
public void gotoMarker(IMarker marker) {
fLastMarkerTarget= marker;
if (!fIsUpdatingAnnotationViews) {
super.gotoMarker(marker);
}
}
/**
* 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.
*
* @param forward <code>true</code> if search direction is forward, <code>false</code> if backward
*/
public void gotoAnnotation(boolean forward) {
ITextSelection selection= (ITextSelection) getSelectionProvider().getSelection();
Position position= new Position(0, 0);
if (false /* delayed - see bug 18316 */) {
getNextAnnotation(selection.getOffset(), selection.getLength(), forward, position);
selectAndReveal(position.getOffset(), position.getLength());
} else /* no delay - see bug 18316 */ {
Annotation annotation= getNextAnnotation(selection.getOffset(), selection.getLength(), forward, position);
setStatusLineErrorMessage(null);
setStatusLineMessage(null);
if (annotation != null) {
updateAnnotationViews(annotation);
selectAndReveal(position.getOffset(), position.getLength());
setStatusLineMessage(annotation.getText());
}
}
}
/**
* Updates the annotation views that show the given annotation.
*
* @param annotation the annotation
*/
private void updateAnnotationViews(Annotation annotation) {
IMarker marker= null;
if (annotation instanceof MarkerAnnotation)
marker= ((MarkerAnnotation) annotation).getMarker();
else if (annotation instanceof IJavaAnnotation) {
Iterator e= ((IJavaAnnotation) annotation).getOverlaidIterator();
if (e != null) {
while (e.hasNext()) {
Object o= e.next();
if (o instanceof MarkerAnnotation) {
marker= ((MarkerAnnotation) o).getMarker();
break;
}
}
}
}
if (marker != null && !marker.equals(fLastMarkerTarget)) {
try {
boolean isProblem= marker.isSubtypeOf(IMarker.PROBLEM);
IWorkbenchPage page= getSite().getPage();
IViewPart view= page.findView(isProblem ? IPageLayout.ID_PROBLEM_VIEW: IPageLayout.ID_TASK_LIST); //$NON-NLS-1$ //$NON-NLS-2$
if (view != null) {
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 exceptions, don't update any of the lists, just set statusline
}
}
/**
* Finds and marks occurrence annotations.
*
* @since 3.0
*/
class OccurrencesFinderJob extends Job implements IDocumentListener {
private IDocument fDocument;
private boolean fCancelled= false;
private IProgressMonitor fProgressMonitor;
private Position[] fPositions;
public OccurrencesFinderJob(IDocument document, Position[] positions) {
super("Occurrences Marker"); //$NON-NLS-1$
fDocument= document;
fPositions= positions;
fDocument.addDocumentListener(this);
}
private boolean isCancelled() {
return fCancelled || fProgressMonitor.isCanceled();
}
/*
* @see Job#run(org.eclipse.core.runtime.IProgressMonitor)
*/
public IStatus run(IProgressMonitor progressMonitor) {
fProgressMonitor= progressMonitor;
try {
if (isCancelled())
return Status.CANCEL_STATUS;
ITextViewer textViewer= getViewer();
if (textViewer == null)
return Status.CANCEL_STATUS;
IDocument document= textViewer.getDocument();
if (document == null)
return Status.CANCEL_STATUS;
IDocumentProvider documentProvider= getDocumentProvider();
if (documentProvider == null)
return Status.CANCEL_STATUS;
IAnnotationModel annotationModel= documentProvider.getAnnotationModel(getEditorInput());
if (annotationModel == null)
return Status.CANCEL_STATUS;
// Add occurrence annotations
int length= fPositions.length;
Map annotationMap= new HashMap(length);
for (int i= 0; i < length; i++) {
if (isCancelled())
return Status.CANCEL_STATUS;
String message;
Position position= fPositions[i];
// Create & add annotation
try {
message= document.get(position.offset, position.length);
} catch (BadLocationException ex) {
// Skip this match
continue;
}
annotationMap.put(
new Annotation("org.eclipse.jdt.ui.occurrences", false, message), //$NON-NLS-1$
position);
}
if (isCancelled())
return Status.CANCEL_STATUS;
synchronized (annotationModel) {
if (annotationModel instanceof IAnnotationModelExtension) {
((IAnnotationModelExtension)annotationModel).replaceAnnotations(fOccurrenceAnnotations, annotationMap);
} else {
removeOccurrenceAnnotations();
Iterator iter= annotationMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry mapEntry= (Map.Entry)iter.next();
annotationModel.addAnnotation((Annotation)mapEntry.getKey(), (Position)mapEntry.getValue());
}
}
fOccurrenceAnnotations= (Annotation[])annotationMap.keySet().toArray(new Annotation[annotationMap.keySet().size()]);
}
} finally {
fDocument.removeDocumentListener(this);
}
return Status.OK_STATUS;
}
/*
* @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent)
*/
public void documentAboutToBeChanged(DocumentEvent event) {
fCancelled= true;
}
/*
* @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent)
*/
public void documentChanged(DocumentEvent event) {
}
}
/**
* Updates the occurrences annotations based
* on the current selection.
*
* @since 3.0
*/
protected void updateOccurrenceAnnotations(ITextSelection selection, CompilationUnit astRoot) {
if (!fMarkOccurrenceAnnotations)
return;
if (astRoot == null || selection == null)
return;
IDocument document= getSourceViewer().getDocument();
if (document == null)
return;
if (fOccurrencesFinderJob != null)
fOccurrencesFinderJob.cancel();
ExceptionOccurrencesFinder exceptionFinder= new ExceptionOccurrencesFinder();
String message= exceptionFinder.initialize(astRoot, selection.getOffset(), selection.getLength());
List matches= new ArrayList();
if (message == null) {
matches= exceptionFinder.perform();
}
if (matches.size() == 0) {
// Find the matches && extract positions so we can forget the AST
OccurrencesFinder finder = new OccurrencesFinder();
message= finder.initialize(astRoot, selection.getOffset(), selection.getLength());
if (message == null) {
matches= finder.perform();
}
}
Position[] positions= new Position[matches.size()];
int i= 0;
for (Iterator each= matches.iterator(); each.hasNext();) {
ASTNode currentNode= (ASTNode)each.next();
positions[i++]= new Position(currentNode.getStartPosition(), currentNode.getLength());
}
fOccurrencesFinderJob= new OccurrencesFinderJob(document, positions);
//fOccurrencesFinderJob.setPriority(Job.DECORATE);
//fOccurrencesFinderJob.setSystem(true);
//fOccurrencesFinderJob.schedule();
((OccurrencesFinderJob) fOccurrencesFinderJob).run(new NullProgressMonitor());
}
protected void installOccurrencesFinder() {
fMarkOccurrenceAnnotations= true;
fPostSelectionListenerWithAST= new ISelectionListenerWithAST() {
public void selectionChanged(IEditorPart part, ITextSelection selection, CompilationUnit astRoot) {
updateOccurrenceAnnotations(selection, astRoot);
}
};
SelectionListenerWithASTManager.getDefault().addListener(this, fPostSelectionListenerWithAST);
}
protected void uninstallOccurrencesFinder() {
fMarkOccurrenceAnnotations= false;
if (fOccurrencesFinderJob != null) {
fOccurrencesFinderJob.cancel();
fOccurrencesFinderJob= null;
}
if (fPostSelectionListenerWithAST != null) {
SelectionListenerWithASTManager.getDefault().removeListener(this, fPostSelectionListenerWithAST);
fPostSelectionListenerWithAST= null;
}
removeOccurrenceAnnotations();
}
void removeOccurrenceAnnotations() {
IDocumentProvider documentProvider= getDocumentProvider();
if (documentProvider == null)
return;
IAnnotationModel annotationModel= documentProvider.getAnnotationModel(getEditorInput());
if (annotationModel == null || fOccurrenceAnnotations == null)
return;
synchronized (annotationModel) {
if (annotationModel instanceof IAnnotationModelExtension) {
((IAnnotationModelExtension)annotationModel).replaceAnnotations(fOccurrenceAnnotations, null);
} else {
for (int i= 0, length= fOccurrenceAnnotations.length; i < length; i++)
annotationModel.removeAnnotation(fOccurrenceAnnotations[i]);
}
fOccurrenceAnnotations= null;
}
}
/**
* Returns the Java element wrapped by this editors input.
*
* @return the Java element wrapped by this editors input.
* @since 3.0
*/
abstract protected IJavaElement getInputJavaElement();
protected void updateStatusLine() {
ITextSelection selection= (ITextSelection) getSelectionProvider().getSelection();
Annotation annotation= getAnnotation(selection.getOffset(), selection.getLength());
setStatusLineErrorMessage(null);
setStatusLineMessage(null);
if (annotation != null) {
try {
fIsUpdatingAnnotationViews= true;
updateAnnotationViews(annotation);
} finally {
fIsUpdatingAnnotationViews= false;
}
if (annotation instanceof IJavaAnnotation && ((IJavaAnnotation) annotation).isProblem())
setStatusLineMessage(annotation.getText());
}
}
/**
* 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());
}
/**
* Sets 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);
}
/**
* Sets the given message as message to this editor's status line.
*
* @param msg message to be set
* @since 3.0
*/
protected void setStatusLineMessage(String msg) {
IEditorStatusLine statusLine= (IEditorStatusLine) getAdapter(IEditorStatusLine.class);
if (statusLine != null)
statusLine.setMessage(false, 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;
}
}
/**
* Returns the annotation closest to the given range respecting the given
* direction. If an annotation is found, the annotations current position
* is copied into the provided annotation position.
*
* @param offset the region offset
* @param length the region length
* @param forward <code>true</code> for forwards, <code>false</code> for backward
* @param annotationPosition the position of the found annotation
* @return the found annotation
*/
private Annotation getNextAnnotation(final int offset, final int length, boolean forward, Position annotationPosition) {
Annotation nextAnnotation= null;
Position nextAnnotationPosition= null;
Annotation containingAnnotation= null;
Position containingAnnotationPosition= null;
boolean currentAnnotation= false;
IDocument document= getDocumentProvider().getDocument(getEditorInput());
int endOfDocument= document.getLength();
int distance= Integer.MAX_VALUE;
IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput());
Iterator e= new JavaAnnotationIterator(model, true, true);
while (e.hasNext()) {
Annotation a= (Annotation) e.next();
if ((a instanceof IJavaAnnotation) && ((IJavaAnnotation)a).hasOverlay() || !isNavigationTarget(a))
continue;
Position p= model.getPosition(a);
if (p == null)
continue;
if (forward && p.offset == offset || !forward && p.offset + p.getLength() == offset + length) {// || p.includes(offset)) {
if (containingAnnotation == null || (forward && p.length >= containingAnnotationPosition.length || !forward && p.length >= containingAnnotationPosition.length)) {
containingAnnotation= a;
containingAnnotationPosition= p;
currentAnnotation= p.length == length;
}
} else {
int currentDistance= 0;
if (forward) {
currentDistance= p.getOffset() - offset;
if (currentDistance < 0)
currentDistance= endOfDocument + currentDistance;
if (currentDistance < distance || currentDistance == distance && p.length < nextAnnotationPosition.length) {
distance= currentDistance;
nextAnnotation= a;
nextAnnotationPosition= p;
}
} else {
currentDistance= offset + length - (p.getOffset() + p.length);
if (currentDistance < 0)
currentDistance= endOfDocument + currentDistance;
if (currentDistance < distance || currentDistance == distance && p.length < nextAnnotationPosition.length) {
distance= currentDistance;
nextAnnotation= a;
nextAnnotationPosition= p;
}
}
}
}
if (containingAnnotationPosition != null && (!currentAnnotation || nextAnnotation == null)) {
annotationPosition.setOffset(containingAnnotationPosition.getOffset());
annotationPosition.setLength(containingAnnotationPosition.getLength());
return containingAnnotation;
}
if (nextAnnotationPosition != null) {
annotationPosition.setOffset(nextAnnotationPosition.getOffset());
annotationPosition.setLength(nextAnnotationPosition.getLength());
}
return nextAnnotation;
}
/**
* Returns the annotation overlapping with the given range or <code>null</code>.
*
* @param offset the region offset
* @param length the region length
* @return the found annotation or <code>null</code>
* @since 3.0
*/
private Annotation getAnnotation(int offset, int length) {
IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput());
Iterator e= new JavaAnnotationIterator(model, true, true);
while (e.hasNext()) {
Annotation a= (Annotation) e.next();
if (!isNavigationTarget(a))
continue;
Position p= model.getPosition(a);
if (p != null && p.overlapsWith(offset, length))
return a;
}
return null;
}
/**
* Returns whether the given annotation is configured as a target for the
* "Go to Next/Previous Annotation" actions
*
* @param annotation the annotation
* @return <code>true</code> if this is a target, <code>false</code>
* otherwise
* @since 3.0
*/
private boolean isNavigationTarget(Annotation annotation) {
Preferences preferences= Platform.getPlugin(EditorsUI.PLUGIN_ID).getPluginPreferences();
AnnotationPreference preference= getAnnotationPreferenceLookup().getAnnotationPreference(annotation);
// See bug 41689
// String key= forward ? preference.getIsGoToNextNavigationTargetKey() : preference.getIsGoToPreviousNavigationTargetKey();
String key= preference == null ? null : preference.getIsGoToNextNavigationTargetKey();
return (key != null && preferences.getBoolean(key));
}
/**
* 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);
}
/*
* @see org.eclipse.ui.texteditor.ExtendedTextEditor#createCompositeRuler()
*/
protected CompositeRuler createCompositeRuler() {
if (!getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_ANNOTATION_ROLL_OVER))
return super.createCompositeRuler();
CompositeRuler ruler= new CompositeRuler();
AnnotationRulerColumn column= new AnnotationRulerColumn(VERTICAL_RULER_WIDTH, getAnnotationAccess());
column.setHover(new JavaExpandHover(ruler, ruler, new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
// for now: just invoke ruler double click action
triggerAction(ITextEditorActionConstants.RULER_DOUBLE_CLICK);
}
private void triggerAction(String actionID) {
IAction action= getAction(actionID);
if (action != null) {
if (action instanceof IUpdate)
((IUpdate) action).update();
// hack to propagate line change
if (action instanceof ISelectionListener) {
((ISelectionListener)action).selectionChanged(null, null);
}
if (action.isEnabled())
action.run();
}
}
}, getAnnotationAccess()));
ruler.addDecorator(0, column);
if (isLineNumberRulerVisible())
ruler.addDecorator(1, createLineNumberRulerColumn());
else if (isPrefQuickDiffAlwaysOn())
ruler.addDecorator(1, createChangeRulerColumn());
return ruler;
}
}
|
51,092 |
Bug 51092 [reconciling] JavaMultiPassReconciler removes annotations
|
I20040130 + plug-in export Open a CU which has errors and warnings. Observe: the annotations in overview and annotation ruler are quickly visible and then get removed. This is caused by JavaMultiPassReconciler.
|
verified fixed
|
831623e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-02-03T19:00:30Z | 2004-02-03T09:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/text/JavaSourceViewerConfiguration.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.text;
import java.util.Vector;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.DefaultInformationControl;
import org.eclipse.jface.text.DefaultTextDoubleClickStrategy;
import org.eclipse.jface.text.IAutoIndentStrategy;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IInformationControl;
import org.eclipse.jface.text.IInformationControlCreator;
import org.eclipse.jface.text.ITextDoubleClickStrategy;
import org.eclipse.jface.text.ITextHover;
import org.eclipse.jface.text.ITextViewerExtension2;
import org.eclipse.jface.text.contentassist.ContentAssistant;
import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
import org.eclipse.jface.text.contentassist.IContentAssistant;
import org.eclipse.jface.text.formatter.ContentFormatter2;
import org.eclipse.jface.text.formatter.IContentFormatter;
import org.eclipse.jface.text.formatter.IFormattingStrategy;
import org.eclipse.jface.text.information.IInformationPresenter;
import org.eclipse.jface.text.information.IInformationProvider;
import org.eclipse.jface.text.information.InformationPresenter;
import org.eclipse.jface.text.presentation.IPresentationReconciler;
import org.eclipse.jface.text.presentation.PresentationReconciler;
import org.eclipse.jface.text.reconciler.IReconciler;
import org.eclipse.jface.text.reconciler.IReconcilingStrategy;
import org.eclipse.jface.text.rules.DefaultDamagerRepairer;
import org.eclipse.jface.text.rules.RuleBasedScanner;
import org.eclipse.jface.text.source.IAnnotationHover;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.actions.IJavaEditorActionDefinitionIds;
import org.eclipse.jdt.ui.text.spelling.SpellReconcileStrategy;
import org.eclipse.jdt.ui.text.spelling.WordCompletionProcessor;
import org.eclipse.jdt.internal.corext.util.CodeFormatterUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.ContentAssistPreference;
import org.eclipse.jdt.internal.ui.text.HTMLTextPresenter;
import org.eclipse.jdt.internal.ui.text.IJavaPartitions;
import org.eclipse.jdt.internal.ui.text.JavaAnnotationHover;
import org.eclipse.jdt.internal.ui.text.JavaElementProvider;
import org.eclipse.jdt.internal.ui.text.JavaMultiPassReconciler;
import org.eclipse.jdt.internal.ui.text.JavaOutlineInformationControl;
import org.eclipse.jdt.internal.ui.text.comment.CommentFormattingStrategy;
import org.eclipse.jdt.internal.ui.text.comment.JavaDocRegion;
import org.eclipse.jdt.internal.ui.text.comment.JavaSnippetFormattingStrategy;
import org.eclipse.jdt.internal.ui.text.java.JavaAutoIndentStrategy;
import org.eclipse.jdt.internal.ui.text.java.JavaCompletionProcessor;
import org.eclipse.jdt.internal.ui.text.java.JavaDoubleClickSelector;
import org.eclipse.jdt.internal.ui.text.java.JavaFormattingStrategy;
import org.eclipse.jdt.internal.ui.text.java.JavaReconcilingStrategy;
import org.eclipse.jdt.internal.ui.text.java.JavaStringAutoIndentStrategy;
import org.eclipse.jdt.internal.ui.text.java.JavaStringDoubleClickSelector;
import org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverDescriptor;
import org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy;
import org.eclipse.jdt.internal.ui.text.java.hover.JavaInformationProvider;
import org.eclipse.jdt.internal.ui.text.javadoc.JavaDocAutoIndentStrategy;
import org.eclipse.jdt.internal.ui.text.javadoc.JavaDocCompletionProcessor;
import org.eclipse.jdt.internal.ui.typehierarchy.HierarchyInformationControl;
/**
* Configuration for a source viewer which shows Java code.
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*/
public class JavaSourceViewerConfiguration extends SourceViewerConfiguration {
/**
* Preference key used to look up display tab width.
*
* @since 2.0
*/
public final static String PREFERENCE_TAB_WIDTH= PreferenceConstants.EDITOR_TAB_WIDTH;
/**
* Preference key for inserting spaces rather than tabs.
*
* @since 2.0
*/
public final static String SPACES_FOR_TABS= PreferenceConstants.EDITOR_SPACES_FOR_TABS;
private JavaTextTools fJavaTextTools;
private ITextEditor fTextEditor;
private String fDocumentPartitioning;
/**
* Creates a new Java source viewer configuration for viewers in the given editor
* using the given Java tools and the specified document partitioning.
*
* @param tools the Java text tools to be used
* @param editor the editor in which the configured viewer(s) will reside
* @param partitioning the document partitioning for this configuration
* @see JavaTextTools
* @since 3.0
*/
public JavaSourceViewerConfiguration(JavaTextTools tools, ITextEditor editor, String partitioning) {
fJavaTextTools= tools;
fTextEditor= editor;
fDocumentPartitioning= partitioning;
}
/**
* Creates a new Java source viewer configuration for viewers in the given editor
* using the given Java tools.
*
* @param tools the Java text tools to be used
* @param editor the editor in which the configured viewer(s) will reside
* @see JavaTextTools
*/
public JavaSourceViewerConfiguration(JavaTextTools tools, ITextEditor editor) {
this(tools, editor, null);
}
/**
* Returns the Java source code scanner for this configuration.
*
* @return the Java source code scanner
*/
protected RuleBasedScanner getCodeScanner() {
return fJavaTextTools.getCodeScanner();
}
/**
* Returns the Java multiline comment scanner for this configuration.
*
* @return the Java multiline comment scanner
* @since 2.0
*/
protected RuleBasedScanner getMultilineCommentScanner() {
return fJavaTextTools.getMultilineCommentScanner();
}
/**
* Returns the Java singleline comment scanner for this configuration.
*
* @return the Java singleline comment scanner
* @since 2.0
*/
protected RuleBasedScanner getSinglelineCommentScanner() {
return fJavaTextTools.getSinglelineCommentScanner();
}
/**
* Returns the Java string scanner for this configuration.
*
* @return the Java string scanner
* @since 2.0
*/
protected RuleBasedScanner getStringScanner() {
return fJavaTextTools.getStringScanner();
}
/**
* Returns the JavaDoc scanner for this configuration.
*
* @return the JavaDoc scanner
*/
protected RuleBasedScanner getJavaDocScanner() {
return fJavaTextTools.getJavaDocScanner();
}
/**
* Returns the color manager for this configuration.
*
* @return the color manager
*/
protected IColorManager getColorManager() {
return fJavaTextTools.getColorManager();
}
/**
* Returns the editor in which the configured viewer(s) will reside.
*
* @return the enclosing editor
*/
protected ITextEditor getEditor() {
return fTextEditor;
}
/**
* Returns the preference store used by this configuration to initialize
* the individual bits and pieces.
*
* @return the preference store used to initialize this configuration
*
* @since 2.0
*/
public IPreferenceStore getPreferenceStore() {
return fJavaTextTools.getPreferenceStore();
}
/*
* @see SourceViewerConfiguration#getPresentationReconciler(ISourceViewer)
*/
public IPresentationReconciler getPresentationReconciler(ISourceViewer sourceViewer) {
PresentationReconciler reconciler= new PresentationReconciler();
reconciler.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer));
DefaultDamagerRepairer dr= new DefaultDamagerRepairer(getCodeScanner());
reconciler.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE);
reconciler.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE);
dr= new DefaultDamagerRepairer(getJavaDocScanner());
reconciler.setDamager(dr, IJavaPartitions.JAVA_DOC);
reconciler.setRepairer(dr, IJavaPartitions.JAVA_DOC);
dr= new DefaultDamagerRepairer(getMultilineCommentScanner());
reconciler.setDamager(dr, IJavaPartitions.JAVA_MULTI_LINE_COMMENT);
reconciler.setRepairer(dr, IJavaPartitions.JAVA_MULTI_LINE_COMMENT);
dr= new DefaultDamagerRepairer(getSinglelineCommentScanner());
reconciler.setDamager(dr, IJavaPartitions.JAVA_SINGLE_LINE_COMMENT);
reconciler.setRepairer(dr, IJavaPartitions.JAVA_SINGLE_LINE_COMMENT);
dr= new DefaultDamagerRepairer(getStringScanner());
reconciler.setDamager(dr, IJavaPartitions.JAVA_STRING);
reconciler.setRepairer(dr, IJavaPartitions.JAVA_STRING);
dr= new DefaultDamagerRepairer(getStringScanner());
reconciler.setDamager(dr, IJavaPartitions.JAVA_CHARACTER);
reconciler.setRepairer(dr, IJavaPartitions.JAVA_CHARACTER);
return reconciler;
}
/*
* @see SourceViewerConfiguration#getContentAssistant(ISourceViewer)
*/
public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) {
if (getEditor() != null) {
ContentAssistant assistant= new ContentAssistant();
assistant.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer));
IContentAssistProcessor processor= new JavaCompletionProcessor(getEditor());
assistant.setContentAssistProcessor(processor, 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(processor, IJavaPartitions.JAVA_STRING);
assistant.setContentAssistProcessor(processor, IJavaPartitions.JAVA_SINGLE_LINE_COMMENT);
processor= new WordCompletionProcessor();
assistant.setContentAssistProcessor(processor, IJavaPartitions.JAVA_MULTI_LINE_COMMENT);
assistant.setContentAssistProcessor(processor, IJavaPartitions.JAVA_SINGLE_LINE_COMMENT);
assistant.setContentAssistProcessor(processor, IJavaPartitions.JAVA_STRING);
assistant.setContentAssistProcessor(new JavaDocCompletionProcessor(getEditor()), IJavaPartitions.JAVA_DOC);
ContentAssistPreference.configure(assistant, getPreferenceStore());
assistant.setContextInformationPopupOrientation(ContentAssistant.CONTEXT_INFO_ABOVE);
assistant.setInformationControlCreator(getInformationControlCreator(sourceViewer));
return assistant;
}
return null;
}
/*
* @see SourceViewerConfiguration#getReconciler(ISourceViewer)
*/
public IReconciler getReconciler(ISourceViewer sourceViewer) {
final ITextEditor editor= getEditor();
if (editor != null && editor.isEditable()) {
final JavaMultiPassReconciler reconciler= new JavaMultiPassReconciler(editor);
final IReconcilingStrategy strategy= new SpellReconcileStrategy(editor, getConfiguredDocumentPartitioning(sourceViewer), PreferenceConstants.getPreferenceStore());
reconciler.addReconcilingStrategy(strategy, IJavaPartitions.JAVA_DOC);
reconciler.addReconcilingStrategy(strategy, IJavaPartitions.JAVA_MULTI_LINE_COMMENT);
reconciler.addReconcilingStrategy(strategy, IJavaPartitions.JAVA_SINGLE_LINE_COMMENT);
reconciler.addReconcilingStrategy(new JavaReconcilingStrategy(editor), IDocument.DEFAULT_CONTENT_TYPE);
reconciler.setIsIncrementalReconciler(false);
reconciler.setProgressMonitor(new NullProgressMonitor());
reconciler.setDelay(500);
return reconciler;
}
return null;
}
/*
* @see SourceViewerConfiguration#getAutoIndentStrategy(ISourceViewer, String)
*/
public IAutoIndentStrategy getAutoIndentStrategy(ISourceViewer sourceViewer, String contentType) {
if (IJavaPartitions.JAVA_DOC.equals(contentType) ||
IJavaPartitions.JAVA_MULTI_LINE_COMMENT.equals(contentType))
return new JavaDocAutoIndentStrategy(getConfiguredDocumentPartitioning(sourceViewer));
else if (IJavaPartitions.JAVA_STRING.equals(contentType))
return new JavaStringAutoIndentStrategy(getConfiguredDocumentPartitioning(sourceViewer));
return new JavaAutoIndentStrategy(getConfiguredDocumentPartitioning(sourceViewer));
}
/*
* @see SourceViewerConfiguration#getDoubleClickStrategy(ISourceViewer, String)
*/
public ITextDoubleClickStrategy getDoubleClickStrategy(ISourceViewer sourceViewer, String contentType) {
if (IJavaPartitions.JAVA_DOC.equals(contentType) ||
IJavaPartitions.JAVA_MULTI_LINE_COMMENT.equals(contentType) ||
IJavaPartitions.JAVA_SINGLE_LINE_COMMENT.equals(contentType))
return new DefaultTextDoubleClickStrategy();
else if (IJavaPartitions.JAVA_STRING.equals(contentType) ||
IJavaPartitions.JAVA_CHARACTER.equals(contentType))
return new JavaStringDoubleClickSelector(getConfiguredDocumentPartitioning(sourceViewer));
return new JavaDoubleClickSelector();
}
/*
* @see SourceViewerConfiguration#getDefaultPrefixes(ISourceViewer, String)
* @since 2.0
*/
public String[] getDefaultPrefixes(ISourceViewer sourceViewer, String contentType) {
return new String[] { "//", "" }; //$NON-NLS-1$ //$NON-NLS-2$
}
/*
* @see SourceViewerConfiguration#getIndentPrefixes(ISourceViewer, String)
*/
public String[] getIndentPrefixes(ISourceViewer sourceViewer, String contentType) {
Vector vector= new Vector();
// prefix[0] is either '\t' or ' ' x tabWidth, depending on useSpaces
int tabWidth= CodeFormatterUtil.getTabWidth();
boolean useSpaces= getPreferenceStore().getBoolean(SPACES_FOR_TABS);
for (int i= 0; i <= tabWidth; i++) {
StringBuffer prefix= new StringBuffer();
if (useSpaces) {
for (int j= 0; j + i < tabWidth; j++)
prefix.append(' ');
if (i != 0)
prefix.append('\t');
} else {
for (int j= 0; j < i; j++)
prefix.append(' ');
if (i != tabWidth)
prefix.append('\t');
}
vector.add(prefix.toString());
}
vector.add(""); //$NON-NLS-1$
return (String[]) vector.toArray(new String[vector.size()]);
}
/*
* @see SourceViewerConfiguration#getTabWidth(ISourceViewer)
*/
public int getTabWidth(ISourceViewer sourceViewer) {
return getPreferenceStore().getInt(PREFERENCE_TAB_WIDTH);
}
/*
* @see SourceViewerConfiguration#getAnnotationHover(ISourceViewer)
*/
public IAnnotationHover getAnnotationHover(ISourceViewer sourceViewer) {
return new JavaAnnotationHover(JavaAnnotationHover.VERTICAL_RULER_HOVER);
}
/*
* @see SourceViewerConfiguration#getOverviewRulerAnnotationHover(ISourceViewer)
* @since 3.0
*/
public IAnnotationHover getOverviewRulerAnnotationHover(ISourceViewer sourceViewer) {
return new JavaAnnotationHover(JavaAnnotationHover.OVERVIEW_RULER_HOVER);
}
/*
* @see SourceViewerConfiguration#getConfiguredTextHoverStateMasks(ISourceViewer, String)
* @since 2.1
*/
public int[] getConfiguredTextHoverStateMasks(ISourceViewer sourceViewer, String contentType) {
JavaEditorTextHoverDescriptor[] hoverDescs= JavaPlugin.getDefault().getJavaEditorTextHoverDescriptors();
int stateMasks[]= new int[hoverDescs.length];
int stateMasksLength= 0;
for (int i= 0; i < hoverDescs.length; i++) {
if (hoverDescs[i].isEnabled()) {
int j= 0;
int stateMask= hoverDescs[i].getStateMask();
while (j < stateMasksLength) {
if (stateMasks[j] == stateMask)
break;
j++;
}
if (j == stateMasksLength)
stateMasks[stateMasksLength++]= stateMask;
}
}
if (stateMasksLength == hoverDescs.length)
return stateMasks;
int[] shortenedStateMasks= new int[stateMasksLength];
System.arraycopy(stateMasks, 0, shortenedStateMasks, 0, stateMasksLength);
return shortenedStateMasks;
}
/*
* @see SourceViewerConfiguration#getTextHover(ISourceViewer, String, int)
* @since 2.1
*/
public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType, int stateMask) {
JavaEditorTextHoverDescriptor[] hoverDescs= JavaPlugin.getDefault().getJavaEditorTextHoverDescriptors();
int i= 0;
while (i < hoverDescs.length) {
if (hoverDescs[i].isEnabled() && hoverDescs[i].getStateMask() == stateMask)
return new JavaEditorTextHoverProxy(hoverDescs[i], getEditor());
i++;
}
return null;
}
/*
* @see SourceViewerConfiguration#getTextHover(ISourceViewer, String)
*/
public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType) {
return getTextHover(sourceViewer, contentType, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK);
}
/*
* @see SourceViewerConfiguration#getConfiguredContentTypes(ISourceViewer)
*/
public String[] getConfiguredContentTypes(ISourceViewer sourceViewer) {
return new String[] {
IDocument.DEFAULT_CONTENT_TYPE,
IJavaPartitions.JAVA_DOC,
IJavaPartitions.JAVA_MULTI_LINE_COMMENT,
IJavaPartitions.JAVA_SINGLE_LINE_COMMENT,
IJavaPartitions.JAVA_STRING,
IJavaPartitions.JAVA_CHARACTER
};
}
/*
* @see org.eclipse.jface.text.source.SourceViewerConfiguration#getConfiguredDocumentPartitioning(org.eclipse.jface.text.source.ISourceViewer)
*/
public String getConfiguredDocumentPartitioning(ISourceViewer sourceViewer) {
if (fDocumentPartitioning != null)
return fDocumentPartitioning;
return super.getConfiguredDocumentPartitioning(sourceViewer);
}
/*
* @see SourceViewerConfiguration#getContentFormatter(ISourceViewer)
*/
public IContentFormatter getContentFormatter(ISourceViewer sourceViewer) {
final ContentFormatter2 formatter= new ContentFormatter2();
formatter.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer));
IFormattingStrategy strategy= new JavaFormattingStrategy(sourceViewer);
formatter.setFormattingStrategy(strategy);
formatter.setFormattingStrategy(strategy, IDocument.DEFAULT_CONTENT_TYPE);
formatter.setFormattingStrategy(new CommentFormattingStrategy(formatter, sourceViewer), IJavaPartitions.JAVA_DOC);
formatter.setFormattingStrategy(new CommentFormattingStrategy(formatter, sourceViewer), IJavaPartitions.JAVA_SINGLE_LINE_COMMENT);
formatter.setFormattingStrategy(new CommentFormattingStrategy(formatter, sourceViewer), IJavaPartitions.JAVA_MULTI_LINE_COMMENT);
formatter.setFormattingStrategy(new JavaSnippetFormattingStrategy(sourceViewer), JavaDocRegion.JAVA_SNIPPET_PARTITION);
return formatter;
}
/*
* @see SourceViewerConfiguration#getInformationControlCreator(ISourceViewer)
* @since 2.0
*/
public IInformationControlCreator getInformationControlCreator(ISourceViewer sourceViewer) {
return new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell parent) {
return new DefaultInformationControl(parent, SWT.NONE, new HTMLTextPresenter(true));
}
};
}
/**
* Returns the information presenter control creator. The creator is a factory creating the
* presenter controls for the given source viewer. This implementation always returns a creator
* for <code>DefaultInformationControl</code> instances.
*
* @param sourceViewer the source viewer to be configured by this configuration
* @return an information control creator
* @since 2.1
*/
private IInformationControlCreator getInformationPresenterControlCreator(ISourceViewer sourceViewer) {
return new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell parent) {
int shellStyle= SWT.RESIZE;
int style= SWT.V_SCROLL | SWT.H_SCROLL;
return new DefaultInformationControl(parent, shellStyle, style, new HTMLTextPresenter(false));
// return new HoverBrowserControl(parent);
}
};
}
/**
* Returns the outline presenter control creator. The creator is a factory creating outline
* presenter controls for the given source viewer. This implementation always returns a creator
* for <code>JavaOutlineInformationControl</code> instances.
*
* @param sourceViewer the source viewer to be configured by this configuration
* @return an information control creator
* @since 2.1
*/
private IInformationControlCreator getOutlinePresenterControlCreator(ISourceViewer sourceViewer, final String commandId) {
return new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell parent) {
int shellStyle= SWT.RESIZE;
int treeStyle= SWT.V_SCROLL | SWT.H_SCROLL;
return new JavaOutlineInformationControl(parent, shellStyle, treeStyle, commandId);
}
};
}
private IInformationControlCreator getHierarchyPresenterControlCreator(ISourceViewer sourceViewer) {
return new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell parent) {
int shellStyle= SWT.RESIZE;
int treeStyle= SWT.V_SCROLL | SWT.H_SCROLL;
return new HierarchyInformationControl(parent, shellStyle, treeStyle);
}
};
}
/*
* @see SourceViewerConfiguration#getInformationPresenter(ISourceViewer)
* @since 2.0
*/
public IInformationPresenter getInformationPresenter(ISourceViewer sourceViewer) {
InformationPresenter presenter= new InformationPresenter(getInformationPresenterControlCreator(sourceViewer));
presenter.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer));
IInformationProvider provider= new JavaInformationProvider(getEditor());
presenter.setInformationProvider(provider, IDocument.DEFAULT_CONTENT_TYPE);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_DOC);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_CHARACTER);
presenter.setSizeConstraints(60, 10, true, true);
return presenter;
}
/**
* Returns the outline presenter which will determine and shown
* information requested for the current cursor position.
*
* @param sourceViewer the source viewer to be configured by this configuration
* @param doCodeResolve a boolean which specifies whether code resolve should be used to compute the Java element
* @return an information presenter
* @since 2.1
*/
public IInformationPresenter getOutlinePresenter(ISourceViewer sourceViewer, boolean doCodeResolve) {
InformationPresenter presenter;
if (doCodeResolve)
presenter= new InformationPresenter(getOutlinePresenterControlCreator(sourceViewer, IJavaEditorActionDefinitionIds.OPEN_STRUCTURE));
else
presenter= new InformationPresenter(getOutlinePresenterControlCreator(sourceViewer, IJavaEditorActionDefinitionIds.SHOW_OUTLINE));
presenter.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer));
presenter.setAnchor(InformationPresenter.ANCHOR_GLOBAL);
IInformationProvider provider= new JavaElementProvider(getEditor(), doCodeResolve);
presenter.setInformationProvider(provider, IDocument.DEFAULT_CONTENT_TYPE);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_DOC);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_MULTI_LINE_COMMENT);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_SINGLE_LINE_COMMENT);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_STRING);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_CHARACTER);
presenter.setSizeConstraints(40, 20, true, true);
return presenter;
}
public IInformationPresenter getHierarchyPresenter(ISourceViewer sourceViewer, boolean doCodeResolve) {
InformationPresenter presenter= new InformationPresenter(getHierarchyPresenterControlCreator(sourceViewer));
presenter.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer));
presenter.setAnchor(InformationPresenter.ANCHOR_GLOBAL);
IInformationProvider provider= new JavaElementProvider(getEditor(), doCodeResolve);
presenter.setInformationProvider(provider, IDocument.DEFAULT_CONTENT_TYPE);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_DOC);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_MULTI_LINE_COMMENT);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_SINGLE_LINE_COMMENT);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_STRING);
presenter.setInformationProvider(provider, IJavaPartitions.JAVA_CHARACTER);
presenter.setSizeConstraints(50, 20, true, true);
return presenter;
}
}
|
51,209 |
Bug 51209 Unhandled event loop exception while trying to open a new file
|
i am using: I20040203 Tue, 3 Feb 2004 -- 09:05 (-0500) Version: 3.0.0 Build id: 200402030905 I had the IDE open, and the "work in progress" preference for auto refresh was turned on. I created a new java source file using another text editor (ie from outside Eclipse). After waiting for a few minutes, I used Ctrl+Shift+T to open the new class. The new class did appear in the "open java class dialog", but when I clicked on the OK button, nothing happened.
|
closed fixed
|
7fc1cd0
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-02-05T16:56:20Z | 2004-02-05T03:00:00Z |
org.eclipse.jdt.ui/core
| |
51,209 |
Bug 51209 Unhandled event loop exception while trying to open a new file
|
i am using: I20040203 Tue, 3 Feb 2004 -- 09:05 (-0500) Version: 3.0.0 Build id: 200402030905 I had the IDE open, and the "work in progress" preference for auto refresh was turned on. I created a new java source file using another text editor (ie from outside Eclipse). After waiting for a few minutes, I used Ctrl+Shift+T to open the new class. The new class did appear in the "open java class dialog", but when I clicked on the OK button, nothing happened.
|
closed fixed
|
7fc1cd0
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-02-05T16:56:20Z | 2004-02-05T03:00:00Z |
extension/org/eclipse/jdt/internal/corext/util/IFileTypeInfo.java
| |
51,184 |
Bug 51184 Fonts on Preference Pages
|
Eclipse 3.0 M6. The following preference pages do not inherit their font settings from their parent Composite. Of course, this could be by design, but I doubt it. You can see this by changing the Dialog Font preference (Workspace > Fonts) from the default, 8 points, to something big such as 16 points. Next time you open the preferences you'll see that most other pages respect the Dialog Font setting. The offenders are as follows: Java > Code Formatter - Preview text area. Java > Code Formatter (WIP turned on) - Preview text area. - Dialog that opens after Clicking the "Edit..." button. Java > Editor > Syntax tab - Preview text area. Java > Editor > Templates - Preview text area. Java > Work in Progress - The whole page. There are other preference page offenders in Platform and Team, for which I'll submit individual bug reports.
|
resolved fixed
|
8a176da
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-02-05T17:24:29Z | 2004-02-04T18:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/WorkInProgressPreferencePage.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.preferences;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.texteditor.ExtendedTextEditorPreferenceConstants;
import org.eclipse.ui.texteditor.quickdiff.QuickDiff;
import org.eclipse.ui.texteditor.quickdiff.ReferenceProviderDescriptor;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
/**
* Preference page for work in progress.
*/
public class WorkInProgressPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
/** prefix for resources */
private static final String PREFIX= "WorkInProgress."; //$NON-NLS-1$
public final static String PREF_FORMATTER= "use_new_formatter"; //$NON-NLS-1$
public final static String PREF_BGSEARCH= "search_in_background"; //$NON-NLS-1$
public final static String PREF_SEARCH_MENU= "small_search_menu"; //$NON-NLS-1$
public final static String PREF_SEARCH_IGNORE_IMPORTS= "search_ignore_imports"; //$NON-NLS-1$
private List fCheckBoxes;
private List fRadioButtons;
private List fTextControls;
/** List for the reference provider default. */
private org.eclipse.swt.widgets.List fQuickDiffProviderList;
/** The reference provider default's list model. */
private String[][] fQuickDiffProviderListModel;
/** Button controlling default setting of the selected reference provider. */
private Button fSetDefaultButton;
/**
* creates a new preference page.
*/
public WorkInProgressPreferencePage() {
setPreferenceStore(getPreferenceStore());
fRadioButtons= new ArrayList();
fCheckBoxes= new ArrayList();
fTextControls= new ArrayList();
List providers= new QuickDiff().getReferenceProviderDescriptors();
fQuickDiffProviderListModel= createQuickDiffReferenceListModel(providers);
}
private String[][] createQuickDiffReferenceListModel(List providers) {
ArrayList listModelItems= new ArrayList();
for (Iterator it= providers.iterator(); it.hasNext();) {
ReferenceProviderDescriptor provider= (ReferenceProviderDescriptor) it.next();
String label= provider.getLabel();
int i= label.indexOf('&');
while (i >= 0) {
if (i < label.length())
label= label.substring(0, i) + label.substring(i+1);
else
label.substring(0, i);
i= label.indexOf('&');
}
listModelItems.add(new String[] { provider.getId(), label });
}
String[][] items= new String[listModelItems.size()][];
listModelItems.toArray(items);
return items;
}
private void handleProviderListSelection() {
int i= fQuickDiffProviderList.getSelectionIndex();
boolean b= getPreferenceStore().getString(ExtendedTextEditorPreferenceConstants.QUICK_DIFF_DEFAULT_PROVIDER).equals(fQuickDiffProviderListModel[i][0]);
fSetDefaultButton.setEnabled(!b);
}
private Button addCheckBox(Composite parent, String label, String key) {
GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
Button button= new Button(parent, SWT.CHECK);
button.setText(label);
button.setData(key);
button.setLayoutData(gd);
button.setSelection(getPreferenceStore().getBoolean(key));
fCheckBoxes.add(button);
return button;
}
/*
* @see PreferencePage#createControl(Composite)
*/
public void createControl(Composite parent) {
super.createControl(parent);
WorkbenchHelp.setHelp(getControl(), "WORK_IN_PROGRESS_PREFERENCE_PAGE"); //$NON-NLS-1$
}
protected Control createContents(Composite parent) {
initializeDialogUnits(parent);
Composite result= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
layout.marginHeight= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
layout.marginWidth= 0;
layout.verticalSpacing= convertVerticalDLUsToPixels(10);
layout.horizontalSpacing= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING);
result.setLayout(layout);
Group group= new Group(result, SWT.NONE);
group.setLayout(new GridLayout());
group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
group.setText(PreferencesMessages.getString(PREFIX + "editor")); //$NON-NLS-1$
addCheckBox(group, PreferencesMessages.getString(PREFIX + "rollover"), PreferenceConstants.EDITOR_ANNOTATION_ROLL_OVER); //$NON-NLS-1$
createSpacer(group, 1);
Label label= new Label(group, SWT.NONE);
label.setText(PreferencesMessages.getString(PREFIX + "smartTyping.label")); //$NON-NLS-1$
addCheckBox(group, PreferencesMessages.getString(PREFIX + "smartTyping.smartSemicolon"), PreferenceConstants.EDITOR_SMART_SEMICOLON); //$NON-NLS-1$
addCheckBox(group, PreferencesMessages.getString(PREFIX + "smartTyping.smartOpeningBrace"), PreferenceConstants.EDITOR_SMART_OPENING_BRACE); //$NON-NLS-1$
addCheckBox(group, PreferencesMessages.getString(PREFIX + "smartTyping.smartTab"), PreferenceConstants.EDITOR_SMART_TAB); //$NON-NLS-1$
/* line change bar */
group= new Group(result, SWT.NONE);
group.setLayout(new GridLayout());
group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
group.setText(PreferencesMessages.getString(PREFIX + "quickdiff")); //$NON-NLS-1$
Label l= new Label(group, SWT.LEFT );
GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= 2;
gd.heightHint= convertHeightInCharsToPixels(1) / 2;
l.setLayoutData(gd);
addCheckBox(group, PreferencesMessages.getString(PREFIX + "showQuickDiffPerDefault"), ExtendedTextEditorPreferenceConstants.QUICK_DIFF_ALWAYS_ON); //$NON-NLS-1$
addCheckBox(group, PreferencesMessages.getString(PREFIX + "quickdiff.characterMode"), ExtendedTextEditorPreferenceConstants.QUICK_DIFF_CHARACTER_MODE); //$NON-NLS-1$
l= new Label(group, SWT.LEFT );
gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= 2;
gd.heightHint= convertHeightInCharsToPixels(1) / 2;
l.setLayoutData(gd);
l= new Label(group, SWT.LEFT);
l.setText(PreferencesMessages.getString(PREFIX + "quickdiff.referenceprovidertitle")); //$NON-NLS-1$
gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= 2;
l.setLayoutData(gd);
Composite editorComposite= new Composite(group, SWT.NONE);
layout= new GridLayout();
layout.numColumns= 2;
layout.marginHeight= 0;
layout.marginWidth= 0;
editorComposite.setLayout(layout);
gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.FILL_VERTICAL);
gd.horizontalSpan= 2;
editorComposite.setLayoutData(gd);
fQuickDiffProviderList= new org.eclipse.swt.widgets.List(editorComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER);
gd= new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL);
gd.heightHint= convertHeightInCharsToPixels(4);
fQuickDiffProviderList.setLayoutData(gd);
Composite stylesComposite= new Composite(editorComposite, SWT.NONE);
layout= new GridLayout();
layout.marginHeight= 0;
layout.marginWidth= 0;
layout.numColumns= 2;
stylesComposite.setLayout(layout);
stylesComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
fSetDefaultButton= new Button(stylesComposite, SWT.PUSH);
fSetDefaultButton.setText(PreferencesMessages.getString(PREFIX + "quickdiff.setDefault")); //$NON-NLS-1$
gd= new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalAlignment= GridData.BEGINNING;
gd.horizontalSpan= 2;
fSetDefaultButton.setLayoutData(gd);
fQuickDiffProviderList.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
// do nothing
}
public void widgetSelected(SelectionEvent e) {
handleProviderListSelection();
}
});
fSetDefaultButton.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
// do nothing
}
public void widgetSelected(SelectionEvent e) {
int i= fQuickDiffProviderList.getSelectionIndex();
for (int j= 0; j < fQuickDiffProviderListModel.length; j++) {
if (getPreferenceStore().getString(ExtendedTextEditorPreferenceConstants.QUICK_DIFF_DEFAULT_PROVIDER).equals(fQuickDiffProviderListModel[j][0])) {
fQuickDiffProviderList.remove(j);
fQuickDiffProviderList.add(fQuickDiffProviderListModel[j][1], j);
}
if (i == j) {
fQuickDiffProviderList.remove(j);
fQuickDiffProviderList.add(fQuickDiffProviderListModel[j][1] + " " + PreferencesMessages.getString(PREFIX + "quickdiff.defaultlabel"), j); //$NON-NLS-1$//$NON-NLS-2$
}
}
fSetDefaultButton.setEnabled(false);
fQuickDiffProviderList.setSelection(i);
fQuickDiffProviderList.redraw();
getPreferenceStore().setValue(ExtendedTextEditorPreferenceConstants.QUICK_DIFF_DEFAULT_PROVIDER, fQuickDiffProviderListModel[i][0]);
}
});
for (int i= 0; i < fQuickDiffProviderListModel.length; i++) {
String sLabel= fQuickDiffProviderListModel[i][1];
if (getPreferenceStore().getString(ExtendedTextEditorPreferenceConstants.QUICK_DIFF_DEFAULT_PROVIDER).equals(fQuickDiffProviderListModel[i][0]))
sLabel += " " + PreferencesMessages.getString(PREFIX + "quickdiff.defaultlabel"); //$NON-NLS-1$ //$NON-NLS-2$
fQuickDiffProviderList.add(sLabel);
}
fQuickDiffProviderList.getDisplay().asyncExec(new Runnable() {
public void run() {
if (fQuickDiffProviderList != null && !fQuickDiffProviderList.isDisposed()) {
fQuickDiffProviderList.select(0);
handleProviderListSelection();
}
}
});
group= new Group(result, SWT.NONE);
group.setLayout(new GridLayout());
group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
group.setText(PreferencesMessages.getString(PREFIX + "quickassist.group")); //$NON-NLS-1$
addCheckBox(group, PreferencesMessages.getString(PREFIX + "quickassist.option"), PreferenceConstants.APPEARANCE_QUICKASSIST_LIGHTBULB); //$NON-NLS-1$ //$NON-NLS-2$
group= new Group(result, SWT.NONE);
group.setLayout(new GridLayout());
group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
group.setText(PreferencesMessages.getString(PREFIX + "search")); //$NON-NLS-1$
addCheckBox(group, PreferencesMessages.getString(PREFIX + "search.small_menu"), PREF_SEARCH_MENU); //$NON-NLS-1$
addCheckBox(group, PreferencesMessages.getString(PREFIX+"newsearch.option"), PREF_BGSEARCH); //$NON-NLS-1$
addCheckBox(group, PreferencesMessages.getString(PREFIX+"search.ignore_imports"), PREF_SEARCH_IGNORE_IMPORTS); //$NON-NLS-1$
return result;
}
/*
* @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench)
*/
public void init(IWorkbench workbench) {
}
protected void createSpacer(Composite composite, int columnSpan) {
Label label= new Label(composite, SWT.NONE);
GridData gd= new GridData();
gd.horizontalSpan= columnSpan;
label.setLayoutData(gd);
}
/*
* @see org.eclipse.jface.preference.PreferencePage#doGetPreferenceStore()
*/
protected IPreferenceStore doGetPreferenceStore() {
return JavaPlugin.getDefault().getPreferenceStore();
}
/*
* @see PreferencePage#performDefaults()
*/
protected void performDefaults() {
IPreferenceStore store= getPreferenceStore();
for (int i= 0; i < fCheckBoxes.size(); i++) {
Button button= (Button) fCheckBoxes.get(i);
String key= (String) button.getData();
button.setSelection(store.getDefaultBoolean(key));
}
for (int i= 0; i < fRadioButtons.size(); i++) {
Button button= (Button) fRadioButtons.get(i);
String[] info= (String[]) button.getData();
button.setSelection(info[1].equals(store.getDefaultString(info[0])));
}
for (int i= 0; i < fTextControls.size(); i++) {
Text text= (Text) fTextControls.get(i);
String key= (String) text.getData();
text.setText(store.getDefaultString(key));
}
handleProviderListSelection();
super.performDefaults();
}
/*
* @see IPreferencePage#performOk()
*/
public boolean performOk() {
IPreferenceStore store= getPreferenceStore();
for (int i= 0; i < fCheckBoxes.size(); i++) {
Button button= (Button) fCheckBoxes.get(i);
String key= (String) button.getData();
store.setValue(key, button.getSelection());
}
for (int i= 0; i < fRadioButtons.size(); i++) {
Button button= (Button) fRadioButtons.get(i);
if (button.getSelection()) {
String[] info= (String[]) button.getData();
store.setValue(info[0], info[1]);
}
}
for (int i= 0; i < fTextControls.size(); i++) {
Text text= (Text) fTextControls.get(i);
String key= (String) text.getData();
store.setValue(key, text.getText());
}
JavaPlugin.getDefault().savePluginPreferences();
return super.performOk();
}
/**
* @param store
*/
public static void initDefaults(IPreferenceStore store) {
store.setDefault(PreferenceConstants.EDITOR_SMART_SEMICOLON, false);
store.setDefault(PreferenceConstants.EDITOR_SMART_OPENING_BRACE, false);
store.setDefault(PreferenceConstants.APPEARANCE_QUICKASSIST_LIGHTBULB, false);
store.setDefault(PREF_SEARCH_MENU, true);
store.setDefault(PREF_SEARCH_IGNORE_IMPORTS, false);
}
}
|
50,676 |
Bug 50676 Out of memory during "Use supertype where possible"
| null |
resolved fixed
|
6244a6f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-02-05T18:01:29Z | 2004-01-27T13:26:40Z |
org.eclipse.jdt.ui/core
| |
50,676 |
Bug 50676 Out of memory during "Use supertype where possible"
| null |
resolved fixed
|
6244a6f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-02-05T18:01:29Z | 2004-01-27T13:26:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ChangeTypeRefactoring.java
| |
50,676 |
Bug 50676 Out of memory during "Use supertype where possible"
| null |
resolved fixed
|
6244a6f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-02-05T18:01:29Z | 2004-01-27T13:26:40Z |
org.eclipse.jdt.ui/core
| |
50,676 |
Bug 50676 Out of memory during "Use supertype where possible"
| null |
resolved fixed
|
6244a6f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-02-05T18:01:29Z | 2004-01-27T13:26:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ExtractInterfaceUtil.java
| |
50,676 |
Bug 50676 Out of memory during "Use supertype where possible"
| null |
resolved fixed
|
6244a6f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-02-05T18:01:29Z | 2004-01-27T13:26:40Z |
org.eclipse.jdt.ui/core
| |
50,676 |
Bug 50676 Out of memory during "Use supertype where possible"
| null |
resolved fixed
|
6244a6f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-02-05T18:01:29Z | 2004-01-27T13:26:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/typeconstraints/CompositeOrTypeConstraint.java
| |
50,676 |
Bug 50676 Out of memory during "Use supertype where possible"
| null |
resolved fixed
|
6244a6f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-02-05T18:01:29Z | 2004-01-27T13:26:40Z |
org.eclipse.jdt.ui/core
| |
50,676 |
Bug 50676 Out of memory during "Use supertype where possible"
| null |
resolved fixed
|
6244a6f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-02-05T18:01:29Z | 2004-01-27T13:26:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/typeconstraints/ConstraintVariableFactory.java
| |
50,676 |
Bug 50676 Out of memory during "Use supertype where possible"
| null |
resolved fixed
|
6244a6f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-02-05T18:01:29Z | 2004-01-27T13:26:40Z |
org.eclipse.jdt.ui/core
| |
50,676 |
Bug 50676 Out of memory during "Use supertype where possible"
| null |
resolved fixed
|
6244a6f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-02-05T18:01:29Z | 2004-01-27T13:26:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/typeconstraints/FullConstraintCreator.java
| |
50,676 |
Bug 50676 Out of memory during "Use supertype where possible"
| null |
resolved fixed
|
6244a6f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-02-05T18:01:29Z | 2004-01-27T13:26:40Z |
org.eclipse.jdt.ui/core
| |
50,676 |
Bug 50676 Out of memory during "Use supertype where possible"
| null |
resolved fixed
|
6244a6f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-02-05T18:01:29Z | 2004-01-27T13:26:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/typeconstraints/ITypeConstraintFactory.java
| |
50,676 |
Bug 50676 Out of memory during "Use supertype where possible"
| null |
resolved fixed
|
6244a6f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-02-05T18:01:29Z | 2004-01-27T13:26:40Z |
org.eclipse.jdt.ui/core
| |
50,676 |
Bug 50676 Out of memory during "Use supertype where possible"
| null |
resolved fixed
|
6244a6f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-02-05T18:01:29Z | 2004-01-27T13:26:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/typeconstraints/SimpleTypeConstraint.java
| |
50,676 |
Bug 50676 Out of memory during "Use supertype where possible"
| null |
resolved fixed
|
6244a6f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-02-05T18:01:29Z | 2004-01-27T13:26:40Z |
org.eclipse.jdt.ui/core
| |
50,676 |
Bug 50676 Out of memory during "Use supertype where possible"
| null |
resolved fixed
|
6244a6f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-02-05T18:01:29Z | 2004-01-27T13:26:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/typeconstraints/TypeConstraintFactory.java
| |
38,458 |
Bug 38458 enhance 'remove from classpath' [reorg] [ccp]
|
20030604 No delete offered on external JAR's: It could ask to remove them from the class path
|
resolved fixed
|
d0d275b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-02-05T21:09:50Z | 2003-06-05T08:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/RemoveFromClasspathAction.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.ui.actions;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.actions.ActionMessages;
/**
* Action to remove package fragment roots from the classpath of its parent
* project. Currently, the action is applicable to selections containing
* not-external archives (JAR or zip).
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 2.1
*/
public class RemoveFromClasspathAction extends SelectionDispatchAction {
/**
* Creates a new <code>RemoveFromClasspathAction</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 RemoveFromClasspathAction(IWorkbenchSite site) {
super(site);
setText(ActionMessages.getString("RemoveFromClasspathAction.Remove")); //$NON-NLS-1$
setToolTipText(ActionMessages.getString("RemoveFromClasspathAction.tooltip")); //$NON-NLS-1$
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.REMOVE_FROM_CLASSPATH_ACTION);
}
/* (non-Javadoc)
* Method declared in SelectionDispatchAction
*/
public void selectionChanged(IStructuredSelection selection) {
setEnabled(checkEnabled(selection));
}
private static boolean checkEnabled(IStructuredSelection selection) {
if (selection.isEmpty())
return false;
for (Iterator iter= selection.iterator(); iter.hasNext();) {
if (! canRemove(iter.next()))
return false;
}
return true;
}
/* (non-Javadoc)
* Method declared in SelectionDispatchAction
*/
public void run(final IStructuredSelection selection) {
try {
PlatformUI.getWorkbench().getActiveWorkbenchWindow().run(true, true, new WorkbenchRunnableAdapter(new IWorkspaceRunnable() {
public void run(IProgressMonitor pm) throws CoreException {
try{
IPackageFragmentRoot[] roots= getRootsToRemove(selection);
pm.beginTask(ActionMessages.getString("RemoveFromClasspathAction.Removing"), roots.length); //$NON-NLS-1$
for (int i= 0; i < roots.length; i++) {
int jCoreFlags= IPackageFragmentRoot.NO_RESOURCE_MODIFICATION | IPackageFragmentRoot.ORIGINATING_PROJECT_CLASSPATH;
roots[i].delete(IResource.NONE, jCoreFlags, new SubProgressMonitor(pm, 1));
}
} finally {
pm.done();
}
}
}));
} catch (InvocationTargetException e) {
ExceptionHandler.handle(e, getShell(),
ActionMessages.getString("RemoveFromClasspathAction.exception_dialog_title"), //$NON-NLS-1$
ActionMessages.getString("RemoveFromClasspathAction.Problems_occurred")); //$NON-NLS-1$
} catch (InterruptedException e) {
// canceled
}
}
private static IPackageFragmentRoot[] getRootsToRemove(IStructuredSelection selection){
List result= new ArrayList(selection.size());
for (Iterator iter= selection.iterator(); iter.hasNext();) {
Object element= iter.next();
if (canRemove(element))
result.add(element);
}
return (IPackageFragmentRoot[]) result.toArray(new IPackageFragmentRoot[result.size()]);
}
private static boolean canRemove(Object element){
if (! (element instanceof IPackageFragmentRoot))
return false;
IPackageFragmentRoot root= (IPackageFragmentRoot)element;
if (! root.isArchive())
return false;
if (root.isExternal())
return false;
return true;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.