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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
26,186 |
Bug 26186 Java preference page should use group bpxes instead of labels
|
20021113 The labels on the Radio groups in the JavaPreferencePage will not be read by screen readers. Use Group boxes instead. Also an issue for the Code Generation, New Project and Refactoring Page.
|
resolved fixed
|
702a1e6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-06T18:12:53Z | 2002-11-13T20:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/NewJavaProjectPreferencePage.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
// AW
package org.eclipse.jdt.internal.ui.preferences;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.JavaConventions;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaUIMessages;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.dialogs.StatusUtil;
/*
* The page for defaults for classpath entries in new java projects.
* See PreferenceConstants to access or change these values through public API.
*/
public class NewJavaProjectPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
private static final String SRCBIN_FOLDERS_IN_NEWPROJ= PreferenceConstants.SRCBIN_FOLDERS_IN_NEWPROJ;
private static final String SRCBIN_SRCNAME= PreferenceConstants.SRCBIN_SRCNAME;
private static final String SRCBIN_BINNAME= PreferenceConstants.SRCBIN_BINNAME;
private static final String CLASSPATH_JRELIBRARY_INDEX= PreferenceConstants.NEWPROJECT_JRELIBRARY_INDEX;
private static final String CLASSPATH_JRELIBRARY_LIST= PreferenceConstants.NEWPROJECT_JRELIBRARY_LIST;
/**
* @deprecated Inline to avoid reference to preference page
*/
public static boolean useSrcAndBinFolders() {
return PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.SRCBIN_FOLDERS_IN_NEWPROJ);
}
/**
* @deprecated Inline to avoid reference to preference page
*/
public static String getSourceFolderName() {
return PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.SRCBIN_SRCNAME);
}
/**
* @deprecated Inline to avoid reference to preference page
*/
public static String getOutputLocationName() {
return PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.SRCBIN_BINNAME);
}
public static IClasspathEntry[] getDefaultJRELibrary() {
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
String str= store.getString(CLASSPATH_JRELIBRARY_LIST);
int index= store.getInt(CLASSPATH_JRELIBRARY_INDEX);
StringTokenizer tok= new StringTokenizer(str, ";"); //$NON-NLS-1$
while (tok.hasMoreTokens() && index > 0) {
tok.nextToken();
index--;
}
if (tok.hasMoreTokens()) {
IClasspathEntry[] res= decodeJRELibraryClasspathEntries(tok.nextToken());
if (res.length > 0) {
return res;
}
}
return new IClasspathEntry[] { getJREContainerEntry() };
}
// JRE Entry
public static String decodeJRELibraryDescription(String encoded) {
int end= encoded.indexOf(' ');
if (end != -1) {
return URLDecoder.decode(encoded.substring(0, end));
}
return ""; //$NON-NLS-1$
}
public static IClasspathEntry[] decodeJRELibraryClasspathEntries(String encoded) {
StringTokenizer tok= new StringTokenizer(encoded, " "); //$NON-NLS-1$
ArrayList res= new ArrayList();
while (tok.hasMoreTokens()) {
try {
tok.nextToken(); // desc: ignore
int kind= Integer.parseInt(tok.nextToken());
IPath path= decodePath(tok.nextToken());
IPath attachPath= decodePath(tok.nextToken());
IPath attachRoot= decodePath(tok.nextToken());
boolean isExported= Boolean.valueOf(tok.nextToken()).booleanValue();
switch (kind) {
case IClasspathEntry.CPE_SOURCE:
res.add(JavaCore.newSourceEntry(path));
break;
case IClasspathEntry.CPE_LIBRARY:
res.add(JavaCore.newLibraryEntry(path, attachPath, attachRoot, isExported));
break;
case IClasspathEntry.CPE_VARIABLE:
res.add(JavaCore.newVariableEntry(path, attachPath, attachRoot, isExported));
break;
case IClasspathEntry.CPE_PROJECT:
res.add(JavaCore.newProjectEntry(path, isExported));
break;
case IClasspathEntry.CPE_CONTAINER:
res.add(JavaCore.newContainerEntry(path, isExported));
break;
}
} catch (NumberFormatException e) {
String message= JavaUIMessages.getString("NewJavaProjectPreferencePage.error.decode"); //$NON-NLS-1$
JavaPlugin.log(new Status(Status.ERROR, JavaUI.ID_PLUGIN, Status.ERROR, message, e));
} catch (NoSuchElementException e) {
String message= JavaUIMessages.getString("NewJavaProjectPreferencePage.error.decode"); //$NON-NLS-1$
JavaPlugin.log(new Status(Status.ERROR, JavaUI.ID_PLUGIN, Status.ERROR, message, e));
}
}
return (IClasspathEntry[]) res.toArray(new IClasspathEntry[res.size()]);
}
public static String encodeJRELibrary(String desc, IClasspathEntry[] cpentries) {
StringBuffer buf= new StringBuffer();
for (int i= 0; i < cpentries.length; i++) {
IClasspathEntry entry= cpentries[i];
buf.append(URLEncoder.encode(desc));
buf.append(' ');
buf.append(entry.getEntryKind());
buf.append(' ');
buf.append(encodePath(entry.getPath()));
buf.append(' ');
buf.append(encodePath(entry.getSourceAttachmentPath()));
buf.append(' ');
buf.append(encodePath(entry.getSourceAttachmentRootPath()));
buf.append(' ');
buf.append(entry.isExported());
buf.append(' ');
}
return buf.toString();
}
private static String encodePath(IPath path) {
if (path == null) {
return "#"; //$NON-NLS-1$
} else if (path.isEmpty()) {
return "&"; //$NON-NLS-1$
} else {
return URLEncoder.encode(path.toString());
}
}
private static IPath decodePath(String str) {
if ("#".equals(str)) { //$NON-NLS-1$
return null;
} else if ("&".equals(str)) { //$NON-NLS-1$
return Path.EMPTY;
} else {
return new Path(URLDecoder.decode(str));
}
}
private ArrayList fCheckBoxes;
private ArrayList fRadioButtons;
private ArrayList fTextControls;
private SelectionListener fSelectionListener;
private ModifyListener fModifyListener;
private Text fBinFolderNameText;
private Text fSrcFolderNameText;
private Combo fJRECombo;
private Button fProjectAsSourceFolder;
private Button fFoldersAsSourceFolder;
private Label fSrcFolderNameLabel;
private Label fBinFolderNameLabel;
public NewJavaProjectPreferencePage() {
super();
setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore());
setDescription(JavaUIMessages.getString("NewJavaProjectPreferencePage.description")); //$NON-NLS-1$
fRadioButtons= new ArrayList();
fCheckBoxes= new ArrayList();
fTextControls= new ArrayList();
fSelectionListener= new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {}
public void widgetSelected(SelectionEvent e) {
controlChanged(e.widget);
}
};
fModifyListener= new ModifyListener() {
public void modifyText(ModifyEvent e) {
controlModified(e.widget);
}
};
}
public static void initDefaults(IPreferenceStore store) {
store.setDefault(SRCBIN_FOLDERS_IN_NEWPROJ, false);
store.setDefault(SRCBIN_SRCNAME, "src"); //$NON-NLS-1$
store.setDefault(SRCBIN_BINNAME, "bin"); //$NON-NLS-1$
store.setDefault(CLASSPATH_JRELIBRARY_LIST, getDefaultJRELibraries());
store.setDefault(CLASSPATH_JRELIBRARY_INDEX, 0); //$NON-NLS-1$
}
private static String getDefaultJRELibraries() {
StringBuffer buf= new StringBuffer();
IClasspathEntry cntentry= getJREContainerEntry();
buf.append(encodeJRELibrary(JavaUIMessages.getString("NewJavaProjectPreferencePage.jre_container.description"), new IClasspathEntry[] { cntentry} )); //$NON-NLS-1$
buf.append(';');
IClasspathEntry varentry= getJREVariableEntry();
buf.append(encodeJRELibrary(JavaUIMessages.getString("NewJavaProjectPreferencePage.jre_variable.description"), new IClasspathEntry[] { varentry })); //$NON-NLS-1$
buf.append(';');
return buf.toString();
}
private static IClasspathEntry getJREContainerEntry() {
return JavaCore.newContainerEntry(new Path("org.eclipse.jdt.launching.JRE_CONTAINER"));
}
private static IClasspathEntry getJREVariableEntry() {
return JavaCore.newVariableEntry(new Path("JRE_LIB"), new Path("JRE_SRC"), new Path("JRE_SRCROOT"));
}
/*
* @see IWorkbenchPreferencePage#init(IWorkbench)
*/
public void init(IWorkbench workbench) {
}
/**
* @see PreferencePage#createControl(Composite)
*/
public void createControl(Composite parent) {
super.createControl(parent);
WorkbenchHelp.setHelp(getControl(), IJavaHelpContextIds.NEW_JAVA_PROJECT_PREFERENCE_PAGE);
}
private Button addRadioButton(Composite parent, String label, String key, String value, int indent) {
GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= 2;
gd.horizontalIndent= indent;
Button button= new Button(parent, SWT.RADIO);
button.setText(label);
button.setData(new String[] { key, value });
button.setLayoutData(gd);
button.setSelection(value.equals(getPreferenceStore().getString(key)));
fRadioButtons.add(button);
return button;
}
private Text addTextControl(Composite parent, Label labelControl, String key, int indent) {
GridData gd= new GridData();
gd.horizontalIndent= indent;
labelControl.setLayoutData(gd);
gd= new GridData();
gd.widthHint= convertWidthInCharsToPixels(40);
Text text= new Text(parent, SWT.SINGLE | SWT.BORDER);
text.setText(getPreferenceStore().getString(key));
text.setData(key);
text.setLayoutData(gd);
fTextControls.add(text);
return text;
}
protected Control createContents(Composite parent) {
initializeDialogUnits(parent);
Composite composite= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
layout.marginHeight= 0;
layout.numColumns= 2;
layout.marginWidth= 0;
composite.setLayout(layout);
GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= 2;
Label label= new Label(composite, SWT.WRAP);
label.setText(JavaUIMessages.getString("NewJavaProjectPreferencePage.sourcefolder.label")); //$NON-NLS-1$
label.setLayoutData(gd);
int indent= convertWidthInCharsToPixels(1);
fProjectAsSourceFolder= addRadioButton(composite, JavaUIMessages.getString("NewJavaProjectPreferencePage.sourcefolder.project"), SRCBIN_FOLDERS_IN_NEWPROJ, IPreferenceStore.FALSE, indent); //$NON-NLS-1$
fProjectAsSourceFolder.addSelectionListener(fSelectionListener);
fFoldersAsSourceFolder= addRadioButton(composite, JavaUIMessages.getString("NewJavaProjectPreferencePage.sourcefolder.folder"), SRCBIN_FOLDERS_IN_NEWPROJ, IPreferenceStore.TRUE, indent); //$NON-NLS-1$
fFoldersAsSourceFolder.addSelectionListener(fSelectionListener);
indent= convertWidthInCharsToPixels(4);
fSrcFolderNameLabel= new Label(composite, SWT.NONE);
fSrcFolderNameLabel.setText(JavaUIMessages.getString("NewJavaProjectPreferencePage.folders.src")); //$NON-NLS-1$
fSrcFolderNameText= addTextControl(composite, fSrcFolderNameLabel, SRCBIN_SRCNAME, indent); //$NON-NLS-1$
fSrcFolderNameText.addModifyListener(fModifyListener);
fBinFolderNameLabel= new Label(composite, SWT.NONE);
fBinFolderNameLabel.setText(JavaUIMessages.getString("NewJavaProjectPreferencePage.folders.bin")); //$NON-NLS-1$
fBinFolderNameText= addTextControl(composite, fBinFolderNameLabel, SRCBIN_BINNAME, indent); //$NON-NLS-1$
fBinFolderNameText.addModifyListener(fModifyListener);
new Label(composite, SWT.NONE);
new Label(composite, SWT.NONE);
String[] jreNames= getJRENames();
if (jreNames.length > 0) {
Label jreSelectionLabel= new Label(composite, SWT.NONE);
jreSelectionLabel.setText(JavaUIMessages.getString("NewJavaProjectPreferencePage.jrelibrary.label")); //$NON-NLS-1$
jreSelectionLabel.setLayoutData(new GridData());
int index= getPreferenceStore().getInt(CLASSPATH_JRELIBRARY_INDEX);
fJRECombo= new Combo(composite, SWT.READ_ONLY);
fJRECombo.setItems(jreNames);
fJRECombo.select(index);
fJRECombo.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
}
validateFolders();
return composite;
}
private void validateFolders() {
boolean useFolders= fFoldersAsSourceFolder.getSelection();
fSrcFolderNameText.setEnabled(useFolders);
fBinFolderNameText.setEnabled(useFolders);
fSrcFolderNameLabel.setEnabled(useFolders);
fBinFolderNameLabel.setEnabled(useFolders);
if (useFolders) {
String srcName= fSrcFolderNameText.getText();
String binName= fBinFolderNameText.getText();
if (srcName.length() + binName.length() == 0) {
updateStatus(new StatusInfo(IStatus.ERROR, JavaUIMessages.getString("NewJavaProjectPreferencePage.folders.error.namesempty"))); //$NON-NLS-1$
return;
}
IWorkspace workspace= JavaPlugin.getWorkspace();
IStatus status;
if (srcName.length() != 0) {
status= workspace.validateName(srcName, IResource.FOLDER);
if (!status.isOK()) {
String message= JavaUIMessages.getFormattedString("NewJavaProjectPreferencePage.folders.error.invalidsrcname", status.getMessage()); //$NON-NLS-1$
updateStatus(new StatusInfo(IStatus.ERROR, message));
return;
}
}
status= workspace.validateName(binName, IResource.FOLDER);
if (!status.isOK()) {
String message= JavaUIMessages.getFormattedString("NewJavaProjectPreferencePage.folders.error.invalidbinname", status.getMessage()); //$NON-NLS-1$
updateStatus(new StatusInfo(IStatus.ERROR, message));
return;
}
IProject dmy= workspace.getRoot().getProject("dmy"); //$NON-NLS-1$
IClasspathEntry entry= JavaCore.newSourceEntry(dmy.getFullPath().append(srcName));
IPath outputLocation= dmy.getFullPath().append(binName);
status= JavaConventions.validateClasspath(JavaCore.create(dmy), new IClasspathEntry[] { entry }, outputLocation);
if (!status.isOK()) {
updateStatus(status);
return;
}
}
updateStatus(new StatusInfo()); // set to OK
}
private void updateStatus(IStatus status) {
setValid(!status.matches(IStatus.ERROR));
StatusUtil.applyToStatusLine(this, status);
}
private void controlChanged(Widget widget) {
if (widget == fFoldersAsSourceFolder || widget == fProjectAsSourceFolder) {
validateFolders();
}
}
private void controlModified(Widget widget) {
if (widget == fSrcFolderNameText || widget == fBinFolderNameText) {
validateFolders();
}
}
/*
* @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));
}
if (fJRECombo != null) {
fJRECombo.select(store.getDefaultInt(CLASSPATH_JRELIBRARY_INDEX));
}
validateFolders();
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());
}
if (fJRECombo != null) {
store.setValue(CLASSPATH_JRELIBRARY_INDEX, fJRECombo.getSelectionIndex());
}
JavaPlugin.getDefault().savePluginPreferences();
return super.performOk();
}
private String[] getJRENames() {
String prefString= getPreferenceStore().getString(CLASSPATH_JRELIBRARY_LIST);
ArrayList list= new ArrayList();
StringTokenizer tok= new StringTokenizer(prefString, ";"); //$NON-NLS-1$
while (tok.hasMoreTokens()) {
list.add(decodeJRELibraryDescription(tok.nextToken()));
}
return (String[]) list.toArray(new String[list.size()]);
}
}
|
27,801 |
Bug 27801 Change the way external JARs are presented in Package Explorer
|
External JARs are currently presented in Package Explorer using their full path. This causes a problem in cases where this path is long (e.g. self- hosting). With the standard view widths, the most important part of the path (library name) is clipped and users have to scroll or move the mouse over to see the tool tip. It would be much better if the name is split into two parts: <library name> - <library location> For example: Instead of d:\eclipse1204\eclipse\plugins\org.eclipse.core.resources_2.1.0\resources.jar use resources.jar - d:\eclipse1204\eclipse\plugins\org.eclipse.core.resources_2.1.0 This way, label will still be clipped, but the library name will be readily visible. This should be a trivial change since it only affects label provider.
|
resolved fixed
|
b4c4551
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-07T12:47:45Z | 2002-12-05T20:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/viewsupport/JavaElementLabels.java
|
package org.eclipse.jdt.internal.ui.viewsupport;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.ui.model.IWorkbenchAdapter;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IInitializer;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
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;
public class JavaElementLabels {
/**
* Method names contain parameter types.
* e.g. <code>foo(int)</code>
*/
public final static int M_PARAMETER_TYPES= 1 << 0;
/**
* Method names contain parameter names.
* e.g. <code>foo(index)</code>
*/
public final static int M_PARAMETER_NAMES= 1 << 1;
/**
* Method names contain thrown exceptions.
* e.g. <code>foo throws IOException</code>
*/
public final static int M_EXCEPTIONS= 1 << 2;
/**
* Method names contain return type (appended)
* e.g. <code>foo : int</code>
*/
public final static int M_APP_RETURNTYPE= 1 << 3;
/**
* Method names contain return type (appended)
* e.g. <code>int foo</code>
*/
public final static int M_PRE_RETURNTYPE= 1 << 4;
/**
* Method names are fully qualified.
* e.g. <code>java.util.Vector.size</code>
*/
public final static int M_FULLY_QUALIFIED= 1 << 5;
/**
* Method names are post qualified.
* e.g. <code>size - java.util.Vector</code>
*/
public final static int M_POST_QUALIFIED= 1 << 6;
/**
* Initializer names are fully qualified.
* e.g. <code>java.util.Vector.{ ... }</code>
*/
public final static int I_FULLY_QUALIFIED= 1 << 7;
/**
* Type names are post qualified.
* e.g. <code>{ ... } - java.util.Map</code>
*/
public final static int I_POST_QUALIFIED= 1 << 8;
/**
* Field names contain the declared type (appended)
* e.g. <code>int fHello</code>
*/
public final static int F_APP_TYPE_SIGNATURE= 1 << 9;
/**
* Field names contain the declared type (prepended)
* e.g. <code>fHello : int</code>
*/
public final static int F_PRE_TYPE_SIGNATURE= 1 << 10;
/**
* Fields names are fully qualified.
* e.g. <code>java.lang.System.out</code>
*/
public final static int F_FULLY_QUALIFIED= 1 << 11;
/**
* Fields names are post qualified.
* e.g. <code>out - java.lang.System</code>
*/
public final static int F_POST_QUALIFIED= 1 << 12;
/**
* Type names are fully qualified.
* e.g. <code>java.util.Map.MapEntry</code>
*/
public final static int T_FULLY_QUALIFIED= 1 << 13;
/**
* Type names are type container qualified.
* e.g. <code>Map.MapEntry</code>
*/
public final static int T_CONTAINER_QUALIFIED= 1 << 14;
/**
* Type names are post qualified.
* e.g. <code>MapEntry - java.util.Map</code>
*/
public final static int T_POST_QUALIFIED= 1 << 15;
/**
* Declarations (import container / declarartion, package declarartion) are qualified.
* e.g. <code>java.util.Vector.class/import container</code>
*/
public final static int D_QUALIFIED= 1 << 16;
/**
* Declarations (import container / declarartion, package declarartion) are post qualified.
* e.g. <code>import container - java.util.Vector.class</code>
*/
public final static int D_POST_QUALIFIED= 1 << 17;
/**
* Class file names are fully qualified.
* e.g. <code>java.util.Vector.class</code>
*/
public final static int CF_QUALIFIED= 1 << 18;
/**
* Class file names are post qualified.
* e.g. <code>Vector.class - java.util</code>
*/
public final static int CF_POST_QUALIFIED= 1 << 19;
/**
* Compilation unit names are fully qualified.
* e.g. <code>java.util.Vector.java</code>
*/
public final static int CU_QUALIFIED= 1 << 20;
/**
* Compilation unit names are post qualified.
* e.g. <code>Vector.java - java.util</code>
*/
public final static int CU_POST_QUALIFIED= 1 << 21;
/**
* Package names are qualified.
* e.g. <code>MyProject/src/java.util</code>
*/
public final static int P_QUALIFIED= 1 << 22;
/**
* Package names are post qualified.
* e.g. <code>java.util - MyProject/src</code>
*/
public final static int P_POST_QUALIFIED= 1 << 23;
/**
* Package Fragment Roots contain variable name if from a variable.
* e.g. <code>JRE_LIB - c:\java\lib\rt.jar</code>
*/
public final static int ROOT_VARIABLE= 1 << 24;
/**
* Package Fragment Roots contain the project name if not an archive (prepended).
* e.g. <code>MyProject/src</code>
*/
public final static int ROOT_QUALIFIED= 1 << 25;
/**
* Package Fragment Roots contain the project name if not an archive (appended).
* e.g. <code>src - MyProject</code>
*/
public final static int ROOT_POST_QUALIFIED= 1 << 26;
/**
* Add root path to all elements except Package Fragment Roots and Java projects.
* e.g. <code>java.lang.Vector - c:\java\lib\rt.jar</code>
* Option only applies to getElementLabel
*/
public final static int APPEND_ROOT_PATH= 1 << 27;
/**
* Add root path to all elements except Package Fragment Roots and Java projects.
* e.g. <code>java.lang.Vector - c:\java\lib\rt.jar</code>
* Option only applies to getElementLabel
*/
public final static int PREPEND_ROOT_PATH= 1 << 28;
/**
* Package names are compressed.
* e.g. <code>o*.e*.search</code>
*/
public final static int P_COMPRESSED= 1 << 29;
/**
* Qualify all elements
*/
public final static int ALL_FULLY_QUALIFIED= F_FULLY_QUALIFIED | M_FULLY_QUALIFIED | I_FULLY_QUALIFIED | T_FULLY_QUALIFIED | D_QUALIFIED | CF_QUALIFIED | CU_QUALIFIED | P_QUALIFIED | ROOT_QUALIFIED;
/**
* Post qualify all elements
*/
public final static int ALL_POST_QUALIFIED= F_POST_QUALIFIED | M_POST_QUALIFIED | I_POST_QUALIFIED | T_POST_QUALIFIED | D_POST_QUALIFIED | CF_POST_QUALIFIED | CU_POST_QUALIFIED | P_POST_QUALIFIED | ROOT_POST_QUALIFIED;
/**
* Default options (M_PARAMETER_TYPES enabled)
*/
public final static int ALL_DEFAULT= M_PARAMETER_TYPES;
/**
* Default qualify options (All except Root and Package)
*/
public final static int DEFAULT_QUALIFIED= F_FULLY_QUALIFIED | M_FULLY_QUALIFIED | I_FULLY_QUALIFIED | T_FULLY_QUALIFIED | D_QUALIFIED | CF_QUALIFIED | CU_QUALIFIED;
/**
* Default post qualify options (All except Root and Package)
*/
public final static int DEFAULT_POST_QUALIFIED= F_POST_QUALIFIED | M_POST_QUALIFIED | I_POST_QUALIFIED | T_POST_QUALIFIED | D_POST_QUALIFIED | CF_POST_QUALIFIED | CU_POST_QUALIFIED;
public final static String CONCAT_STRING= JavaUIMessages.getString("JavaElementLabels.concat_string"); // " - "; //$NON-NLS-1$
public final static String COMMA_STRING= JavaUIMessages.getString("JavaElementLabels.comma_string"); // ", "; //$NON-NLS-1$
public final static String DECL_STRING= JavaUIMessages.getString("JavaElementLabels.declseparator_string"); // " "; // use for return type //$NON-NLS-1$
/*
* Package name compression
*/
private static String fgPkgNamePattern= ""; //$NON-NLS-1$
private static String fgPkgNamePrefix;
private static String fgPkgNamePostfix;
private static int fgPkgNameChars;
private static int fgPkgNameLength;
private JavaElementLabels() {
}
private static boolean getFlag(int flags, int flag) {
return (flags & flag) != 0;
}
public static String getTextLabel(Object obj, int flags) {
if (obj instanceof IJavaElement) {
return getElementLabel((IJavaElement) obj, flags);
} else if (obj instanceof IAdaptable) {
IWorkbenchAdapter wbadapter= (IWorkbenchAdapter) ((IAdaptable)obj).getAdapter(IWorkbenchAdapter.class);
if (wbadapter != null) {
return wbadapter.getLabel(obj);
}
}
return ""; //$NON-NLS-1$
}
/**
* Returns the label for a Java element. Flags as defined above.
*/
public static String getElementLabel(IJavaElement element, int flags) {
StringBuffer buf= new StringBuffer(60);
getElementLabel(element, flags, buf);
return buf.toString();
}
/**
* Returns the label for a Java element. Flags as defined above.
*/
public static void getElementLabel(IJavaElement element, int flags, StringBuffer buf) {
int type= element.getElementType();
IPackageFragmentRoot root= null;
if (type != IJavaElement.JAVA_MODEL && type != IJavaElement.JAVA_PROJECT && type != IJavaElement.PACKAGE_FRAGMENT_ROOT)
root= JavaModelUtil.getPackageFragmentRoot(element);
if (root != null && getFlag(flags, PREPEND_ROOT_PATH)) {
getPackageFragmentRootLabel(root, ROOT_QUALIFIED, buf);
buf.append(CONCAT_STRING);
}
switch (type) {
case IJavaElement.METHOD:
getMethodLabel((IMethod) element, flags, buf);
break;
case IJavaElement.FIELD:
getFieldLabel((IField) element, flags, buf);
break;
case IJavaElement.INITIALIZER:
getInitializerLabel((IInitializer) element, flags, buf);
break;
case IJavaElement.TYPE:
getTypeLabel((IType) element, flags, buf);
break;
case IJavaElement.CLASS_FILE:
getClassFileLabel((IClassFile) element, flags, buf);
break;
case IJavaElement.COMPILATION_UNIT:
getCompilationUnitLabel((ICompilationUnit) element, flags, buf);
break;
case IJavaElement.PACKAGE_FRAGMENT:
getPackageFragmentLabel((IPackageFragment) element, flags, buf);
break;
case IJavaElement.PACKAGE_FRAGMENT_ROOT:
getPackageFragmentRootLabel((IPackageFragmentRoot) element, flags, buf);
break;
case IJavaElement.IMPORT_CONTAINER:
case IJavaElement.IMPORT_DECLARATION:
case IJavaElement.PACKAGE_DECLARATION:
getDeclararionLabel(element, flags, buf);
break;
case IJavaElement.JAVA_PROJECT:
case IJavaElement.JAVA_MODEL:
buf.append(element.getElementName());
break;
default:
buf.append(element.getElementName());
}
if (root != null && getFlag(flags, APPEND_ROOT_PATH)) {
buf.append(CONCAT_STRING);
getPackageFragmentRootLabel(root, ROOT_QUALIFIED, buf);
}
}
/**
* Appends the label for a method to a StringBuffer. Considers the M_* flags.
*/
public static void getMethodLabel(IMethod method, int flags, StringBuffer buf) {
try {
// return type
if (getFlag(flags, M_PRE_RETURNTYPE) && method.exists() && !method.isConstructor()) {
buf.append(Signature.getSimpleName(Signature.toString(method.getReturnType())));
buf.append(' ');
}
// qualification
if (getFlag(flags, M_FULLY_QUALIFIED)) {
getTypeLabel(method.getDeclaringType(), T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf);
buf.append('.');
}
buf.append(method.getElementName());
// parameters
if (getFlag(flags, M_PARAMETER_TYPES | M_PARAMETER_NAMES)) {
buf.append('(');
String[] types= getFlag(flags, M_PARAMETER_TYPES) ? method.getParameterTypes() : null;
String[] names= (getFlag(flags, M_PARAMETER_NAMES) && method.exists()) ? method.getParameterNames() : null;
int nParams= types != null ? types.length : names.length;
for (int i= 0; i < nParams; i++) {
if (i > 0) {
buf.append(COMMA_STRING); //$NON-NLS-1$
}
if (types != null) {
buf.append(Signature.getSimpleName(Signature.toString(types[i])));
}
if (names != null) {
if (types != null) {
buf.append(' ');
}
buf.append(names[i]);
}
}
buf.append(')');
}
if (getFlag(flags, M_EXCEPTIONS) && method.exists()) {
String[] types= method.getExceptionTypes();
if (types.length > 0) {
buf.append(" throws "); //$NON-NLS-1$
for (int i= 0; i < types.length; i++) {
if (i > 0) {
buf.append(COMMA_STRING);
}
buf.append(Signature.getSimpleName(Signature.toString(types[i])));
}
}
}
if (getFlag(flags, M_APP_RETURNTYPE) && method.exists() && !method.isConstructor()) {
buf.append(DECL_STRING);
buf.append(Signature.getSimpleName(Signature.toString(method.getReturnType())));
}
// post qualification
if (getFlag(flags, M_POST_QUALIFIED)) {
buf.append(CONCAT_STRING);
getTypeLabel(method.getDeclaringType(), T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf);
}
} catch (JavaModelException e) {
JavaPlugin.log(e); // NotExistsException will not reach this point
}
}
/**
* Appends the label for a field to a StringBuffer. Considers the F_* flags.
*/
public static void getFieldLabel(IField field, int flags, StringBuffer buf) {
try {
if (getFlag(flags, F_PRE_TYPE_SIGNATURE) && field.exists()) {
buf.append(Signature.toString(field.getTypeSignature()));
buf.append(' ');
}
// qualification
if (getFlag(flags, F_FULLY_QUALIFIED)) {
getTypeLabel(field.getDeclaringType(), T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf);
buf.append('.');
}
buf.append(field.getElementName());
if (getFlag(flags, F_APP_TYPE_SIGNATURE) && field.exists()) {
buf.append(DECL_STRING);
buf.append(Signature.toString(field.getTypeSignature()));
}
// post qualification
if (getFlag(flags, F_POST_QUALIFIED)) {
buf.append(CONCAT_STRING);
getTypeLabel(field.getDeclaringType(), T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf);
}
} catch (JavaModelException e) {
JavaPlugin.log(e); // NotExistsException will not reach this point
}
}
/**
* Appends the label for a initializer to a StringBuffer. Considers the I_* flags.
*/
public static void getInitializerLabel(IInitializer initializer, int flags, StringBuffer buf) {
// qualification
if (getFlag(flags, I_FULLY_QUALIFIED)) {
getTypeLabel(initializer.getDeclaringType(), T_FULLY_QUALIFIED | (flags ^ P_COMPRESSED), buf);
buf.append('.');
}
buf.append(JavaUIMessages.getString("JavaElementLabels.initializer")); //$NON-NLS-1$
// post qualification
if (getFlag(flags, I_POST_QUALIFIED)) {
buf.append(CONCAT_STRING);
getTypeLabel(initializer.getDeclaringType(), T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf);
}
}
/**
* Appends the label for a type to a StringBuffer. Considers the T_* flags.
*/
public static void getTypeLabel(IType type, int flags, StringBuffer buf) {
if (getFlag(flags, T_FULLY_QUALIFIED)) {
IPackageFragment pack= type.getPackageFragment();
if (!pack.isDefaultPackage()) {
getPackageFragmentLabel(pack, (flags & P_COMPRESSED), buf);
buf.append('.');
}
buf.append(JavaModelUtil.getTypeQualifiedName(type));
} else if (getFlag(flags, T_CONTAINER_QUALIFIED)) {
buf.append(JavaModelUtil.getTypeQualifiedName(type));
} else {
buf.append(type.getElementName());
}
// post qualification
if (getFlag(flags, T_POST_QUALIFIED)) {
buf.append(CONCAT_STRING);
IType declaringType= type.getDeclaringType();
if (declaringType != null) {
getTypeLabel(declaringType, T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf);
} else {
getPackageFragmentLabel(type.getPackageFragment(), (flags & P_COMPRESSED), buf);
}
}
}
/**
* Appends the label for a declaration to a StringBuffer. Considers the D_* flags.
*/
public static void getDeclararionLabel(IJavaElement declaration, int flags, StringBuffer buf) {
if (getFlag(flags, D_QUALIFIED)) {
IJavaElement openable= (IJavaElement) declaration.getOpenable();
if (openable != null) {
buf.append(getElementLabel(openable, CF_QUALIFIED | CU_QUALIFIED));
buf.append('/');
}
}
if (declaration.getElementType() == IJavaElement.IMPORT_CONTAINER) {
buf.append(JavaUIMessages.getString("JavaElementLabels.import_container")); //$NON-NLS-1$
} else {
buf.append(declaration.getElementName());
}
// post qualification
if (getFlag(flags, D_POST_QUALIFIED)) {
IJavaElement openable= (IJavaElement) declaration.getOpenable();
if (openable != null) {
buf.append(CONCAT_STRING);
buf.append(getElementLabel(openable, CF_QUALIFIED | CU_QUALIFIED));
}
}
}
/**
* Appends the label for a class file to a StringBuffer. Considers the CF_* flags.
*/
public static void getClassFileLabel(IClassFile classFile, int flags, StringBuffer buf) {
if (getFlag(flags, CF_QUALIFIED)) {
IPackageFragment pack= (IPackageFragment) classFile.getParent();
if (!pack.isDefaultPackage()) {
buf.append(pack.getElementName());
buf.append('.');
}
}
buf.append(classFile.getElementName());
if (getFlag(flags, CF_POST_QUALIFIED)) {
buf.append(CONCAT_STRING);
getPackageFragmentLabel((IPackageFragment) classFile.getParent(), 0, buf);
}
}
/**
* Appends the label for a compilation unit to a StringBuffer. Considers the CU_* flags.
*/
public static void getCompilationUnitLabel(ICompilationUnit cu, int flags, StringBuffer buf) {
if (getFlag(flags, CU_QUALIFIED)) {
IPackageFragment pack= (IPackageFragment) cu.getParent();
if (!pack.isDefaultPackage()) {
buf.append(pack.getElementName());
buf.append('.');
}
}
buf.append(cu.getElementName());
if (getFlag(flags, CU_POST_QUALIFIED)) {
buf.append(CONCAT_STRING);
getPackageFragmentLabel((IPackageFragment) cu.getParent(), 0, buf);
}
}
/**
* Appends the label for a package fragment to a StringBuffer. Considers the P_* flags.
*/
public static void getPackageFragmentLabel(IPackageFragment pack, int flags, StringBuffer buf) {
if (getFlag(flags, P_QUALIFIED)) {
getPackageFragmentRootLabel((IPackageFragmentRoot) pack.getParent(), ROOT_QUALIFIED, buf);
buf.append('/');
}
refreshPackageNamePattern();
if (pack.isDefaultPackage()) {
buf.append(JavaUIMessages.getString("JavaElementLabels.default_package")); //$NON-NLS-1$
} else if (getFlag(flags, P_COMPRESSED) && fgPkgNameLength >= 0) {
String name= pack.getElementName();
int start= 0;
int dot= name.indexOf('.', start);
while (dot > 0) {
if (dot - start > fgPkgNameLength-1) {
buf.append(fgPkgNamePrefix);
if (fgPkgNameChars > 0)
buf.append(name.substring(start, Math.min(start+ fgPkgNameChars, dot)));
buf.append(fgPkgNamePostfix);
} else
buf.append(name.substring(start, dot + 1));
start= dot + 1;
dot= name.indexOf('.', start);
}
buf.append(name.substring(start));
} else {
buf.append(pack.getElementName());
}
if (getFlag(flags, P_POST_QUALIFIED)) {
buf.append(CONCAT_STRING);
getPackageFragmentRootLabel((IPackageFragmentRoot) pack.getParent(), ROOT_QUALIFIED, buf);
}
}
/**
* Appends the label for a package fragment root to a StringBuffer. Considers the ROOT_* flags.
*/
public static void getPackageFragmentRootLabel(IPackageFragmentRoot root, int flags, StringBuffer buf) {
if (root.isArchive() && getFlag(flags, ROOT_VARIABLE)) {
try {
IClasspathEntry rawEntry= root.getRawClasspathEntry();
if (rawEntry != null) {
if (rawEntry.getEntryKind() == IClasspathEntry.CPE_VARIABLE) {
buf.append(rawEntry.getPath().makeRelative());
buf.append(CONCAT_STRING);
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e); // problems with class path
}
}
if (root.isExternal()) {
// external jars have path == name
// no qualification for external roots
buf.append(root.getPath().toOSString());
} else {
if (getFlag(flags, ROOT_QUALIFIED)) {
buf.append(root.getPath().makeRelative().toString());
} else {
buf.append(root.getElementName());
}
if (getFlag(flags, ROOT_POST_QUALIFIED)) {
buf.append(CONCAT_STRING);
buf.append(root.getParent().getElementName());
}
}
}
private static void refreshPackageNamePattern() {
String pattern= getPkgNamePatternForPackagesView();
if (pattern.equals(fgPkgNamePattern))
return;
else if (pattern.equals("")) { //$NON-NLS-1$
fgPkgNamePattern= ""; //$NON-NLS-1$
fgPkgNameLength= -1;
return;
}
fgPkgNamePattern= pattern;
int i= 0;
fgPkgNameChars= 0;
fgPkgNamePrefix= ""; //$NON-NLS-1$
fgPkgNamePostfix= ""; //$NON-NLS-1$
while (i < pattern.length()) {
char ch= pattern.charAt(i);
if (Character.isDigit(ch)) {
fgPkgNameChars= ch-48;
if (i > 0)
fgPkgNamePrefix= pattern.substring(0, i);
if (i >= 0)
fgPkgNamePostfix= pattern.substring(i+1);
fgPkgNameLength= fgPkgNamePrefix.length() + fgPkgNameChars + fgPkgNamePostfix.length();
return;
}
i++;
}
fgPkgNamePrefix= pattern;
fgPkgNameLength= pattern.length();
}
private static String getPkgNamePatternForPackagesView() {
IPreferenceStore store= PreferenceConstants.getPreferenceStore();
if (!store.getBoolean(PreferenceConstants.APPEARANCE_COMPRESS_PACKAGE_NAMES))
return ""; //$NON-NLS-1$
return store.getString(PreferenceConstants.APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW);
}
}
|
21,047 |
Bug 21047 code formatter availability inconsistent
|
Sometimes the hotkey (ctrl-shift-f) and the menu entry for formatting the source code are disabled, while the entry in the context menu is enabled and works as expected. I didn't find any patterns on when this occurs till now.
|
resolved fixed
|
ede408a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-07T14:01:43Z | 2002-06-27T09:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/CompilationUnitEditor.java
|
/**********************************************************************
Copyright (c) 2000, 2002 IBM Corp. 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 implementation
**********************************************************************/
package org.eclipse.jdt.internal.ui.javaeditor;
import java.lang.reflect.InvocationTargetException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Preferences;
import org.eclipse.core.runtime.Preferences.IPropertyChangeListener;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.custom.VerifyKeyListener;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Layout;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.text.AbstractHoverInformationControlManager;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DocumentCommand;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ILineTracker;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextOperationTarget;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.ITextViewerExtension;
import org.eclipse.jface.text.ITextViewerExtension3;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.IWidgetTokenKeeper;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.contentassist.ContentAssistant;
import org.eclipse.jface.text.contentassist.IContentAssistant;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.IVerticalRuler;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.actions.WorkspaceModifyOperation;
import org.eclipse.ui.dialogs.SaveAsDialog;
import org.eclipse.ui.editors.text.IStorageDocumentProvider;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.texteditor.ContentAssistAction;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.ui.texteditor.IEditorStatusLine;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.ui.texteditor.MarkerAnnotation;
import org.eclipse.ui.texteditor.TextOperationAction;
import org.eclipse.ui.views.tasklist.TaskList;
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.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.ui.text.JavaTextTools;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.compare.LocalHistoryActionGroup;
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.preferences.JavaEditorPreferencePage;
import org.eclipse.jdt.internal.ui.search.SearchUsagesInFileAction;
import org.eclipse.jdt.internal.ui.text.ContentAssistPreference;
import org.eclipse.jdt.internal.ui.text.JavaPairMatcher;
import org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionSourceViewer;
import org.eclipse.jdt.internal.ui.text.java.IReconcilingParticipant;
import org.eclipse.jdt.internal.ui.text.java.SmartBracesAutoEditStrategy;
import org.eclipse.jdt.internal.ui.text.link.LinkedPositionManager;
import org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI;
import org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI.ExitFlags;
/**
* Java specific text editor.
*/
public class CompilationUnitEditor extends JavaEditor implements IReconcilingParticipant {
interface ITextConverter {
void customizeDocumentCommand(IDocument document, DocumentCommand command);
};
class AdaptedRulerLayout extends Layout {
protected int fGap;
protected AdaptedSourceViewer fAdaptedSourceViewer;
protected AdaptedRulerLayout(int gap, AdaptedSourceViewer asv) {
fGap= gap;
fAdaptedSourceViewer= asv;
}
protected Point computeSize(Composite composite, int wHint, int hHint, boolean flushCache) {
Control[] children= composite.getChildren();
Point s= children[children.length - 1].computeSize(SWT.DEFAULT, SWT.DEFAULT, flushCache);
if (fAdaptedSourceViewer.isVerticalRulerVisible())
s.x += fAdaptedSourceViewer.getVerticalRuler().getWidth() + fGap;
return s;
}
protected void layout(Composite composite, boolean flushCache) {
Rectangle clArea= composite.getClientArea();
if (fAdaptedSourceViewer.isVerticalRulerVisible()) {
StyledText textWidget= fAdaptedSourceViewer.getTextWidget();
Rectangle trim= textWidget.computeTrim(0, 0, 0, 0);
int scrollbarHeight= trim.height;
IVerticalRuler vr= fAdaptedSourceViewer.getVerticalRuler();
int vrWidth=vr.getWidth();
int orWidth= 0;
if (fAdaptedSourceViewer.isOverviewRulerVisible()) {
OverviewRuler or= fAdaptedSourceViewer.getOverviewRuler();
orWidth= or.getWidth();
or.getControl().setBounds(clArea.width - orWidth, scrollbarHeight, orWidth, clArea.height - 3*scrollbarHeight);
}
textWidget.setBounds(vrWidth + fGap, 0, clArea.width - vrWidth - orWidth - 2*fGap, clArea.height);
vr.getControl().setBounds(0, 0, vrWidth, clArea.height - scrollbarHeight);
} else {
StyledText textWidget= fAdaptedSourceViewer.getTextWidget();
textWidget.setBounds(0, 0, clArea.width, clArea.height);
}
}
};
class AdaptedSourceViewer extends JavaCorrectionSourceViewer {
private List fTextConverters;
private OverviewRuler fOverviewRuler;
private boolean fIsOverviewRulerVisible;
/** The viewer's overview ruler hovering controller */
private AbstractHoverInformationControlManager fOverviewRulerHoveringController;
private boolean fIgnoreTextConverters= false;
private IVerticalRuler fCachedVerticalRuler;
private boolean fCachedIsVerticalRulerVisible;
public AdaptedSourceViewer(Composite parent, IVerticalRuler ruler, int styles) {
super(parent, ruler, styles, CompilationUnitEditor.this);
fCachedVerticalRuler= ruler;
fCachedIsVerticalRulerVisible= (ruler != null);
fOverviewRuler= new OverviewRuler(VERTICAL_RULER_WIDTH);
delayedCreateControl(parent, styles);
}
/*
* @see ISourceViewer#showAnnotations(boolean)
*/
public void showAnnotations(boolean show) {
fCachedIsVerticalRulerVisible= (show && fCachedVerticalRuler != null);
super.showAnnotations(show);
}
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 UNDO:
fIgnoreTextConverters= true;
break;
case REDO:
fIgnoreTextConverters= true;
break;
}
super.doOperation(operation);
}
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;
}
public IVerticalRuler getVerticalRuler() {
return fCachedVerticalRuler;
}
public boolean isVerticalRulerVisible() {
return fCachedIsVerticalRulerVisible;
}
public OverviewRuler getOverviewRuler() {
return fOverviewRuler;
}
/*
* @see TextViewer#createControl(Composite, int)
*/
protected void createControl(Composite parent, int styles) {
// do nothing here
}
protected void delayedCreateControl(Composite parent, int styles) {
//create the viewer
super.createControl(parent, styles);
Control control= getControl();
if (control instanceof Composite) {
Composite composite= (Composite) control;
composite.setLayout(new AdaptedRulerLayout(GAP_SIZE, this));
fOverviewRuler.createControl(composite, this);
}
}
private void ensureOverviewHoverManagerInstalled() {
if (fOverviewRulerHoveringController == null && fAnnotationHover != null && fHoverControlCreator != null) {
fOverviewRulerHoveringController= new OverviewRulerHoverManager(fOverviewRuler, this, fAnnotationHover, fHoverControlCreator);
fOverviewRulerHoveringController.install(fOverviewRuler.getControl());
}
}
public void hideOverviewRuler() {
fIsOverviewRulerVisible= false;
Control control= getControl();
if (control instanceof Composite) {
Composite composite= (Composite) control;
composite.layout();
}
if (fOverviewRulerHoveringController != null) {
fOverviewRulerHoveringController.dispose();
fOverviewRulerHoveringController= null;
}
}
public void showOverviewRuler() {
fIsOverviewRulerVisible= true;
Control control= getControl();
if (control instanceof Composite) {
Composite composite= (Composite) control;
composite.layout();
}
ensureOverviewHoverManagerInstalled();
}
public boolean isOverviewRulerVisible() {
return fIsOverviewRulerVisible;
}
/*
* @see ISourceViewer#setDocument(IDocument, IAnnotationModel, int, int)
*/
public void setDocument(IDocument document, IAnnotationModel annotationModel, int visibleRegionOffset, int visibleRegionLength) {
super.setDocument(document, annotationModel, visibleRegionOffset, visibleRegionLength);
fOverviewRuler.setModel(annotationModel);
}
// 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 org.eclipse.jface.text.source.ISourceViewer#configure(org.eclipse.jface.text.source.SourceViewerConfiguration)
*/
public void configure(SourceViewerConfiguration configuration) {
super.configure(configuration);
prependAutoEditStrategy(new SmartBracesAutoEditStrategy(this), IDocument.DEFAULT_CONTENT_TYPE);
}
protected void handleDispose() {
fOverviewRuler= null;
if (fOverviewRulerHoveringController != null) {
fOverviewRulerHoveringController.dispose();
fOverviewRulerHoveringController= null;
}
super.handleDispose();
}
};
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 PropertyChangeListener implements IPropertyChangeListener {
/*
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
handlePreferencePropertyChanged(event);
}
}
/* Preference key for code formatter tab size */
private final static String CODE_FORMATTER_TAB_SIZE= JavaCore.FORMATTER_TAB_SIZE;
/** Preference key for matching brackets */
private final static String MATCHING_BRACKETS= PreferenceConstants.EDITOR_MATCHING_BRACKETS;
/** Preference key for matching brackets color */
private final static String MATCHING_BRACKETS_COLOR= PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR;
/** Preference key for highlighting current line */
private final static String CURRENT_LINE= PreferenceConstants.EDITOR_CURRENT_LINE;
/** Preference key for highlight color of current line */
private final static String CURRENT_LINE_COLOR= PreferenceConstants.EDITOR_CURRENT_LINE_COLOR;
/** Preference key for showing print marging ruler */
private final static String PRINT_MARGIN= PreferenceConstants.EDITOR_PRINT_MARGIN;
/** Preference key for print margin ruler color */
private final static String PRINT_MARGIN_COLOR= PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR;
/** Preference key for print margin ruler column */
private final static String PRINT_MARGIN_COLUMN= PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN;
/** Preference key for inserting spaces rather than tabs */
private final static String SPACES_FOR_TABS= PreferenceConstants.EDITOR_SPACES_FOR_TABS;
/** Preference key for error indication */
private final static String ERROR_INDICATION= PreferenceConstants.EDITOR_PROBLEM_INDICATION;
/** Preference key for error color */
private final static String ERROR_INDICATION_COLOR= PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR;
/** Preference key for warning indication */
private final static String WARNING_INDICATION= PreferenceConstants.EDITOR_WARNING_INDICATION;
/** Preference key for warning color */
private final static String WARNING_INDICATION_COLOR= PreferenceConstants.EDITOR_WARNING_INDICATION_COLOR;
/** Preference key for task indication */
private final static String TASK_INDICATION= PreferenceConstants.EDITOR_TASK_INDICATION;
/** Preference key for task color */
private final static String TASK_INDICATION_COLOR= PreferenceConstants.EDITOR_TASK_INDICATION_COLOR;
/** Preference key for bookmark indication */
private final static String BOOKMARK_INDICATION= PreferenceConstants.EDITOR_BOOKMARK_INDICATION;
/** Preference key for bookmark color */
private final static String BOOKMARK_INDICATION_COLOR= PreferenceConstants.EDITOR_BOOKMARK_INDICATION_COLOR;
/** Preference key for search result indication */
private final static String SEARCH_RESULT_INDICATION= PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION;
/** Preference key for search result color */
private final static String SEARCH_RESULT_INDICATION_COLOR= PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_COLOR;
/** Preference key for unknown annotation indication */
private final static String UNKNOWN_INDICATION= PreferenceConstants.EDITOR_UNKNOWN_INDICATION;
/** Preference key for unknown annotation color */
private final static String UNKNOWN_INDICATION_COLOR= PreferenceConstants.EDITOR_UNKNOWN_INDICATION_COLOR;
/** Preference key for linked position color */
private final static String LINKED_POSITION_COLOR= PreferenceConstants.EDITOR_LINKED_POSITION_COLOR;
/** Preference key for shwoing the overview ruler */
private final static String OVERVIEW_RULER= PreferenceConstants.EDITOR_OVERVIEW_RULER;
/** Preference key for error indication in overview ruler */
private final static String ERROR_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER;
/** Preference key for warning indication in overview ruler */
private final static String WARNING_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER;
/** Preference key for task indication in overview ruler */
private final static String TASK_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER;
/** Preference key for bookmark indication in overview ruler */
private final static String BOOKMARK_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER;
/** Preference key for search result indication in overview ruler */
private final static String SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER;
/** Preference key for unknown annotation indication in overview ruler */
private final static String UNKNOWN_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER;
/** Preference key for automatically closing strings */
private final static String CLOSE_STRINGS= PreferenceConstants.EDITOR_CLOSE_STRINGS;
/** Preference key for automatically wrapping Java strings */
private final static String WRAP_STRINGS= PreferenceConstants.EDITOR_WRAP_STRINGS;
/** Preference key for automatically closing brackets and parenthesis */
private final static String CLOSE_BRACKETS= PreferenceConstants.EDITOR_CLOSE_BRACKETS;
/** Preference key for automatically closing javadocs and comments */
private final static String CLOSE_JAVADOCS= PreferenceConstants.EDITOR_CLOSE_JAVADOCS;
/** Preference key for automatically adding javadoc tags */
private final static String ADD_JAVADOC_TAGS= PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS;
/** Preference key for automatically formatting javadocs */
private final static String FORMAT_JAVADOCS= PreferenceConstants.EDITOR_FORMAT_JAVADOCS;
/** Preference key for smart paste */
private final static String SMART_PASTE= PreferenceConstants.EDITOR_SMART_PASTE;
private final static class AnnotationInfo {
public String fColorPreference;
public String fOverviewRulerPreference;
public String fEditorPreference;
};
private final static Map ANNOTATION_MAP;
static {
AnnotationInfo info;
ANNOTATION_MAP= new HashMap();
info= new AnnotationInfo();
info.fColorPreference= TASK_INDICATION_COLOR;
info.fOverviewRulerPreference= TASK_INDICATION_IN_OVERVIEW_RULER;
info.fEditorPreference= TASK_INDICATION;
ANNOTATION_MAP.put(AnnotationType.TASK, info);
info= new AnnotationInfo();
info.fColorPreference= ERROR_INDICATION_COLOR;
info.fOverviewRulerPreference= ERROR_INDICATION_IN_OVERVIEW_RULER;
info.fEditorPreference= ERROR_INDICATION;
ANNOTATION_MAP.put(AnnotationType.ERROR, info);
info= new AnnotationInfo();
info.fColorPreference= WARNING_INDICATION_COLOR;
info.fOverviewRulerPreference= WARNING_INDICATION_IN_OVERVIEW_RULER;
info.fEditorPreference= WARNING_INDICATION;
ANNOTATION_MAP.put(AnnotationType.WARNING, info);
info= new AnnotationInfo();
info.fColorPreference= BOOKMARK_INDICATION_COLOR;
info.fOverviewRulerPreference= BOOKMARK_INDICATION_IN_OVERVIEW_RULER;
info.fEditorPreference= BOOKMARK_INDICATION;
ANNOTATION_MAP.put(AnnotationType.BOOKMARK, info);
info= new AnnotationInfo();
info.fColorPreference= SEARCH_RESULT_INDICATION_COLOR;
info.fOverviewRulerPreference= SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER;
info.fEditorPreference= SEARCH_RESULT_INDICATION;
ANNOTATION_MAP.put(AnnotationType.SEARCH_RESULT, info);
info= new AnnotationInfo();
info.fColorPreference= UNKNOWN_INDICATION_COLOR;
info.fOverviewRulerPreference= UNKNOWN_INDICATION_IN_OVERVIEW_RULER;
info.fEditorPreference= UNKNOWN_INDICATION;
ANNOTATION_MAP.put(AnnotationType.UNKNOWN, info);
};
private final static AnnotationType[] ANNOTATION_LAYERS= new AnnotationType[] {
AnnotationType.UNKNOWN,
AnnotationType.BOOKMARK,
AnnotationType.TASK,
AnnotationType.SEARCH_RESULT,
AnnotationType.WARNING,
AnnotationType.ERROR
};
/** 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 paint manager */
private PaintManager fPaintManager;
/** The editor's bracket painter */
private BracketPainter fBracketPainter;
/** The editor's bracket matcher */
private JavaPairMatcher fBracketMatcher;
/** The editor's line painter */
private LinePainter fLinePainter;
/** The editor's print margin ruler painter */
private PrintMarginPainter fPrintMarginPainter;
/** The editor's problem painter */
private ProblemPainter fProblemPainter;
/** The editor's tab converter */
private TabConverter fTabConverter;
/** History for structure select action */
private SelectionHistory fSelectionHistory;
/** The preference property change listener for java core. */
private IPropertyChangeListener fPropertyChangeListener= new PropertyChangeListener();
/** 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, JavaCorrectionSourceViewer.CORRECTIONASSIST_PROPOSALS); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.CORRECTION_ASSIST_PROPOSALS);
setAction("CorrectionAssistProposal", action); //$NON-NLS-1$
action= new ContentAssistAction(JavaEditorMessages.getResourceBundle(), "ContentAssistProposal.", this); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS);
setAction("ContentAssistProposal", action); //$NON-NLS-1$
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$
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "Comment.", this, ITextOperationTarget.PREFIX); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.COMMENT);
setAction("Comment", action); //$NON-NLS-1$
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "Uncomment.", this, ITextOperationTarget.STRIP_PREFIX); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.UNCOMMENT);
setAction("Uncomment", action); //$NON-NLS-1$
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "Format.", this, ISourceViewer.FORMAT); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.FORMAT);
setAction("Format", action); //$NON-NLS-1$
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"ShowOutline.", this, JavaCorrectionSourceViewer.SHOW_OUTLINE, true); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_OUTLINE);
setAction(IJavaEditorActionDefinitionIds.SHOW_OUTLINE, action);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"OpenStructure.", this, JavaCorrectionSourceViewer.OPEN_STRUCTURE, true); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_STRUCTURE);
setAction(IJavaEditorActionDefinitionIds.OPEN_STRUCTURE, action);
markAsStateDependentAction("CorrectionAssistProposal", true); //$NON-NLS-1$
markAsStateDependentAction("ContentAssistProposal", true); //$NON-NLS-1$
markAsStateDependentAction("ContentAssistContextInformation", true); //$NON-NLS-1$
markAsStateDependentAction("Comment", true); //$NON-NLS-1$
markAsStateDependentAction("Uncomment", true); //$NON-NLS-1$
markAsStateDependentAction("Format", true); //$NON-NLS-1$
action= new GotoMatchingBracketAction(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_MATCHING_BRACKET);
setAction(GotoMatchingBracketAction.GOTO_MATCHING_BRACKET, action);
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);
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);
action= new SearchUsagesInFileAction(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_REFERENCES);
setAction(SearchUsagesInFileAction.SHOWREFERENCES, action);
StructureSelectHistoryAction historyAction= new StructureSelectHistoryAction(this, fSelectionHistory);
historyAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_LAST);
setAction(StructureSelectionAction.HISTORY, historyAction);
fSelectionHistory.setHistoryAction(historyAction);
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) {
JavaPlugin.log(x.getStatus());
// nothing found, be tolerant and go on
}
}
return null;
}
/*
* @see JavaEditor#getCorrespondingElement(IJavaElement)
*/
protected IJavaElement getCorrespondingElement(IJavaElement element) {
try {
return EditorUtility.getWorkingCopy(element, true);
} catch (JavaModelException x) {
JavaPlugin.log(x.getStatus());
// nothing found, be tolerant and go on
}
return null;
}
/*
* @see AbstractTextEditor#editorContextMenuAboutToShow(IMenuManager)
*/
public void editorContextMenuAboutToShow(IMenuManager menu) {
super.editorContextMenuAboutToShow(menu);
addAction(menu, ITextEditorActionConstants.GROUP_EDIT, "Format"); //$NON-NLS-1$
ActionContext context= new ActionContext(getSelectionProvider().getSelection());
fContextMenuGroup.setContext(context);
fContextMenuGroup.fillContextMenu(menu);
fContextMenuGroup.setContext(null);
}
/*
* @see JavaEditor#setOutlinePageInput(JavaOutlinePage, IEditorInput)
*/
protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input) {
if (page != null) {
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
page.setInput(manager.getWorkingCopy(input));
}
}
/*
* @see AbstractTextEditor#performSaveOperation(WorkspaceModifyOperation, IProgressMonitor)
*/
protected void performSaveOperation(WorkspaceModifyOperation operation, IProgressMonitor progressMonitor) {
IDocumentProvider p= getDocumentProvider();
if (p instanceof CompilationUnitDocumentProvider) {
CompilationUnitDocumentProvider cp= (CompilationUnitDocumentProvider) p;
cp.setSavePolicy(fSavePolicy);
}
try {
super.performSaveOperation(operation, progressMonitor);
} finally {
if (p instanceof CompilationUnitDocumentProvider) {
CompilationUnitDocumentProvider cp= (CompilationUnitDocumentProvider) p;
cp.setSavePolicy(null);
}
}
}
/*
* @see AbstractTextEditor#doSaveAs
*/
public void doSaveAs() {
if (askIfNonWorkbenchEncodingIsOk()) {
super.doSaveAs();
}
}
/*
* @see AbstractTextEditor#doSave(IProgressMonitor)
*/
public void doSave(IProgressMonitor progressMonitor) {
IDocumentProvider p= getDocumentProvider();
if (p == null) {
// editor has been closed
return;
}
if (!askIfNonWorkbenchEncodingIsOk()) {
progressMonitor.setCanceled(true);
return;
}
if (p.isDeleted(getEditorInput())) {
if (isSaveAsAllowed()) {
/*
* 1GEUSSR: ITPUI:ALL - User should never loose changes made in the editors.
* Changed Behavior to make sure that if called inside a regular save (because
* of deletion of input element) there is a way to report back to the caller.
*/
performSaveAs(progressMonitor);
} else {
/*
* 1GF5YOX: ITPJUI:ALL - Save of delete file claims it's still there
* Missing resources.
*/
Shell shell= getSite().getShell();
MessageDialog.openError(shell, JavaEditorMessages.getString("CompilationUnitEditor.error.saving.title1"), JavaEditorMessages.getString("CompilationUnitEditor.error.saving.message1")); //$NON-NLS-1$ //$NON-NLS-2$
}
} else {
setStatusLineErrorMessage(null);
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
ICompilationUnit unit= manager.getWorkingCopy(getEditorInput());
if (unit != null) {
synchronized (unit) {
performSaveOperation(createSaveOperation(false), progressMonitor);
}
} else
performSaveOperation(createSaveOperation(false), progressMonitor);
}
}
/**
* Asks the user if it is ok to store in non-workbench encoding.
* @return <true> if the user wants to continue
*/
private boolean askIfNonWorkbenchEncodingIsOk() {
IDocumentProvider provider= getDocumentProvider();
if (provider instanceof IStorageDocumentProvider) {
IEditorInput input= getEditorInput();
IStorageDocumentProvider storageProvider= (IStorageDocumentProvider)provider;
String encoding= storageProvider.getEncoding(input);
String defaultEncoding= storageProvider.getDefaultEncoding();
if (encoding != null && !encoding.equals(defaultEncoding)) {
Shell shell= getSite().getShell();
String title= JavaEditorMessages.getString("CompilationUnitEditor.warning.save.nonWorkbenchEncoding.title"); //$NON-NLS-1$
String msg;
if (input != null)
msg= MessageFormat.format(JavaEditorMessages.getString("CompilationUnitEditor.warning.save.nonWorkbenchEncoding.message1"), new String[] {input.getName(), encoding});//$NON-NLS-1$
else
msg= MessageFormat.format(JavaEditorMessages.getString("CompilationUnitEditor.warning.save.nonWorkbenchEncoding.message2"), new String[] {encoding});//$NON-NLS-1$
return MessageDialog.openQuestion(shell, title, msg);
}
}
return true;
}
/**
* Jumps to the error next according to the given direction.
*/
public void gotoError(boolean forward) {
ISelectionProvider provider= getSelectionProvider();
ITextSelection s= (ITextSelection) provider.getSelection();
Position errorPosition= new Position(0, 0);
IProblemAnnotation nextError= getNextError(s.getOffset(), forward, errorPosition);
if (nextError != null) {
IMarker marker= null;
if (nextError instanceof MarkerAnnotation)
marker= ((MarkerAnnotation) nextError).getMarker();
else {
Iterator e= nextError.getOverlaidIterator();
if (e != null) {
while (e.hasNext()) {
Object o= e.next();
if (o instanceof MarkerAnnotation) {
marker= ((MarkerAnnotation) o).getMarker();
break;
}
}
}
}
if (marker != null) {
IWorkbenchPage page= getSite().getPage();
IViewPart view= view= page.findView("org.eclipse.ui.views.TaskList"); //$NON-NLS-1$
if (view instanceof TaskList) {
StructuredSelection ss= new StructuredSelection(marker);
((TaskList) view).setSelection(ss, true);
}
}
selectAndReveal(errorPosition.getOffset(), errorPosition.getLength());
setStatusLineErrorMessage(nextError.getMessage());
} else {
setStatusLineErrorMessage(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 final static char[] BRACKETS= { '{', '}', '(', ')', '[', ']' };
private static boolean isBracket(char character) {
for (int i= 0; i != BRACKETS.length; ++i)
if (character == BRACKETS[i])
return true;
return false;
}
private static boolean isSurroundedByBrackets(IDocument document, int offset) {
if (offset == 0 || offset == document.getLength())
return false;
try {
return
isBracket(document.getChar(offset - 1)) &&
isBracket(document.getChar(offset));
} catch (BadLocationException e) {
return false;
}
}
/**
* Jumps to the matching bracket.
*/
public void gotoMatchingBracket() {
if (fBracketMatcher == null)
fBracketMatcher= new JavaPairMatcher(BRACKETS);
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();
int targetOffset= (JavaPairMatcher.RIGHT == anchor) ? offset : offset + length - 1;
boolean visible= false;
if (sourceViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) sourceViewer;
visible= (extension.modelOffset2WidgetOffset(targetOffset) > -1);
} else {
IRegion visibleRegion= sourceViewer.getVisibleRegion();
visible= (targetOffset >= visibleRegion.getOffset() && targetOffset < visibleRegion.getOffset() + visibleRegion.getLength());
}
if (!visible) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.bracketOutsideSelectedElement")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
if (selection.getLength() < 0)
targetOffset -= selection.getLength();
sourceViewer.setSelectedRange(targetOffset, selection.getLength());
sourceViewer.revealRange(targetOffset, selection.getLength());
}
/**
* Ses the given message as error message to this editor's status line.
* @param msg message to be set
*/
protected void setStatusLineErrorMessage(String msg) {
IEditorStatusLine statusLine= (IEditorStatusLine) getAdapter(IEditorStatusLine.class);
if (statusLine != null)
statusLine.setMessage(true, msg, null);
}
private IProblemAnnotation getNextError(int offset, boolean forward, Position errorPosition) {
IProblemAnnotation nextError= null;
Position nextErrorPosition= null;
IDocument document= getDocumentProvider().getDocument(getEditorInput());
int endOfDocument= document.getLength();
int distance= 0;
IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput());
Iterator e= new ProblemAnnotationIterator(model, false);
while (e.hasNext()) {
IProblemAnnotation a= (IProblemAnnotation) e.next();
if (a.hasOverlay() || !a.isProblem())
continue;
Position p= model.getPosition((Annotation) a);
if (!p.includes(offset)) {
int currentDistance= 0;
if (forward) {
currentDistance= p.getOffset() - offset;
if (currentDistance < 0)
currentDistance= endOfDocument - offset + p.getOffset();
} else {
currentDistance= offset - p.getOffset();
if (currentDistance < 0)
currentDistance= offset + endOfDocument - p.getOffset();
}
if (nextError == null || currentDistance < distance) {
distance= currentDistance;
nextError= a;
nextErrorPosition= p;
}
}
}
if (nextErrorPosition != null) {
errorPosition.setOffset(nextErrorPosition.getOffset());
errorPosition.setLength(nextErrorPosition.getLength());
}
return nextError;
}
/*
* @see AbstractTextEditor#isSaveAsAllowed()
*/
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() == Dialog.CANCEL) {
if (progressMonitor != null)
progressMonitor.setCanceled(true);
return;
}
IPath filePath= dialog.getResult();
if (filePath == null) {
if (progressMonitor != null)
progressMonitor.setCanceled(true);
return;
}
IWorkspace workspace= ResourcesPlugin.getWorkspace();
IFile file= workspace.getRoot().getFile(filePath);
final IEditorInput newInput= new FileEditorInput(file);
WorkspaceModifyOperation op= new WorkspaceModifyOperation() {
public void execute(final IProgressMonitor monitor) throws CoreException {
getDocumentProvider().saveDocument(monitor, newInput, getDocumentProvider().getDocument(getEditorInput()), true);
}
};
boolean success= false;
try {
provider.aboutToChange(newInput);
new ProgressMonitorDialog(shell).run(false, true, op);
success= true;
} catch (InterruptedException x) {
} catch (InvocationTargetException x) {
Throwable t= x.getTargetException();
if (t instanceof CoreException) {
CoreException cx= (CoreException) t;
ErrorDialog.openError(shell, JavaEditorMessages.getString("CompilationUnitEditor.error.saving.title2"), JavaEditorMessages.getString("CompilationUnitEditor.error.saving.message2"), cx.getStatus()); //$NON-NLS-1$ //$NON-NLS-2$
} else {
MessageDialog.openError(shell, JavaEditorMessages.getString("CompilationUnitEditor.error.saving.title3"), JavaEditorMessages.getString("CompilationUnitEditor.error.saving.message3") + t.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
}
} finally {
provider.changed(newInput);
if (success)
setInput(newInput);
}
if (progressMonitor != null)
progressMonitor.setCanceled(!success);
}
/*
* @see AbstractTextEditor#doSetInput(IEditorInput)
*/
protected void doSetInput(IEditorInput input) throws CoreException {
super.doSetInput(input);
configureTabConverter();
}
private void startBracketHighlighting() {
if (fBracketPainter == null) {
ISourceViewer sourceViewer= getSourceViewer();
fBracketPainter= new BracketPainter(sourceViewer);
fBracketPainter.setHighlightColor(getColor(MATCHING_BRACKETS_COLOR));
fPaintManager.addPainter(fBracketPainter);
}
}
private void stopBracketHighlighting() {
if (fBracketPainter != null) {
fPaintManager.removePainter(fBracketPainter);
fBracketPainter.deactivate(true);
fBracketPainter.dispose();
fBracketPainter= null;
}
}
private boolean isBracketHighlightingEnabled() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(MATCHING_BRACKETS);
}
private void startLineHighlighting() {
if (fLinePainter == null) {
ISourceViewer sourceViewer= getSourceViewer();
fLinePainter= new LinePainter(sourceViewer);
fLinePainter.setHighlightColor(getColor(CURRENT_LINE_COLOR));
fPaintManager.addPainter(fLinePainter);
}
}
private void stopLineHighlighting() {
if (fLinePainter != null) {
fPaintManager.removePainter(fLinePainter);
fLinePainter.deactivate(true);
fLinePainter.dispose();
fLinePainter= null;
}
}
private boolean isLineHighlightingEnabled() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(CURRENT_LINE);
}
private void showPrintMargin() {
if (fPrintMarginPainter == null) {
fPrintMarginPainter= new PrintMarginPainter(getSourceViewer());
fPrintMarginPainter.setMarginRulerColor(getColor(PRINT_MARGIN_COLOR));
fPrintMarginPainter.setMarginRulerColumn(getPreferenceStore().getInt(PRINT_MARGIN_COLUMN));
fPaintManager.addPainter(fPrintMarginPainter);
}
}
private void hidePrintMargin() {
if (fPrintMarginPainter != null) {
fPaintManager.removePainter(fPrintMarginPainter);
fPrintMarginPainter.deactivate(true);
fPrintMarginPainter.dispose();
fPrintMarginPainter= null;
}
}
private boolean isPrintMarginVisible() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(PRINT_MARGIN);
}
private void startAnnotationIndication(AnnotationType annotationType) {
if (fProblemPainter == null) {
fProblemPainter= new ProblemPainter(this, getSourceViewer());
fPaintManager.addPainter(fProblemPainter);
}
fProblemPainter.setColor(annotationType, getColor(annotationType));
fProblemPainter.paintAnnotations(annotationType, true);
fProblemPainter.paint(IPainter.CONFIGURATION);
}
private void shutdownAnnotationIndication() {
if (fProblemPainter != null) {
if (!fProblemPainter.isPaintingAnnotations()) {
fPaintManager.removePainter(fProblemPainter);
fProblemPainter.deactivate(true);
fProblemPainter.dispose();
fProblemPainter= null;
} else {
fProblemPainter.paint(IPainter.CONFIGURATION);
}
}
}
private void stopAnnotationIndication(AnnotationType annotationType) {
if (fProblemPainter != null) {
fProblemPainter.paintAnnotations(annotationType, false);
shutdownAnnotationIndication();
}
}
private boolean isAnnotationIndicationEnabled(AnnotationType annotationType) {
IPreferenceStore store= getPreferenceStore();
AnnotationInfo info= (AnnotationInfo) ANNOTATION_MAP.get(annotationType);
if (info != null)
return store.getBoolean(info.fEditorPreference);
return false;
}
private boolean isAnnotationIndicationInOverviewRulerEnabled(AnnotationType annotationType) {
IPreferenceStore store= getPreferenceStore();
AnnotationInfo info= (AnnotationInfo) ANNOTATION_MAP.get(annotationType);
if (info != null)
return store.getBoolean(info.fOverviewRulerPreference);
return false;
}
private void showAnnotationIndicationInOverviewRuler(AnnotationType annotationType, boolean show) {
AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer();
OverviewRuler ruler= asv.getOverviewRuler();
if (ruler != null) {
ruler.setColor(annotationType, getColor(annotationType));
ruler.showAnnotation(annotationType, show);
ruler.update();
}
}
private void setColorInOverviewRuler(AnnotationType annotationType, Color color) {
AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer();
OverviewRuler ruler= asv.getOverviewRuler();
if (ruler != null) {
ruler.setColor(annotationType, color);
ruler.update();
}
}
private void configureTabConverter() {
if (fTabConverter != null) {
IDocumentProvider provider= getDocumentProvider();
if (provider instanceof CompilationUnitDocumentProvider) {
CompilationUnitDocumentProvider cup= (CompilationUnitDocumentProvider) 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);
}
private void showOverviewRuler() {
AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer();
asv.showOverviewRuler();
OverviewRuler overviewRuler= asv.getOverviewRuler();
if (overviewRuler != null) {
for (int i= 0; i < ANNOTATION_LAYERS.length; i++) {
AnnotationType type= ANNOTATION_LAYERS[i];
overviewRuler.setLayer(type, i);
if (isAnnotationIndicationInOverviewRulerEnabled(type))
showAnnotationIndicationInOverviewRuler(type, true);
}
}
}
private void hideOverviewRuler() {
AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer();
asv.hideOverviewRuler();
}
private boolean isOverviewRulerVisible() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(OVERVIEW_RULER);
}
private Color getColor(String key) {
RGB rgb= PreferenceConverter.getColor(getPreferenceStore(), key);
return getColor(rgb);
}
private Color getColor(RGB rgb) {
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
return textTools.getColorManager().getColor(rgb);
}
private Color getColor(AnnotationType annotationType) {
AnnotationInfo info= (AnnotationInfo) ANNOTATION_MAP.get(annotationType);
if (info != null)
return getColor(info.fColorPreference);
return null;
}
/*
* @see AbstractTextEditor#dispose()
*/
public void dispose() {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer instanceof ITextViewerExtension)
((ITextViewerExtension) sourceViewer).removeVerifyKeyListener(fBracketInserter);
if (fPropertyChangeListener != null) {
Preferences preferences= JavaCore.getPlugin().getPluginPreferences();
preferences.removePropertyChangeListener(fPropertyChangeListener);
fPropertyChangeListener= null;
}
if (fJavaEditorErrorTickUpdater != null) {
fJavaEditorErrorTickUpdater.dispose();
fJavaEditorErrorTickUpdater= null;
}
if (fSelectionHistory != null)
fSelectionHistory.dispose();
if (fPaintManager != null) {
fPaintManager.dispose();
fPaintManager= null;
}
if (fActionGroups != null)
fActionGroups.dispose();
super.dispose();
}
/*
* @see AbstractTextEditor#createPartControl(Composite)
*/
public void createPartControl(Composite parent) {
super.createPartControl(parent);
fPaintManager= new PaintManager(getSourceViewer());
if (isBracketHighlightingEnabled())
startBracketHighlighting();
if (isLineHighlightingEnabled())
startLineHighlighting();
if (isPrintMarginVisible())
showPrintMargin();
Iterator e= ANNOTATION_MAP.keySet().iterator();
while (e.hasNext()) {
AnnotationType type= (AnnotationType) e.next();
if (isAnnotationIndicationEnabled(type))
startAnnotationIndication(type);
}
if (isTabConversionEnabled())
startTabConversion();
if (isOverviewRulerVisible())
showOverviewRuler();
Preferences preferences= JavaCore.getPlugin().getPluginPreferences();
preferences.addPropertyChangeListener(fPropertyChangeListener);
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 getPeerCharacter(char character) {
switch (character) {
case '(':
return ')';
case ')':
return '(';
case '[':
return ']';
case ']':
return '[';
case '"':
return character;
default:
throw new IllegalArgumentException();
}
}
private static class ExitPolicy implements LinkedPositionUI.ExitPolicy {
final char fExitCharacter;
public ExitPolicy(char exitCharacter) {
fExitCharacter= exitCharacter;
}
/*
* @see org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI.ExitPolicy#doExit(org.eclipse.jdt.internal.ui.text.link.LinkedPositionManager, org.eclipse.swt.events.VerifyEvent, int, int)
*/
public ExitFlags doExit(LinkedPositionManager manager, VerifyEvent event, int offset, int length) {
if (event.character == fExitCharacter) {
if (manager.anyPositionIncludes(offset, length))
return new ExitFlags(LinkedPositionUI.COMMIT| LinkedPositionUI.UPDATE_CARET, false);
else
return new ExitFlags(LinkedPositionUI.COMMIT, true);
}
switch (event.character) {
case '\b':
if (manager.getFirstPosition().length == 0)
return new ExitFlags(0, false);
else
return null;
case '\n':
case '\r':
return new ExitFlags(LinkedPositionUI.COMMIT, true);
default:
return null;
}
}
}
private class BracketInserter implements VerifyKeyListener, LinkedPositionUI.ExitListener {
private boolean fCloseBrackets= true;
private boolean fCloseStrings= true;
private int fOffset;
private int fLength;
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)
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;
}
try {
ITypedRegion partition= document.getPartition(offset);
if (! IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType()) && partition.getOffset() != offset)
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());
LinkedPositionManager manager= new LinkedPositionManager(document);
manager.addPosition(offset + 1, 0);
fOffset= offset;
fLength= 2;
LinkedPositionUI editor= new LinkedPositionUI(sourceViewer, manager);
editor.setCancelListener(this);
editor.setExitPolicy(new ExitPolicy(closingCharacter));
editor.setFinalCaretOffset(offset + 2);
editor.enter();
IRegion newSelection= editor.getSelectedRegion();
sourceViewer.setSelectedRange(newSelection.getOffset(), newSelection.getLength());
event.doit= false;
} catch (BadLocationException e) {
}
break;
}
}
/*
* @see org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI.ExitListener#exit(boolean)
*/
public void exit(boolean accept) {
if (accept)
return;
// remove brackets
try {
final ISourceViewer sourceViewer= getSourceViewer();
IDocument document= sourceViewer.getDocument();
document.replace(fOffset, fLength, null);
} catch (BadLocationException e) {
}
}
}
protected AnnotationType getAnnotationType(String preferenceKey) {
Iterator e= ANNOTATION_MAP.keySet().iterator();
while (e.hasNext()) {
AnnotationType type= (AnnotationType) e.next();
AnnotationInfo info= (AnnotationInfo) ANNOTATION_MAP.get(type);
if (info != null) {
if (preferenceKey.equals(info.fColorPreference) || preferenceKey.equals(info.fEditorPreference) || preferenceKey.equals(info.fOverviewRulerPreference))
return type;
}
}
return null;
}
/*
* @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 (MATCHING_BRACKETS.equals(p)) {
if (isBracketHighlightingEnabled())
startBracketHighlighting();
else
stopBracketHighlighting();
return;
}
if (MATCHING_BRACKETS_COLOR.equals(p)) {
if (fBracketPainter != null)
fBracketPainter.setHighlightColor(getColor(MATCHING_BRACKETS_COLOR));
return;
}
if (CURRENT_LINE.equals(p)) {
if (isLineHighlightingEnabled())
startLineHighlighting();
else
stopLineHighlighting();
return;
}
if (CURRENT_LINE_COLOR.equals(p)) {
if (fLinePainter != null) {
stopLineHighlighting();
startLineHighlighting();
}
return;
}
if (PRINT_MARGIN.equals(p)) {
if (isPrintMarginVisible())
showPrintMargin();
else
hidePrintMargin();
return;
}
if (PRINT_MARGIN_COLOR.equals(p)) {
if (fPrintMarginPainter != null)
fPrintMarginPainter.setMarginRulerColor(getColor(PRINT_MARGIN_COLOR));
return;
}
if (PRINT_MARGIN_COLUMN.equals(p)) {
if (fPrintMarginPainter != null)
fPrintMarginPainter.setMarginRulerColumn(getPreferenceStore().getInt(PRINT_MARGIN_COLUMN));
return;
}
if (OVERVIEW_RULER.equals(p)) {
if (isOverviewRulerVisible())
showOverviewRuler();
else
hideOverviewRuler();
return;
}
AnnotationType type= getAnnotationType(p);
if (type != null) {
AnnotationInfo info= (AnnotationInfo) ANNOTATION_MAP.get(type);
if (info.fColorPreference.equals(p)) {
Color color= getColor(type);
if (fProblemPainter != null) {
fProblemPainter.setColor(type, color);
fProblemPainter.paint(IPainter.CONFIGURATION);
}
setColorInOverviewRuler(type, color);
return;
}
if (info.fEditorPreference.equals(p)) {
if (isAnnotationIndicationEnabled(type))
startAnnotationIndication(type);
else
stopAnnotationIndication(type);
return;
}
if (info.fOverviewRulerPreference.equals(p)) {
if (isAnnotationIndicationInOverviewRulerEnabled(type))
showAnnotationIndicationInOverviewRuler(type, true);
else
showAnnotationIndicationInOverviewRuler(type, false);
return;
}
}
IContentAssistant c= asv.getContentAssistant();
if (c instanceof ContentAssistant)
ContentAssistPreference.changeConfiguration((ContentAssistant) c, getPreferenceStore(), event);
}
} finally {
super.handlePreferenceStoreChanged(event);
}
}
/**
* 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) {
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());
}
}
}
/*
* @see AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent)
*/
protected boolean affectsTextPresentation(PropertyChangeEvent event) {
String p= event.getProperty();
boolean affects=MATCHING_BRACKETS_COLOR.equals(p) || CURRENT_LINE_COLOR.equals(p) ||
ERROR_INDICATION_COLOR.equals(p) || WARNING_INDICATION_COLOR.equals(p) || TASK_INDICATION_COLOR.equals(p);
return affects ? affects : super.affectsTextPresentation(event);
}
/*
* @see JavaEditor#createJavaSourceViewer(Composite, IVerticalRuler, int)
*/
protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler ruler, int styles) {
return new AdaptedSourceViewer(parent, ruler, styles);
}
/*
* @see JavaEditor#synchronizeOutlinePageSelection()
*/
public void synchronizeOutlinePageSelection() {
if (isEditingScriptRunning())
return;
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null || fOutlinePage == null)
return;
StyledText styledText= sourceViewer.getTextWidget();
if (styledText == null)
return;
int modelCaret= 0;
if (sourceViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) sourceViewer;
modelCaret= extension.widgetOffset2ModelOffset(styledText.getCaretOffset());
} else {
int offset= sourceViewer.getVisibleRegion().getOffset();
modelCaret= offset + styledText.getCaretOffset();
}
IJavaElement element= getElementAt(modelCaret, false);
ISourceReference reference= getSourceReference(element, modelCaret);
if (reference != null) {
fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener);
fOutlinePage.select(reference);
fOutlinePage.addSelectionChangedListener(fSelectionChangedListener);
}
}
private ISourceReference getSourceReference(IJavaElement element, int offset) {
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() == offset)
return container;
}
return (ISourceReference) element;
}
/*
* @see IReconcilingParticipant#reconciled()
*/
public void reconciled() {
if (!JavaEditorPreferencePage.synchronizeOutlineOnCursorMove()) {
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);
}
}
|
28,875 |
Bug 28875 Refactor - Change method signature [refactoring]
|
I tried it, and this is what I got in the log : java.lang.reflect.InvocationTargetException: java.lang.ClassCastException: org.eclipse.jdt.internal.core.SourceField at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactoring .getMethod(ChangeSignatureRefactoring.java:1081) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactoring .needsVisibilityUpdate(ChangeSignatureRefactoring.java:1085) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactoring .updateDeclarationNode(ChangeSignatureRefactoring.java:962) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactoring .modifyMethodOccurrences(ChangeSignatureRefactoring.java:946) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactoring .createChangeManager(ChangeSignatureRefactoring.java:807) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactoring .checkInput(ChangeSignatureRefactoring.java:476) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:59) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:94) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:95) !ENTRY org.eclipse.jdt.ui 4 10001 26, 2002 17:14:18.437 !MESSAGE Internal Error
|
resolved fixed
|
89c1e22
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-07T14:34:06Z | 2002-12-26T13:40:00Z |
org.eclipse.jdt.ui/core
| |
28,875 |
Bug 28875 Refactor - Change method signature [refactoring]
|
I tried it, and this is what I got in the log : java.lang.reflect.InvocationTargetException: java.lang.ClassCastException: org.eclipse.jdt.internal.core.SourceField at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactoring .getMethod(ChangeSignatureRefactoring.java:1081) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactoring .needsVisibilityUpdate(ChangeSignatureRefactoring.java:1085) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactoring .updateDeclarationNode(ChangeSignatureRefactoring.java:962) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactoring .modifyMethodOccurrences(ChangeSignatureRefactoring.java:946) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactoring .createChangeManager(ChangeSignatureRefactoring.java:807) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactoring .checkInput(ChangeSignatureRefactoring.java:476) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:59) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:94) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:95) !ENTRY org.eclipse.jdt.ui 4 10001 26, 2002 17:14:18.437 !MESSAGE Internal Error
|
resolved fixed
|
89c1e22
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-07T14:34:06Z | 2002-12-26T13:40:00Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ChangeSignatureRefactoring.java
| |
28,869 |
Bug 28869 Parse error with final local vars without immediate assignment
|
Consider this prototype code: void foo() { final PreparedStatement statement; try { statement = xxx.prepareStatement(...) } catch (..) { // handle errors } return statement; } For this kind of thing I often use a final local variable - mostly to enable the compiler to find my errors (like assigning more than once). However, with Eclipse I get parse errors (cursor on the line that declares the local var) when using refactoring functions, such as "Reorganize imports". The Eclipse version used is Eclipse 2.1 M4.
|
verified fixed
|
a58f54a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-07T17:13:55Z | 2002-12-25T09:53:20Z |
org.eclipse.jdt.ui/core
| |
28,869 |
Bug 28869 Parse error with final local vars without immediate assignment
|
Consider this prototype code: void foo() { final PreparedStatement statement; try { statement = xxx.prepareStatement(...) } catch (..) { // handle errors } return statement; } For this kind of thing I often use a final local variable - mostly to enable the compiler to find my errors (like assigning more than once). However, with Eclipse I get parse errors (cursor on the line that declares the local var) when using refactoring functions, such as "Reorganize imports". The Eclipse version used is Eclipse 2.1 M4.
|
verified fixed
|
a58f54a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-07T17:13:55Z | 2002-12-25T09:53:20Z |
extension/org/eclipse/jdt/internal/corext/codemanipulation/OrganizeImportsOperation.java
| |
28,869 |
Bug 28869 Parse error with final local vars without immediate assignment
|
Consider this prototype code: void foo() { final PreparedStatement statement; try { statement = xxx.prepareStatement(...) } catch (..) { // handle errors } return statement; } For this kind of thing I often use a final local variable - mostly to enable the compiler to find my errors (like assigning more than once). However, with Eclipse I get parse errors (cursor on the line that declares the local var) when using refactoring functions, such as "Reorganize imports". The Eclipse version used is Eclipse 2.1 M4.
|
verified fixed
|
a58f54a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-07T17:13:55Z | 2002-12-25T09:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/OrganizeImportsAction.java
|
/*******************************************************************************
* Copyright (c) 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.ui.actions;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.ui.IEditorActionBarContributor;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.EditorActionBarContributor;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.corext.ValidateEditException;
import org.eclipse.jdt.internal.corext.codemanipulation.OrganizeImportsOperation;
import org.eclipse.jdt.internal.corext.codemanipulation.OrganizeImportsOperation.IChooseImportQuery;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.corext.util.TypeInfo;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.ActionMessages;
import org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter;
import org.eclipse.jdt.internal.ui.dialogs.MultiElementListSelectionDialog;
import org.eclipse.jdt.internal.ui.dialogs.ProblemDialog;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext;
import org.eclipse.jdt.internal.ui.util.ElementValidator;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.util.TypeInfoLabelProvider;
import org.eclipse.jdt.ui.IWorkingCopyManager;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
/**
* Organizes the imports of a compilation unit.
* <p>
* The action is applicable to selections containing elements of
* type <code>ICompilationUnit</code> or <code>IPackage
* </code>.
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 2.0
*/
public class OrganizeImportsAction extends SelectionDispatchAction {
private JavaEditor fEditor;
/* (non-Javadoc)
* Class implements IObjectActionDelegate
*/
public static class ObjectDelegate implements IObjectActionDelegate {
private OrganizeImportsAction fAction;
public void setActivePart(IAction action, IWorkbenchPart targetPart) {
fAction= new OrganizeImportsAction(targetPart.getSite());
}
public void run(IAction action) {
fAction.run();
}
public void selectionChanged(IAction action, ISelection selection) {
if (fAction == null)
action.setEnabled(false);
}
}
/**
* Creates a new <code>OrganizeImportsAction</code>. The action requires
* that the selection provided by the site's selection provider is of type <code>
* org.eclipse.jface.viewers.IStructuredSelection</code>.
*
* @param site the site providing context information for this action
*/
public OrganizeImportsAction(IWorkbenchSite site) {
super(site);
setText(ActionMessages.getString("OrganizeImportsAction.label")); //$NON-NLS-1$
setToolTipText(ActionMessages.getString("OrganizeImportsAction.tooltip")); //$NON-NLS-1$
setDescription(ActionMessages.getString("OrganizeImportsAction.description")); //$NON-NLS-1$
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.ORGANIZE_IMPORTS_ACTION);
}
/**
* Note: This constructor is for internal use only. Clients should not call this constructor.
*/
public OrganizeImportsAction(JavaEditor editor) {
this(editor.getEditorSite());
fEditor= editor;
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
protected void selectionChanged(ITextSelection selection) {
// do nothing
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
protected void selectionChanged(IStructuredSelection selection) {
setEnabled(isEnabled(selection));
}
private ICompilationUnit[] getCompilationUnits(IStructuredSelection selection) {
HashSet result= new HashSet();
Object[] selected= selection.toArray();
for (int i= 0; i < selected.length; i++) {
try {
if (selected[i] instanceof IJavaElement) {
IJavaElement elem= (IJavaElement) selected[i];
switch (elem.getElementType()) {
case IJavaElement.COMPILATION_UNIT:
result.add(elem);
break;
case IJavaElement.IMPORT_CONTAINER:
result.add(elem.getParent());
break;
case IJavaElement.PACKAGE_FRAGMENT:
collectCompilationUnits((IPackageFragment) elem, result);
break;
case IJavaElement.PACKAGE_FRAGMENT_ROOT:
collectCompilationUnits((IPackageFragmentRoot) elem, result);
break;
case IJavaElement.JAVA_PROJECT:
IPackageFragmentRoot[] roots= ((IJavaProject) elem).getPackageFragmentRoots();
for (int k= 0; k < roots.length; k++) {
collectCompilationUnits(roots[i], result);
}
break;
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
return (ICompilationUnit[]) result.toArray(new ICompilationUnit[result.size()]);
}
private void collectCompilationUnits(IPackageFragment pack, Collection result) throws JavaModelException {
result.addAll(Arrays.asList(pack.getCompilationUnits()));
}
private void collectCompilationUnits(IPackageFragmentRoot root, Collection result) throws JavaModelException {
if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
IJavaElement[] children= root.getChildren();
for (int i= 0; i < children.length; i++) {
collectCompilationUnits((IPackageFragment) children[i], result);
}
}
}
private boolean isEnabled(IStructuredSelection selection) {
Object[] selected= selection.toArray();
for (int i= 0; i < selected.length; i++) {
try {
if (selected[i] instanceof IJavaElement) {
IJavaElement elem= (IJavaElement) selected[i];
switch (elem.getElementType()) {
case IJavaElement.COMPILATION_UNIT:
return true;
case IJavaElement.IMPORT_CONTAINER:
return true;
case IJavaElement.PACKAGE_FRAGMENT:
case IJavaElement.PACKAGE_FRAGMENT_ROOT:
IPackageFragmentRoot root= (IPackageFragmentRoot) elem.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
return (root.getKind() == IPackageFragmentRoot.K_SOURCE);
case IJavaElement.JAVA_PROJECT:
return hasSourceFolders((IJavaProject) elem);
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
return false;
}
private boolean hasSourceFolders(IJavaProject project) throws JavaModelException {
IPackageFragmentRoot[] roots= project.getPackageFragmentRoots();
for (int i= 0; i < roots.length; i++) {
IPackageFragmentRoot root= roots[i];
if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
return true;
}
}
return false;
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
protected void run(ITextSelection selection) {
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
ICompilationUnit cu= manager.getWorkingCopy(fEditor.getEditorInput());
runOnSingle(cu, true, true);
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
protected void run(IStructuredSelection selection) {
ICompilationUnit[] cus= getCompilationUnits(selection);
if (cus.length == 1) {
runOnSingle(cus[0], true, false);
} else {
runOnMultiple(cus, true);
}
}
private void runOnMultiple(final ICompilationUnit[] cus, final boolean doResolve) {
try {
String message= ActionMessages.getString("OrganizeImportsAction.multi.status.description"); //$NON-NLS-1$
final MultiStatus status= new MultiStatus(JavaUI.ID_PLUGIN, Status.OK, message, null);
ProgressMonitorDialog dialog= new ProgressMonitorDialog(getShell());
dialog.run(false, true, new WorkbenchRunnableAdapter(new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) {
doRunOnMultiple(cus, status, doResolve, monitor);
}
}));
if (!status.isOK()) {
String title= ActionMessages.getString("OrganizeImportsAction.multi.status.title"); //$NON-NLS-1$
ProblemDialog.open(getShell(), title, null, status);
}
} catch (InvocationTargetException e) {
ExceptionHandler.handle(e, getShell(), ActionMessages.getString("OrganizeImportsAction.error.title"), ActionMessages.getString("OrganizeImportsAction.error.message")); //$NON-NLS-1$ //$NON-NLS-2$
} catch (InterruptedException e) {
// cancelled by user
}
}
private void doRunOnMultiple(ICompilationUnit[] cus, MultiStatus status, boolean doResolve, IProgressMonitor monitor) throws OperationCanceledException {
final class OrganizeImportError extends Error {
}
if (monitor == null) {
monitor= new NullProgressMonitor();
}
monitor.beginTask(ActionMessages.getString("OrganizeImportsAction.multi.op.description"), cus.length); //$NON-NLS-1$
try {
IPreferenceStore store= PreferenceConstants.getPreferenceStore();
String[] prefOrder= JavaPreferencesSettings.getImportOrderPreference(store);
int threshold= JavaPreferencesSettings.getImportNumberThreshold(store);
boolean ignoreLowerCaseNames= store.getBoolean(PreferenceConstants.ORGIMPORTS_IGNORELOWERCASE);
IChooseImportQuery query= new IChooseImportQuery() {
public TypeInfo[] chooseImports(TypeInfo[][] openChoices, ISourceRange[] ranges) {
throw new OrganizeImportError();
}
};
for (int i= 0; i < cus.length; i++) {
ICompilationUnit cu= cus[i];
String cuLocation= cu.getPath().makeRelative().toString();
try {
cu= JavaModelUtil.toWorkingCopy(cu);
monitor.subTask(cuLocation);
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, prefOrder, threshold, ignoreLowerCaseNames, !cu.isWorkingCopy(), doResolve, query);
op.run(new SubProgressMonitor(monitor, 1));
if (monitor.isCanceled()) {
throw new OperationCanceledException();
}
ISourceRange errorRange= op.getErrorSourceRange();
if (errorRange != null) {
String message= ActionMessages.getFormattedString("OrganizeImportsAction.multi.error.parse", cuLocation); //$NON-NLS-1$
status.add(new Status(Status.INFO, JavaUI.ID_PLUGIN, Status.ERROR, message, null));
}
} catch (OrganizeImportError e) {
String message= ActionMessages.getFormattedString("OrganizeImportsAction.multi.error.unresolvable", cuLocation); //$NON-NLS-1$
status.add(new Status(Status.INFO, JavaUI.ID_PLUGIN, Status.ERROR, message, null));
} catch (ValidateEditException e) {
status.add(e.getStatus());
} catch (CoreException e) {
JavaPlugin.log(e);
String message= ActionMessages.getFormattedString("OrganizeImportsAction.multi.error.unexpected", e.getStatus().getMessage()); //$NON-NLS-1$
status.add(new Status(Status.ERROR, JavaUI.ID_PLUGIN, Status.ERROR, message, null));
}
}
} finally {
monitor.done();
}
}
private void runOnSingle(ICompilationUnit cu, boolean doResolve, boolean inEditor) {
if (!ElementValidator.check(cu, getShell(), ActionMessages.getString("OrganizeImportsAction.error.title"), inEditor)) //$NON-NLS-1$
return;
try {
IPreferenceStore store= PreferenceConstants.getPreferenceStore();
String[] prefOrder= JavaPreferencesSettings.getImportOrderPreference(store);
int threshold= JavaPreferencesSettings.getImportNumberThreshold(store);
boolean ignoreLowerCaseNames= store.getBoolean(PreferenceConstants.ORGIMPORTS_IGNORELOWERCASE);
if (!cu.isWorkingCopy()) {
IEditorPart editor= EditorUtility.openInEditor(cu);
if (editor instanceof JavaEditor) {
fEditor= (JavaEditor) editor;
}
cu= JavaModelUtil.toWorkingCopy(cu);
}
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, prefOrder, threshold, ignoreLowerCaseNames, !cu.isWorkingCopy(), doResolve, createChooseImportQuery());
BusyIndicatorRunnableContext context= new BusyIndicatorRunnableContext();
context.run(false, true, new WorkbenchRunnableAdapter(op));
ISourceRange errorRange= op.getErrorSourceRange();
if (errorRange != null) {
MessageDialog.openInformation(getShell(), ActionMessages.getString("OrganizeImportsAction.error.title"), ActionMessages.getString("OrganizeImportsAction.single.error.parse")); //$NON-NLS-1$ //$NON-NLS-2$
if (fEditor != null) {
fEditor.selectAndReveal(errorRange.getOffset(), errorRange.getLength());
}
} else {
if (fEditor != null) {
setStatusBarMessage(getOrganizeInfo(op));
}
}
} catch (CoreException e) {
ExceptionHandler.handle(e, getShell(), ActionMessages.getString("OrganizeImportsAction.error.title"), ActionMessages.getString("OrganizeImportsAction.error.message")); //$NON-NLS-1$ //$NON-NLS-2$
} catch (InvocationTargetException e) {
ExceptionHandler.handle(e, getShell(), ActionMessages.getString("OrganizeImportsAction.error.title"), ActionMessages.getString("OrganizeImportsAction.error.message")); //$NON-NLS-1$ //$NON-NLS-2$
} catch (InterruptedException e) {
}
}
private String getOrganizeInfo(OrganizeImportsOperation op) {
int nImportsAdded= op.getNumberOfImportsAdded();
if (nImportsAdded >= 0) {
return ActionMessages.getFormattedString("OrganizeImportsAction.summary_added", String.valueOf(nImportsAdded)); //$NON-NLS-1$
} else {
return ActionMessages.getFormattedString("OrganizeImportsAction.summary_removed", String.valueOf(-nImportsAdded)); //$NON-NLS-1$
}
}
private IChooseImportQuery createChooseImportQuery() {
return new IChooseImportQuery() {
public TypeInfo[] chooseImports(TypeInfo[][] openChoices, ISourceRange[] ranges) {
return doChooseImports(openChoices, ranges);
}
};
}
private TypeInfo[] doChooseImports(TypeInfo[][] openChoices, final ISourceRange[] ranges) {
// remember selection
ISelection sel= fEditor.getSelectionProvider().getSelection();
TypeInfo[] result= null;;
ILabelProvider labelProvider= new TypeInfoLabelProvider(TypeInfoLabelProvider.SHOW_FULLYQUALIFIED);
MultiElementListSelectionDialog dialog= new MultiElementListSelectionDialog(getShell(), labelProvider) {
protected void handleSelectionChanged() {
super.handleSelectionChanged();
// show choices in editor
doListSelectionChanged(getCurrentPage(), ranges);
}
};
dialog.setTitle(ActionMessages.getString("OrganizeImportsAction.selectiondialog.title")); //$NON-NLS-1$
dialog.setMessage(ActionMessages.getString("OrganizeImportsAction.selectiondialog.message")); //$NON-NLS-1$
dialog.setElements(openChoices);
if (dialog.open() == Window.OK) {
Object[] res= dialog.getResult();
result= new TypeInfo[res.length];
for (int i= 0; i < res.length; i++) {
Object[] array= (Object[]) res[i];
if (array.length > 0)
result[i]= (TypeInfo) array[0];
}
}
// restore selection
if (sel instanceof ITextSelection) {
ITextSelection textSelection= (ITextSelection) sel;
fEditor.selectAndReveal(textSelection.getOffset(), textSelection.getLength());
}
return result;
}
private void doListSelectionChanged(int page, ISourceRange[] ranges) {
if (page >= 0 && page < ranges.length) {
ISourceRange range= ranges[page];
fEditor.selectAndReveal(range.getOffset(), range.getLength());
}
}
private void setStatusBarMessage(String message) {
IEditorActionBarContributor contributor= fEditor.getEditorSite().getActionBarContributor();
if (contributor instanceof EditorActionBarContributor) {
IStatusLineManager manager= ((EditorActionBarContributor) contributor).getActionBars().getStatusLineManager();
manager.setMessage(message);
}
}
}
|
28,250 |
Bug 28250 opening a file calls getImage 2 times on packageExplorer's label provider [package explorer]
|
20021210 what is the reason for the package explorer to update its labels on opening/closing files? No resource has changed, nothing really happened - but stuff gets updated anyhow. it's called twice on opening and once on closing closing: Thread [main] (Suspended (breakpoint at line 67 in org.eclipse.jface.viewers.DecoratingLabelProvider)) org.eclipse.jface.viewers.DecoratingLabelProvider.getImage (java.lang.Object) line: 67 org.eclipse.jdt.internal.ui.packageview.PackageExplorerPart$4 (org.eclipse.jface.viewers.TreeViewer).doUpdateItem (org.eclipse.swt.widgets.Item, java.lang.Object) line: 83 org.eclipse.jdt.internal.ui.packageview.PackageExplorerPart$4 (org.eclipse.jface.viewers.AbstractTreeViewer).doUpdateItem (org.eclipse.swt.widgets.Widget, java.lang.Object, boolean) line: 363 org.eclipse.jdt.internal.ui.packageview.PackageExplorerPart$4 (org.eclipse.jface.viewers.StructuredViewer).updateItem (org.eclipse.swt.widgets.Widget, java.lang.Object) line: 1132 org.eclipse.jdt.internal.ui.packageview.PackageExplorerPart$4 (org.eclipse.jface.viewers.AbstractTreeViewer).internalRefresh (org.eclipse.swt.widgets.Widget, java.lang.Object, boolean) line: 843 org.eclipse.jdt.internal.ui.packageview.PackageExplorerPart$4 (org.eclipse.jface.viewers.AbstractTreeViewer).internalRefresh (java.lang.Object) line: 826 org.eclipse.jface.viewers.StructuredViewer$4.run() line: 744 org.eclipse.jdt.internal.ui.packageview.PackageExplorerPart$4 (org.eclipse.jface.viewers.StructuredViewer).preservingSelection (java.lang.Runnable) line: 684 org.eclipse.jdt.internal.ui.packageview.PackageExplorerPart$4 (org.eclipse.jface.viewers.StructuredViewer).refresh(java.lang.Object) line: 742 org.eclipse.jdt.internal.ui.packageview.PackageExplorerContentProvider$3 .run() line: 440 org.eclipse.swt.widgets.RunnableLock.run() line: 31 org.eclipse.ui.internal.UISynchronizer (org.eclipse.swt.widgets.Synchronizer).runAsyncMessages() line: 94 org.eclipse.swt.widgets.Display.runAsyncMessages() line: 1669 org.eclipse.swt.widgets.Display.readAndDispatch() line: 1414 org.eclipse.ui.internal.Workbench.runEventLoop() line: 1403 org.eclipse.ui.internal.Workbench.run(java.lang.Object) line: 1386 org.eclipse.core.internal.boot.InternalBootLoader.run(java.lang.String, java.net.URL, java.lang.String, java.lang.String[], java.lang.Runnable) line: 840 org.eclipse.core.boot.BootLoader.run(java.lang.String, java.net.URL, java.lang.String, java.lang.String[], java.lang.Runnable) line: 462 sun.reflect.NativeMethodAccessorImpl.invoke0(java.lang.reflect.Method, java.lang.Object, java.lang.Object[]) line: not available [native method] sun.reflect.NativeMethodAccessorImpl.invoke(java.lang.Object, java.lang.Object[]) line: 39 sun.reflect.DelegatingMethodAccessorImpl.invoke(java.lang.Object, java.lang.Object[]) line: 25 java.lang.reflect.Method.invoke(java.lang.Object, java.lang.Object[]) line: 324 org.eclipse.core.launcher.Main.basicRun(java.lang.String[]) line: 247 org.eclipse.core.launcher.Main.run(java.lang.String[]) line: 703 org.eclipse.core.launcher.Main.main(java.lang.String[]) line: 539 ---------------------------- opening 1 : Thread [main] (Suspended (breakpoint at line 67 in org.eclipse.jface.viewers.DecoratingLabelProvider)) org.eclipse.jface.viewers.DecoratingLabelProvider.getImage (java.lang.Object) line: 67 org.eclipse.jdt.internal.ui.packageview.PackageExplorerPart$4 (org.eclipse.jface.viewers.TreeViewer).doUpdateItem (org.eclipse.swt.widgets.Item, java.lang.Object) line: 83 org.eclipse.jdt.internal.ui.packageview.PackageExplorerPart$4 (org.eclipse.jface.viewers.AbstractTreeViewer).doUpdateItem (org.eclipse.swt.widgets.Widget, java.lang.Object, boolean) line: 363 org.eclipse.jdt.internal.ui.packageview.PackageExplorerPart$4 (org.eclipse.jface.viewers.StructuredViewer).updateItem (org.eclipse.swt.widgets.Widget, java.lang.Object) line: 1132 org.eclipse.jdt.internal.ui.packageview.PackageExplorerPart$4 (org.eclipse.jface.viewers.AbstractTreeViewer).internalRefresh (org.eclipse.swt.widgets.Widget, java.lang.Object, boolean) line: 843 org.eclipse.jdt.internal.ui.packageview.PackageExplorerPart$4 (org.eclipse.jface.viewers.AbstractTreeViewer).internalRefresh (java.lang.Object) line: 826 org.eclipse.jface.viewers.StructuredViewer$4.run() line: 744 org.eclipse.jdt.internal.ui.packageview.PackageExplorerPart$4 (org.eclipse.jface.viewers.StructuredViewer).preservingSelection (java.lang.Runnable) line: 684 org.eclipse.jdt.internal.ui.packageview.PackageExplorerPart$4 (org.eclipse.jface.viewers.StructuredViewer).refresh(java.lang.Object) line: 742 org.eclipse.jdt.internal.ui.packageview.PackageExplorerContentProvider$3 .run() line: 440 org.eclipse.swt.widgets.RunnableLock.run() line: 31 org.eclipse.ui.internal.UISynchronizer (org.eclipse.swt.widgets.Synchronizer).runAsyncMessages() line: 94 org.eclipse.swt.widgets.Display.runAsyncMessages() line: 1669 org.eclipse.swt.widgets.Display.readAndDispatch() line: 1414 org.eclipse.jface.operation.ModalContext$ModalContextThread.block() line: 130 org.eclipse.jface.operation.ModalContext.run (org.eclipse.jface.operation.IRunnableWithProgress, boolean, org.eclipse.core.runtime.IProgressMonitor, org.eclipse.swt.widgets.Display) line: 255 org.eclipse.jface.window.ApplicationWindow$1.run() line: 409 org.eclipse.swt.custom.BusyIndicator.showWhile (org.eclipse.swt.widgets.Display, java.lang.Runnable) line: 65 org.eclipse.ui.internal.WorkbenchWindow (org.eclipse.jface.window.ApplicationWindow).run(boolean, boolean, org.eclipse.jface.operation.IRunnableWithProgress) line: 406 org.eclipse.ui.internal.WorkbenchWindow.run(boolean, boolean, org.eclipse.jface.operation.IRunnableWithProgress) line: 1147 org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor (org.eclipse.ui.texteditor.AbstractTextEditor).internalInit (org.eclipse.ui.IWorkbenchWindow, org.eclipse.ui.IEditorSite, org.eclipse.ui.IEditorInput) line: 1774 org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor (org.eclipse.ui.texteditor.AbstractTextEditor).init(org.eclipse.ui.IEditorSite, org.eclipse.ui.IEditorInput) line: 1791 org.eclipse.ui.internal.EditorManager.createSite (org.eclipse.ui.IEditorPart, org.eclipse.ui.internal.registry.EditorDescriptor, org.eclipse.ui.IEditorInput) line: 571 org.eclipse.ui.internal.EditorManager.openInternalEditor (org.eclipse.ui.IEditorReference, org.eclipse.ui.internal.registry.EditorDescriptor, org.eclipse.ui.IEditorInput, boolean) line: 621 org.eclipse.ui.internal.EditorManager.openEditorFromDescriptor (org.eclipse.ui.IEditorReference, org.eclipse.ui.internal.registry.EditorDescriptor, org.eclipse.ui.IEditorInput, boolean) line: 429 org.eclipse.ui.internal.EditorManager.openEditorFromInput (org.eclipse.ui.IEditorReference, org.eclipse.ui.IEditorInput, boolean, boolean) line: 303 org.eclipse.ui.internal.EditorManager.openEditor(java.lang.String, org.eclipse.ui.IEditorInput, boolean, boolean) line: 394 org.eclipse.ui.internal.WorkbenchPage.openEditor (org.eclipse.ui.IEditorInput, java.lang.String, boolean, boolean, org.eclipse.core.resources.IFile, boolean) line: 1863 org.eclipse.ui.internal.WorkbenchPage.openEditor (org.eclipse.core.resources.IFile, java.lang.String, boolean) line: 1700 org.eclipse.jdt.internal.ui.javaeditor.EditorUtility.openInEditor (org.eclipse.core.resources.IFile, boolean) line: 129 org.eclipse.jdt.internal.ui.javaeditor.EditorUtility.openInEditor (java.lang.Object, boolean) line: 107 org.eclipse.jdt.internal.ui.actions.OpenActionUtil.open (java.lang.Object, boolean) line: 47 org.eclipse.jdt.ui.actions.OpenAction.run(java.lang.Object[]) line: 157 org.eclipse.jdt.ui.actions.OpenAction.run (org.eclipse.jface.viewers.IStructuredSelection) line: 146 org.eclipse.jdt.ui.actions.OpenAction (org.eclipse.jdt.ui.actions.SelectionDispatchAction).dispatchRun (org.eclipse.jface.viewers.ISelection) line: 191 org.eclipse.jdt.ui.actions.OpenAction (org.eclipse.jdt.ui.actions.SelectionDispatchAction).run() line: 169 org.eclipse.jdt.internal.ui.packageview.PackageExplorerActionGroup.handl eOpen(org.eclipse.jface.viewers.OpenEvent) line: 325 org.eclipse.jdt.internal.ui.packageview.PackageExplorerPart$3.open (org.eclipse.jface.viewers.OpenEvent) line: 298 org.eclipse.jdt.internal.ui.packageview.PackageExplorerPart$4 (org.eclipse.jface.viewers.StructuredViewer).fireOpen (org.eclipse.jface.viewers.OpenEvent) line: 316 org.eclipse.jdt.internal.ui.packageview.PackageExplorerPart$4 (org.eclipse.jface.viewers.StructuredViewer).handleOpen (org.eclipse.swt.events.SelectionEvent) line: 490 org.eclipse.jface.viewers.StructuredViewer$3.handleOpen (org.eclipse.swt.events.SelectionEvent) line: 577 org.eclipse.jface.util.OpenStrategy.fireOpenEvent (org.eclipse.swt.events.SelectionEvent) line: 203 org.eclipse.jface.util.OpenStrategy.access$2 (org.eclipse.jface.util.OpenStrategy, org.eclipse.swt.events.SelectionEvent) line: 198 org.eclipse.jface.util.OpenStrategy$1.handleEvent (org.eclipse.swt.widgets.Event) line: 227 org.eclipse.swt.widgets.EventTable.sendEvent (org.eclipse.swt.widgets.Event) line: 77 org.eclipse.swt.widgets.Tree(org.eclipse.swt.widgets.Widget).sendEvent (org.eclipse.swt.widgets.Event) line: 825 org.eclipse.swt.widgets.Display.runDeferredEvents() line: 1692 org.eclipse.swt.widgets.Display.readAndDispatch() line: 1410 org.eclipse.ui.internal.Workbench.runEventLoop() line: 1403 org.eclipse.ui.internal.Workbench.run(java.lang.Object) line: 1386 org.eclipse.core.internal.boot.InternalBootLoader.run(java.lang.String, java.net.URL, java.lang.String, java.lang.String[], java.lang.Runnable) line: 840 org.eclipse.core.boot.BootLoader.run(java.lang.String, java.net.URL, java.lang.String, java.lang.String[], java.lang.Runnable) line: 462 sun.reflect.NativeMethodAccessorImpl.invoke0(java.lang.reflect.Method, java.lang.Object, java.lang.Object[]) line: not available [native method] sun.reflect.NativeMethodAccessorImpl.invoke(java.lang.Object, java.lang.Object[]) line: 39 sun.reflect.DelegatingMethodAccessorImpl.invoke(java.lang.Object, java.lang.Object[]) line: 25 java.lang.reflect.Method.invoke(java.lang.Object, java.lang.Object[]) line: 324 org.eclipse.core.launcher.Main.basicRun(java.lang.String[]) line: 247 org.eclipse.core.launcher.Main.run(java.lang.String[]) line: 703 org.eclipse.core.launcher.Main.main(java.lang.String[]) line: 539 ------------------------ opening 2: Thread [main] (Suspended (breakpoint at line 67 in org.eclipse.jface.viewers.DecoratingLabelProvider)) org.eclipse.jface.viewers.DecoratingLabelProvider.getImage (java.lang.Object) line: 67 org.eclipse.jdt.internal.ui.viewsupport.ResourceToItemsMapper.updateItem (org.eclipse.swt.widgets.Item) line: 65 org.eclipse.jdt.internal.ui.viewsupport.ResourceToItemsMapper.resourceCh anged(org.eclipse.core.resources.IResource) line: 50 org.eclipse.jdt.internal.ui.packageview.PackageExplorerPart$4 (org.eclipse.jdt.internal.ui.viewsupport.ProblemTreeViewer).handleLabelProviderC hanged(org.eclipse.jface.viewers.LabelProviderChangedEvent) line: 120 org.eclipse.jface.viewers.ContentViewer$1.labelProviderChanged (org.eclipse.jface.viewers.LabelProviderChangedEvent) line: 68 org.eclipse.ui.internal.decorators.DecoratorManager.fireListeners (org.eclipse.jface.viewers.LabelProviderChangedEvent) line: 145 org.eclipse.ui.internal.decorators.DecoratorManager.labelProviderChanged (org.eclipse.jface.viewers.LabelProviderChangedEvent) line: 434 org.eclipse.jdt.ui.ProblemsLabelDecorator.fireProblemsChanged (org.eclipse.core.resources.IResource[], boolean) line: 338 org.eclipse.jdt.ui.ProblemsLabelDecorator.access$0 (org.eclipse.jdt.ui.ProblemsLabelDecorator, org.eclipse.core.resources.IResource [], boolean) line: 333 org.eclipse.jdt.ui.ProblemsLabelDecorator$1.problemsChanged (org.eclipse.core.resources.IResource[], boolean) line: 313 org.eclipse.jdt.internal.ui.viewsupport.ProblemMarkerManager$1.run() line: 177 org.eclipse.swt.widgets.RunnableLock.run() line: 31 org.eclipse.ui.internal.UISynchronizer (org.eclipse.swt.widgets.Synchronizer).runAsyncMessages() line: 94 org.eclipse.swt.widgets.Display.runAsyncMessages() line: 1669 org.eclipse.swt.widgets.Display.readAndDispatch() line: 1414 org.eclipse.ui.internal.Workbench.runEventLoop() line: 1403 org.eclipse.ui.internal.Workbench.run(java.lang.Object) line: 1386 org.eclipse.core.internal.boot.InternalBootLoader.run(java.lang.String, java.net.URL, java.lang.String, java.lang.String[], java.lang.Runnable) line: 840 org.eclipse.core.boot.BootLoader.run(java.lang.String, java.net.URL, java.lang.String, java.lang.String[], java.lang.Runnable) line: 462 sun.reflect.NativeMethodAccessorImpl.invoke0(java.lang.reflect.Method, java.lang.Object, java.lang.Object[]) line: not available [native method] sun.reflect.NativeMethodAccessorImpl.invoke(java.lang.Object, java.lang.Object[]) line: 39 sun.reflect.DelegatingMethodAccessorImpl.invoke(java.lang.Object, java.lang.Object[]) line: 25 java.lang.reflect.Method.invoke(java.lang.Object, java.lang.Object[]) line: 324 org.eclipse.core.launcher.Main.basicRun(java.lang.String[]) line: 247 org.eclipse.core.launcher.Main.run(java.lang.String[]) line: 703 org.eclipse.core.launcher.Main.main(java.lang.String[]) line: 539
|
resolved fixed
|
655a6c0
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-07T21:16:05Z | 2002-12-13T11:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/packageview/PackageExplorerContentProvider.java
|
/*
* (c) Copyright IBM Corp. 2000, 2002.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.packageview;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceDelta;
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.ElementChangedEvent;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IElementChangedListener;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaElementDelta;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.IWorkingCopy;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.StandardJavaElementContentProvider;
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 {
protected TreeViewer fViewer;
protected Object fInput;
private boolean fIsFlatLayout;
private PackageFragmentProvider fPackageFragmentProvider= new PackageFragmentProvider();
/**
* Creates a new content provider for Java elements.
*/
public PackageExplorerContentProvider() {
}
/**
* Creates a new content provider for Java elements.
*/
public PackageExplorerContentProvider(boolean provideMembers, boolean provideWorkingCopy) {
super(provideMembers, provideWorkingCopy);
}
/* (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 needsToDelegate(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) {
if (needsToDelegate(parentElement)) {
Object[] packageFragments= fPackageFragmentProvider.getChildren(parentElement);
return getWithParentsResources(packageFragments, parentElement);
} else
return super.getChildren(parentElement);
}
public Object getParent(Object child) {
if (needsToDelegate(child)) {
return fPackageFragmentProvider.getParent(child);
} else
return super.getParent(child);
}
/**
* 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.
*/
public void processDelta(IJavaElementDelta delta) throws JavaModelException {
int kind= delta.getKind();
int flags= delta.getFlags();
IJavaElement element= delta.getElement();
if(element.getElementType()!= IJavaElement.JAVA_MODEL && element.getElementType()!= IJavaElement.JAVA_PROJECT){
IJavaProject proj= element.getJavaProject();
if (proj == null || !proj.getProject().isOpen())
return;
}
if (!fIsFlatLayout && element.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
fPackageFragmentProvider.processDelta(delta);
if (processResourceDeltas(delta.getResourceDeltas(), element))
return;
IJavaElementDelta[] affectedChildren= delta.getAffectedChildren();
processAffectedChildren(affectedChildren);
return;
}
if (!getProvideWorkingCopy() && isWorkingCopy(element))
return;
if (element != null && element.getElementType() == IJavaElement.COMPILATION_UNIT && !isOnClassPath((ICompilationUnit)element))
return;
// handle open and closing of a solution or project
if (((flags & IJavaElementDelta.F_CLOSED) != 0) || ((flags & IJavaElementDelta.F_OPENED) != 0)) {
postRefresh(element);
return;
}
if (kind == IJavaElementDelta.REMOVED) {
// when a working copy is removed all we have to do
// is to refresh the compilation unit
if (isWorkingCopy(element)) {
refreshWorkingCopy((IWorkingCopy)element);
return;
}
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) {
// when a working copy is added all we have to do
// is to refresh the compilation unit
if (isWorkingCopy(element)) {
refreshWorkingCopy((IWorkingCopy)element);
return;
}
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 (element instanceof ICompilationUnit) {
if (getProvideWorkingCopy()) {
IJavaElement original= ((IWorkingCopy)element).getOriginalElement();
if (original != null)
element= original;
}
if (kind == IJavaElementDelta.CHANGED) {
postRefresh(element);
updateSelection(delta);
return;
}
}
// we don't show the contents of a compilation or IClassFile, so don't go any deeper
if ((element instanceof ICompilationUnit) || (element instanceof IClassFile))
return;
// the contents of an external JAR has changed
if (element instanceof IPackageFragmentRoot && ((flags & IJavaElementDelta.F_ARCHIVE_CONTENT_CHANGED) != 0)) {
postRefresh(element);
return;
}
// the source attachment of a JAR has changed
if (element instanceof IPackageFragmentRoot && (((flags & IJavaElementDelta.F_SOURCEATTACHED) != 0 || ((flags & 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 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) throws JavaModelException {
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;
}
/**
* Refreshes the Compilation unit corresponding to the workging copy
* @param iWorkingCopy
*/
private void refreshWorkingCopy(IWorkingCopy workingCopy) {
IJavaElement original= workingCopy.getOriginalElement();
if (original != null)
postRefresh(original);
}
private boolean isWorkingCopy(IJavaElement element) {
return (element instanceof IWorkingCopy) && ((IWorkingCopy)element).isWorkingCopy();
}
/**
* 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();
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);
}
processResourceDeltas(delta.getAffectedChildren(), resource);
return false;
}
/**
* 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(final Object root) {
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.refresh(root);
}
}
});
}
private void postAdd(final Object parent, final Object 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.add(parent, element);
}
}
});
}
private void postRemove(final Object 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.remove(element);
}
}
});
}
private void postRunnable(final Runnable r) {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
ctrl.getDisplay().asyncExec(r);
}
}
void setIsFlatLayout(boolean state) {
fIsFlatLayout= state;
}
}
|
29,165 |
Bug 29165 exception when deleting a class in I20030107 (win2k)
|
steps to reproduce the exception : - selected class in package explorer - selected delete in contextmenu
|
resolved fixed
|
dd38a97
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-09T09:07:05Z | 2003-01-08T21:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/JavaPlugin.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
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.IPath;
import org.eclipse.core.runtime.IPluginDescriptor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Path;
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.plugin.AbstractUIPlugin;
import org.eclipse.jdt.core.IJavaElement;
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.corext.javadoc.JavaDocLocations;
import org.eclipse.jdt.internal.ui.javaeditor.ClassFileDocumentProvider;
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitDocumentProvider;
import org.eclipse.jdt.internal.ui.preferences.MembersOrderPreferenceCache;
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 {
// TODO: Evaluate if we should move these ID's to JavaUI
/**
* The id of the best match hover contributed for extension point
* <code>javaEditorTextHovers</code>.
*
* @since 2.1
*/
public static String ID_BESTMATCH_HOVER= "org.eclipse.jdt.ui.BestMatchHover"; //$NON-NLS-1$
/**
* The id of the source code hover contributed for extension point
* <code>javaEditorTextHovers</code>.
*
* @since 2.1
*/
public static String ID_SOURCE_HOVER= "org.eclipse.jdt.ui.JavaSourceHover"; //$NON-NLS-1$
/**
* The id of the javadoc hover contributed for extension point
* <code>javaEditorTextHovers</code>.
*
* @since 2.1
*/
public static String ID_JAVADOC_HOVER= "org.eclipse.jdt.ui.JavadocHover"; //$NON-NLS-1$
/**
* The id of the problem hover contributed for extension point
* <code>javaEditorTextHovers</code>.
*
* @since 2.1
*/
public static String ID_PROBLEM_HOVER= "org.eclipse.jdt.ui.ProblemHover"; //$NON-NLS-1$
private static JavaPlugin fgJavaPlugin;
private CompilationUnitDocumentProvider 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 MembersOrderPreferenceCache fMembersOrderPreferenceCache;
private IPropertyChangeListener fFontPropertyChangeListener;
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() {
return getActiveWorkbenchWindow().getShell();
}
/**
* 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 i= 0; i < windows.length; i++) {
IWorkbenchPage[] pages= windows[i].getPages();
for (int x= 0; x < pages.length; x++) {
IEditorReference[] references= pages[i].getEditorReferences();
for (int j= 0; j < references.length; j++) {
IEditorPart editor= references[j].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();
}
/* package */ static IPath getInstallLocation() {
return new Path(getDefault().getDescriptor().getInstallURL().getFile());
}
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();
/*
* 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.setValue(getPreferenceStore(), JFaceResources.TEXT_FONT, JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT).getFontData());
fFontPropertyChangeListener= new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
if (PreferenceConstants.EDITOR_TEXT_FONT.equals(event.getProperty()))
PreferenceConverter.setValue(getPreferenceStore(), JFaceResources.TEXT_FONT, JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT).getFontData());
}
};
JFaceResources.getFontRegistry().addListener(fFontPropertyChangeListener);
}
/* (non - Javadoc)
* Method declared in AbstractUIPlugin
*/
protected ImageRegistry createImageRegistry() {
return JavaPluginImages.getImageRegistry();
}
/* (non - Javadoc)
* Method declared in Plugin
*/
public void shutdown() throws CoreException {
if (fImageDescriptorRegistry != null)
fImageDescriptorRegistry.dispose();
unregisterAdapters();
super.shutdown();
if (fCompilationUnitDocumentProvider != null) {
fCompilationUnitDocumentProvider.shutdown();
fCompilationUnitDocumentProvider= null;
}
if (fJavaTextTools != null) {
fJavaTextTools.dispose();
fJavaTextTools= null;
}
JavaDocLocations.shutdownJavadocLocations();
JFaceResources.getFontRegistry().removeListener(fFontPropertyChangeListener);
}
private IWorkbenchPage internalGetActivePage() {
IWorkbenchWindow window= getWorkbench().getActiveWorkbenchWindow();
if (window == null)
return null;
return getWorkbench().getActiveWorkbenchWindow().getActivePage();
}
public synchronized CompilationUnitDocumentProvider getCompilationUnitDocumentProvider() {
if (fCompilationUnitDocumentProvider == null)
fCompilationUnitDocumentProvider= new CompilationUnitDocumentProvider();
return fCompilationUnitDocumentProvider;
}
public synchronized ClassFileDocumentProvider getClassFileDocumentProvider() {
if (fClassFileDocumentProvider == null)
fClassFileDocumentProvider= new ClassFileDocumentProvider();
return fClassFileDocumentProvider;
}
public synchronized IWorkingCopyManager getWorkingCopyManager() {
return getCompilationUnitDocumentProvider();
}
public synchronized ProblemMarkerManager getProblemMarkerManager() {
if (fProblemMarkerManager == null)
fProblemMarkerManager= new ProblemMarkerManager();
return fProblemMarkerManager;
}
public synchronized JavaTextTools getJavaTextTools() {
if (fJavaTextTools == null)
fJavaTextTools= new JavaTextTools(getPreferenceStore());
return fJavaTextTools;
}
public synchronized MembersOrderPreferenceCache getMemberOrderPreferenceCache() {
if (fMembersOrderPreferenceCache == null)
fMembersOrderPreferenceCache= new MembersOrderPreferenceCache();
return fMembersOrderPreferenceCache;
}
/**
* 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);
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();
IAdapterManager manager= Platform.getAdapterManager();
manager.registerAdapters(fJavaElementAdapterFactory, IJavaElement.class);
manager.registerAdapters(fMarkerAdapterFactory, IMarker.class);
manager.registerAdapters(fEditorInputAdapterFactory, IEditorInput.class);
manager.registerAdapters(fResourceAdapterFactory, IResource.class);
}
private void unregisterAdapters() {
IAdapterManager manager= Platform.getAdapterManager();
manager.unregisterAdapters(fJavaElementAdapterFactory);
manager.unregisterAdapters(fMarkerAdapterFactory);
manager.unregisterAdapters(fEditorInputAdapterFactory);
manager.unregisterAdapters(fResourceAdapterFactory);
}
}
|
25,152 |
Bug 25152 Code format too tight when creating a missing method [code manipulation]
|
When you choose the quick fix 'create method', the code generated butts up below the method without a new line: } /** * Method precompile. */ private void precompile() { } instead of: } /** * Method precompile. */ private void precompile() { }
|
resolved fixed
|
027c529
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-09T09:53:35Z | 2002-10-21T22:40:00Z |
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/astrewrite/ASTRewritingMoveCodeTest.java
|
package org.eclipse.jdt.ui.tests.astrewrite;
import java.util.Hashtable;
import java.util.List;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.Block;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.ExpressionStatement;
import org.eclipse.jdt.core.dom.ForStatement;
import org.eclipse.jdt.core.dom.IfStatement;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.MethodInvocation;
import org.eclipse.jdt.core.dom.ReturnStatement;
import org.eclipse.jdt.core.dom.Statement;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jdt.core.dom.WhileStatement;
import org.eclipse.jdt.testplugin.JavaProjectHelper;
import org.eclipse.jdt.internal.corext.dom.ASTRewrite;
import org.eclipse.jdt.internal.ui.text.correction.ASTRewriteCorrectionProposal;
public class ASTRewritingMoveCodeTest extends ASTRewritingTest {
private static final Class THIS= ASTRewritingMoveCodeTest.class;
private IJavaProject fJProject1;
private IPackageFragmentRoot fSourceFolder;
public ASTRewritingMoveCodeTest(String name) {
super(name);
}
public static Test suite() {
if (false) {
return new TestSuite(THIS);
} else {
TestSuite suite= new TestSuite();
suite.addTest(new ASTRewritingMoveCodeTest("testMoveForStatementToForBlock"));
return suite;
}
}
protected void setUp() throws Exception {
Hashtable options= JavaCore.getOptions();
options.put(JavaCore.FORMATTER_TAB_CHAR, JavaCore.SPACE);
options.put(JavaCore.FORMATTER_TAB_SIZE, "4");
JavaCore.setOptions(options);
fJProject1= JavaProjectHelper.createJavaProject("TestProject1", "bin");
assertTrue("rt not found", JavaProjectHelper.addRTJar(fJProject1) != null);
fSourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
}
protected void tearDown() throws Exception {
JavaProjectHelper.delete(fJProject1);
}
public void testMoveDeclSameLevel() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends Exception implements Runnable, Serializable {\n");
buf.append(" public static class EInner {\n");
buf.append(" public void xee() {\n");
buf.append(" /* does nothing */\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" private /* inner comment */ int i;\n");
buf.append(" private int k;\n");
buf.append(" public E() {\n");
buf.append(" super();\n");
buf.append(" i= 0;\n");
buf.append(" k= 9;\n");
buf.append(" if (System.out == null) {\n");
buf.append(" gee(); // cool\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" public void gee() {\n");
buf.append(" }\n");
buf.append("}\n");
buf.append("interface G {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, false);
ASTRewrite rewrite= new ASTRewrite(astRoot);
assertTrue("Code has errors", (astRoot.getFlags() & CompilationUnit.MALFORMED) == 0);
TypeDeclaration type= findTypeDeclaration(astRoot, "E");
{ // move inner type to the end of the type & move, copy statements from constructor to method
List members= type.bodyDeclarations();
assertTrue("Has declarations", !members.isEmpty());
assertTrue("Cannot find inner class", members.get(0) instanceof TypeDeclaration);
TypeDeclaration innerType= (TypeDeclaration) members.get(0);
rewrite.markAsRemoved(innerType);
ASTNode movedNode= rewrite.createCopy(innerType);
members.add(movedNode);
rewrite.markAsInserted(movedNode);
Statement toMove;
Statement toCopy;
{
MethodDeclaration methodDecl= findMethodDeclaration(type, "E");
assertTrue("Cannot find Constructor E", methodDecl != null);
Block body= methodDecl.getBody();
assertTrue("No body", body != null);
List statements= body.statements();
assertTrue("Not expected number of statements", statements.size() == 4);
toMove= (Statement) statements.get(1);
toCopy= (Statement) statements.get(3);
rewrite.markAsRemoved(toMove);
}
{
MethodDeclaration methodDecl= findMethodDeclaration(type, "gee");
assertTrue("Cannot find gee()", methodDecl != null);
Block body= methodDecl.getBody();
assertTrue("No body", body != null);
List statements= body.statements();
assertTrue("Has statements", statements.isEmpty());
ASTNode insertNodeForMove= rewrite.createCopy(toMove);
ASTNode insertNodeForCopy= rewrite.createCopy(toCopy);
statements.add(insertNodeForCopy);
statements.add(insertNodeForMove);
rewrite.markAsInserted(insertNodeForMove);
rewrite.markAsInserted(insertNodeForCopy);
}
}
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null);
proposal.getCompilationUnitChange().setSave(true);
proposal.apply(null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends Exception implements Runnable, Serializable {\n");
buf.append(" private /* inner comment */ int i;\n");
buf.append(" private int k;\n");
buf.append(" public E() {\n");
buf.append(" super();\n");
buf.append(" k= 9;\n");
buf.append(" if (System.out == null) {\n");
buf.append(" gee(); // cool\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" public void gee() {\n");
buf.append(" if (System.out == null) {\n");
buf.append(" gee(); // cool\n");
buf.append(" }\n");
buf.append(" i= 0;\n");
buf.append(" }\n");
buf.append(" public static class EInner {\n");
buf.append(" public void xee() {\n");
buf.append(" /* does nothing */\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
buf.append("interface G {\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
clearRewrite(rewrite);
}
public void testMoveDeclDifferentLevel() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends Exception implements Runnable, Serializable {\n");
buf.append(" public static class EInner {\n");
buf.append(" public void xee() {\n");
buf.append(" /* does nothing */\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" private /* inner comment */ int i;\n");
buf.append(" private int k;\n");
buf.append(" public E() {\n");
buf.append(" super();\n");
buf.append(" i= 0;\n");
buf.append(" k= 9;\n");
buf.append(" if (System.out == null) {\n");
buf.append(" gee(); // cool\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" public void gee() {\n");
buf.append(" }\n");
buf.append("}\n");
buf.append("interface G {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, false);
ASTRewrite rewrite= new ASTRewrite(astRoot);
AST ast= astRoot.getAST();
assertTrue("Code has errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0);
TypeDeclaration type= findTypeDeclaration(astRoot, "E");
{
List members= type.bodyDeclarations();
assertTrue("Has declarations", !members.isEmpty());
assertTrue("Cannot find inner class", members.get(0) instanceof TypeDeclaration);
TypeDeclaration innerType= (TypeDeclaration) members.get(0);
List innerMembers= innerType.bodyDeclarations();
assertTrue("Not expected number of inner members", innerMembers.size() == 1);
{ // move outer as inner of inner.
TypeDeclaration outerType= findTypeDeclaration(astRoot, "G");
assertTrue("G not found", outerType != null);
rewrite.markAsRemoved(outerType);
ASTNode insertNodeForCopy= rewrite.createCopy(outerType);
innerMembers.add(insertNodeForCopy);
rewrite.markAsInserted(insertNodeForCopy);
}
{ // copy method of inner to main type
MethodDeclaration methodDecl= (MethodDeclaration) innerMembers.get(0);
ASTNode insertNodeForMove= rewrite.createCopy(methodDecl);
members.add(insertNodeForMove);
rewrite.markAsInserted(insertNodeForMove);
}
{ // nest body of constructor in a while statement
MethodDeclaration methodDecl= findMethodDeclaration(type, "E");
assertTrue("Cannot find Constructor E", methodDecl != null);
Block body= methodDecl.getBody();
WhileStatement whileStatement= ast.newWhileStatement();
whileStatement.setExpression(ast.newBooleanLiteral(true));
Statement insertNodeForCopy= (Statement) rewrite.createCopy(body);
whileStatement.setBody(insertNodeForCopy); // set existing body
Block newBody= ast.newBlock();
List newStatements= newBody.statements();
newStatements.add(whileStatement);
rewrite.markAsReplaced(body, newBody);
}
}
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null);
proposal.getCompilationUnitChange().setSave(true);
proposal.apply(null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends Exception implements Runnable, Serializable {\n");
buf.append(" public static class EInner {\n");
buf.append(" public void xee() {\n");
buf.append(" /* does nothing */\n");
buf.append(" }\n");
buf.append(" interface G {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" private /* inner comment */ int i;\n");
buf.append(" private int k;\n");
buf.append(" public E() {\n");
buf.append(" while (true) {\n");
buf.append(" super();\n");
buf.append(" i= 0;\n");
buf.append(" k= 9;\n");
buf.append(" if (System.out == null) {\n");
buf.append(" gee(); // cool\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" public void gee() {\n");
buf.append(" }\n");
buf.append(" public void xee() {\n");
buf.append(" /* does nothing */\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
clearRewrite(rewrite);
}
public void testMoveStatements() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends Exception implements Runnable, Serializable {\n");
buf.append(" public static class EInner {\n");
buf.append(" public void xee() {\n");
buf.append(" /* does nothing */\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" private /* inner comment */ int i;\n");
buf.append(" private int k;\n");
buf.append(" public E() {\n");
buf.append(" super();\n");
buf.append(" i= 0;\n");
buf.append(" k= 9;\n");
buf.append(" if (System.out == null) {\n");
buf.append(" gee(); // cool\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" public void gee() {\n");
buf.append(" }\n");
buf.append("}\n");
buf.append("interface G {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, false);
ASTRewrite rewrite= new ASTRewrite(astRoot);
AST ast= astRoot.getAST();
assertTrue("Code has errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0);
TypeDeclaration type= findTypeDeclaration(astRoot, "E");
{ // move first statments inside an ifstatement, move second statment inside a new while statement
// that is in the ifstatement
MethodDeclaration methodDecl= findMethodDeclaration(type, "E");
assertTrue("Cannot find Constructor E", methodDecl != null);
Block body= methodDecl.getBody();
List statements= body.statements();
assertTrue("Cannot find if statement", statements.get(3) instanceof IfStatement);
IfStatement ifStatement= (IfStatement) statements.get(3);
Statement insertNodeForCopy1= (Statement) rewrite.createCopy((ASTNode) statements.get(1));
Statement insertNodeForCopy2= (Statement) rewrite.createCopy((ASTNode) statements.get(2));
Block whileBody= ast.newBlock();
WhileStatement whileStatement= ast.newWhileStatement();
whileStatement.setExpression(ast.newBooleanLiteral(true));
whileStatement.setBody(whileBody);
List whileBodyStatements= whileBody.statements();
whileBodyStatements.add(insertNodeForCopy2);
assertTrue("if statement body not a block", ifStatement.getThenStatement() instanceof Block);
List ifBodyStatements= ((Block)ifStatement.getThenStatement()).statements();
ifBodyStatements.add(0, whileStatement);
ifBodyStatements.add(1, insertNodeForCopy1);
rewrite.markAsInserted(whileStatement);
rewrite.markAsInserted(insertNodeForCopy1);
rewrite.markAsRemoved((ASTNode) statements.get(1));
rewrite.markAsRemoved((ASTNode) statements.get(2));
}
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null);
proposal.getCompilationUnitChange().setSave(true);
proposal.apply(null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends Exception implements Runnable, Serializable {\n");
buf.append(" public static class EInner {\n");
buf.append(" public void xee() {\n");
buf.append(" /* does nothing */\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" private /* inner comment */ int i;\n");
buf.append(" private int k;\n");
buf.append(" public E() {\n");
buf.append(" super();\n");
buf.append(" if (System.out == null) {\n");
buf.append(" while (true) {\n");
buf.append(" k= 9;\n");
buf.append(" }\n");
buf.append(" i= 0;\n");
buf.append(" gee(); // cool\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" public void gee() {\n");
buf.append(" }\n");
buf.append("}\n");
buf.append("interface G {\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
clearRewrite(rewrite);
}
public void tesCopyFromDeleted() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" if (System.out == null) {\n");
buf.append(" gee(); // cool\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" public void goo() {\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, false);
ASTRewrite rewrite= new ASTRewrite(astRoot);
assertTrue("Code has errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0);
TypeDeclaration type= findTypeDeclaration(astRoot, "E");
{ // delete method foo, but copy if statement to goo
MethodDeclaration methodDecl= findMethodDeclaration(type, "foo");
assertTrue("Cannot find foo", methodDecl != null);
rewrite.markAsRemoved(methodDecl);
Block body= methodDecl.getBody();
List statements= body.statements();
assertTrue("Cannot find if statement", statements.size() == 1);
ASTNode placeHolder= rewrite.createCopy((ASTNode) statements.get(0));
MethodDeclaration methodGoo= findMethodDeclaration(type, "goo");
assertTrue("Cannot find goo", methodGoo != null);
rewrite.markAsInserted(placeHolder);
methodGoo.getBody().statements().add(placeHolder);
}
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null);
proposal.getCompilationUnitChange().setSave(true);
proposal.apply(null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void goo() {\n");
buf.append(" if (System.out == null) {\n");
buf.append(" gee(); // cool\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
clearRewrite(rewrite);
}
public void testChangesInMove() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" if (System.out == null) {\n");
buf.append(" gee( /* cool */);\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" public void goo() {\n");
buf.append(" x= 1;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, false);
ASTRewrite rewrite= new ASTRewrite(astRoot);
AST ast= astRoot.getAST();
assertTrue("Code has errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0);
TypeDeclaration type= findTypeDeclaration(astRoot, "E");
{ // replace statement in goo with moved ifStatement from foo. add a node to if statement
MethodDeclaration methodDecl= findMethodDeclaration(type, "foo");
assertTrue("Cannot find foo", methodDecl != null);
List fooStatements= methodDecl.getBody().statements();
assertTrue("Cannot find if statement", fooStatements.size() == 1);
// prepare ifStatement to move
IfStatement ifStatement= (IfStatement) fooStatements.get(0);
rewrite.markAsRemoved(ifStatement);
ASTNode placeHolder= rewrite.createCopy(ifStatement);
// add return statement to ifStatement block
ReturnStatement returnStatement= ast.newReturnStatement();
rewrite.markAsInserted(returnStatement);
Block then= (Block) ifStatement.getThenStatement();
then.statements().add(returnStatement);
// replace statement in goo with moved ifStatement
MethodDeclaration methodGoo= findMethodDeclaration(type, "goo");
assertTrue("Cannot find goo", methodGoo != null);
List gooStatements= methodGoo.getBody().statements();
assertTrue("Cannot find statement in goo", gooStatements.size() == 1);
rewrite.markAsReplaced((ASTNode) gooStatements.get(0), placeHolder);
}
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null);
proposal.getCompilationUnitChange().setSave(true);
proposal.apply(null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" }\n");
buf.append(" public void goo() {\n");
buf.append(" if (System.out == null) {\n");
buf.append(" gee( /* cool */);\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
clearRewrite(rewrite);
}
public void testSwap() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" goo(xoo(/*hello*/), k * 2);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, false);
ASTRewrite rewrite= new ASTRewrite(astRoot);
assertTrue("Code has errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0);
TypeDeclaration type= findTypeDeclaration(astRoot, "E");
{ // swap the two arguments
MethodDeclaration methodDecl= findMethodDeclaration(type, "foo");
assertTrue("Cannot find foo", methodDecl != null);
List fooStatements= methodDecl.getBody().statements();
assertTrue("More statements than expected", fooStatements.size() == 1);
ExpressionStatement statement= (ExpressionStatement) fooStatements.get(0);
MethodInvocation invocation= (MethodInvocation) statement.getExpression();
List arguments= invocation.arguments();
assertTrue("More arguments than expected", arguments.size() == 2);
ASTNode arg0= (ASTNode) arguments.get(0);
ASTNode arg1= (ASTNode) arguments.get(1);
ASTNode placeHolder0= rewrite.createCopy(arg0);
ASTNode placeHolder1= rewrite.createCopy(arg1);
rewrite.markAsReplaced(arg0, placeHolder1);
rewrite.markAsReplaced(arg1, placeHolder0);
}
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null);
proposal.getCompilationUnitChange().setSave(true);
proposal.apply(null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" goo(k * 2, xoo(/*hello*/));\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
clearRewrite(rewrite);
}
public void testCopyRangeAndInsert() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" if (i == 0) {\n");
buf.append(" foo();\n");
buf.append(" i++; // comment\n");
buf.append(" i++;\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, false);
ASTRewrite rewrite= new ASTRewrite(astRoot);
assertTrue("Code has errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0);
TypeDeclaration type= findTypeDeclaration(astRoot, "E");
MethodDeclaration methodDecl= findMethodDeclaration(type, "foo");
{
List statements= methodDecl.getBody().statements();
IfStatement ifStatement= (IfStatement) statements.get(0);
List ifStatementBody= ((Block) ifStatement.getThenStatement()).statements();
ASTNode first= (ASTNode) ifStatementBody.get(0);
ASTNode last= (ASTNode) ifStatementBody.get(ifStatementBody.size() - 1);
ASTNode placeholder= rewrite.createCopy(first, last);
rewrite.markAsInserted(placeholder);
statements.add(placeholder);
}
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null);
proposal.getCompilationUnitChange().setSave(true);
proposal.apply(null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" if (i == 0) {\n");
buf.append(" foo();\n");
buf.append(" i++; // comment\n");
buf.append(" i++;\n");
buf.append(" }\n");
buf.append(" foo();\n");
buf.append(" i++; // comment\n");
buf.append(" i++;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
clearRewrite(rewrite);
}
public void testCopyRangeAndReplace() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" if (i == 0) {\n");
buf.append(" foo();\n");
buf.append(" i++; // comment\n");
buf.append(" i++;\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, false);
ASTRewrite rewrite= new ASTRewrite(astRoot);
AST ast= astRoot.getAST();
assertTrue("Code has errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0);
TypeDeclaration type= findTypeDeclaration(astRoot, "E");
MethodDeclaration methodDecl= findMethodDeclaration(type, "foo");
{
List statements= methodDecl.getBody().statements();
IfStatement ifStatement= (IfStatement) statements.get(0);
List ifStatementBody= ((Block) ifStatement.getThenStatement()).statements();
ASTNode first= (ASTNode) ifStatementBody.get(0);
ASTNode last= (ASTNode) ifStatementBody.get(ifStatementBody.size() - 1);
ASTNode placeholder= rewrite.createCopy(first, last);
ReturnStatement returnStatement= ast.newReturnStatement();
rewrite.markAsReplaced(last, returnStatement);
rewrite.markAsReplaced(ifStatement, placeholder);
}
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null);
proposal.getCompilationUnitChange().setSave(true);
proposal.apply(null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" foo();\n");
buf.append(" i++; // comment\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
clearRewrite(rewrite);
}
public void testMoveForStatementToForBlock() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" for(int i= 0; i < 8; i++)\n");
buf.append(" foo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, false);
ASTRewrite rewrite= new ASTRewrite(astRoot);
AST ast= astRoot.getAST();
assertTrue("Code has errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0);
TypeDeclaration type= findTypeDeclaration(astRoot, "E");
MethodDeclaration methodDecl= findMethodDeclaration(type, "foo");
{
List statements= methodDecl.getBody().statements();
ForStatement forStatement= (ForStatement) statements.get(0);
Statement body= forStatement.getBody();
ASTNode placeholder= rewrite.createCopy(body);
Block newBody= ast.newBlock();
newBody.statements().add(placeholder);
rewrite.markAsReplaced(body, newBody);
}
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null);
proposal.getCompilationUnitChange().setSave(true);
proposal.apply(null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" for(int i= 0; i < 8; i++)\n");
buf.append(" {\n");
buf.append(" foo();\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
clearRewrite(rewrite);
}
}
|
25,152 |
Bug 25152 Code format too tight when creating a missing method [code manipulation]
|
When you choose the quick fix 'create method', the code generated butts up below the method without a new line: } /** * Method precompile. */ private void precompile() { } instead of: } /** * Method precompile. */ private void precompile() { }
|
resolved fixed
|
027c529
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-09T09:53:35Z | 2002-10-21T22:40:00Z |
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/astrewrite/ASTRewritingTypeDeclTest.java
|
package org.eclipse.jdt.ui.tests.astrewrite;
import java.util.Hashtable;
import java.util.List;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.dom.*;
import org.eclipse.jdt.testplugin.JavaProjectHelper;
import org.eclipse.jdt.internal.corext.dom.ASTRewrite;
import org.eclipse.jdt.internal.ui.text.correction.ASTRewriteCorrectionProposal;
public class ASTRewritingTypeDeclTest extends ASTRewritingTest {
private static final Class THIS= ASTRewritingTypeDeclTest.class;
private IJavaProject fJProject1;
private IPackageFragmentRoot fSourceFolder;
public ASTRewritingTypeDeclTest(String name) {
super(name);
}
public static Test suite() {
if (true) {
return new TestSuite(THIS);
} else {
TestSuite suite= new TestSuite();
suite.addTest(new ASTRewritingTypeDeclTest("testSingleVariableDeclaration"));
return suite;
}
}
protected void setUp() throws Exception {
Hashtable options= JavaCore.getOptions();
options.put(JavaCore.FORMATTER_TAB_CHAR, JavaCore.SPACE);
options.put(JavaCore.FORMATTER_TAB_SIZE, "4");
JavaCore.setOptions(options);
fJProject1= JavaProjectHelper.createJavaProject("TestProject1", "bin");
assertTrue("rt not found", JavaProjectHelper.addRTJar(fJProject1) != null);
fSourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
}
protected void tearDown() throws Exception {
JavaProjectHelper.delete(fJProject1);
}
public void testTypeDeclChanges() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends Exception implements Runnable, Serializable {\n");
buf.append(" public static class EInner {\n");
buf.append(" public void xee() {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" private int i;\n");
buf.append(" private int k;\n");
buf.append(" public E() {\n");
buf.append(" }\n");
buf.append(" public void gee() {\n");
buf.append(" }\n");
buf.append(" public void hee() {\n");
buf.append(" }\n");
buf.append("}\n");
buf.append("class F implements Runnable {\n");
buf.append(" public void foo() {\n");
buf.append(" }\n");
buf.append("}\n");
buf.append("interface G {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, false);
ASTRewrite rewrite= new ASTRewrite(astRoot);
AST ast= astRoot.getAST();
{ // rename type, rename supertype, rename first interface, replace inner class with field
TypeDeclaration type= findTypeDeclaration(astRoot, "E");
SimpleName name= type.getName();
SimpleName newName= ast.newSimpleName("X");
rewrite.markAsReplaced(name, newName);
Name superClass= type.getSuperclass();
assertTrue("Has super type", superClass != null);
SimpleName newSuperclass= ast.newSimpleName("Object");
rewrite.markAsReplaced(superClass, newSuperclass, "Rename Superclass");
List superInterfaces= type.superInterfaces();
assertTrue("Has super interfaces", !superInterfaces.isEmpty());
SimpleName newSuperinterface= ast.newSimpleName("Cloneable");
rewrite.markAsReplaced((ASTNode) superInterfaces.get(0), newSuperinterface, "Rename Interface");
List members= type.bodyDeclarations();
assertTrue("Has declarations", !members.isEmpty());
FieldDeclaration newFieldDecl= createNewField(ast, "fCount");
rewrite.markAsReplaced((ASTNode) members.get(0), newFieldDecl, "Replace inner class with field");
}
{ // replace method in F, change to interface
TypeDeclaration type= findTypeDeclaration(astRoot, "F");
// change flags
TypeDeclaration modifiedNode= ast.newTypeDeclaration();
modifiedNode.setInterface(true);
modifiedNode.setModifiers(0);
rewrite.markAsModified(type, modifiedNode);
List members= type.bodyDeclarations();
assertTrue("Has declarations", members.size() == 1);
MethodDeclaration methodDecl= createNewMethod(ast, "newFoo", true);
rewrite.markAsReplaced((ASTNode) members.get(0), methodDecl);
}
{ // change to class, add supertype
TypeDeclaration type= findTypeDeclaration(astRoot, "G");
// change flags
TypeDeclaration modifiedNode= ast.newTypeDeclaration();
modifiedNode.setInterface(false);
modifiedNode.setModifiers(0);
rewrite.markAsModified(type, modifiedNode);
SimpleName newSuperclass= ast.newSimpleName("Object");
type.setSuperclass(newSuperclass);
rewrite.markAsInserted(newSuperclass);
}
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null);
proposal.getCompilationUnitChange().setSave(true);
proposal.apply(null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X extends Object implements Cloneable, Serializable {\n");
buf.append(" private double fCount;\n");
buf.append(" private int i;\n");
buf.append(" private int k;\n");
buf.append(" public E() {\n");
buf.append(" }\n");
buf.append(" public void gee() {\n");
buf.append(" }\n");
buf.append(" public void hee() {\n");
buf.append(" }\n");
buf.append("}\n");
buf.append("interface F extends Runnable {\n");
buf.append(" private abstract void newFoo(String str);\n");
buf.append("}\n");
buf.append("class G extends Object {\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
clearRewrite(rewrite);
}
public void testTypeDeclRemoves() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends Exception implements Runnable, Serializable {\n");
buf.append(" public static class EInner {\n");
buf.append(" public void xee() {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" private int i;\n");
buf.append(" private int k;\n");
buf.append(" public E() {\n");
buf.append(" }\n");
buf.append(" public void gee() {\n");
buf.append(" }\n");
buf.append(" public void hee() {\n");
buf.append(" }\n");
buf.append("}\n");
buf.append("class F implements Runnable {\n");
buf.append(" public void foo() {\n");
buf.append(" }\n");
buf.append("}\n");
buf.append("interface G {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, false);
ASTRewrite rewrite= new ASTRewrite(astRoot);
AST ast= astRoot.getAST();
{ // change to interface, remove supertype, remove first interface, remove field
TypeDeclaration type= findTypeDeclaration(astRoot, "E");
// change flags
TypeDeclaration modifiedNode= ast.newTypeDeclaration();
modifiedNode.setInterface(true);
modifiedNode.setModifiers(0);
rewrite.markAsModified(type, modifiedNode);
Name superClass= type.getSuperclass();
assertTrue("Has super type", superClass != null);
rewrite.markAsRemoved(superClass);
List superInterfaces= type.superInterfaces();
assertTrue("Has super interfaces", !superInterfaces.isEmpty());
rewrite.markAsRemoved((ASTNode) superInterfaces.get(0));
List members= type.bodyDeclarations();
assertTrue("Has declarations", !members.isEmpty());
rewrite.markAsRemoved((ASTNode) members.get(1));
MethodDeclaration meth= findMethodDeclaration(type, "hee");
rewrite.markAsRemoved(meth);
}
{ // remove superinterface & method, change to interface & final
TypeDeclaration type= findTypeDeclaration(astRoot, "F");
// change flags
TypeDeclaration modifiedNode= ast.newTypeDeclaration();
modifiedNode.setInterface(true);
modifiedNode.setModifiers(Modifier.FINAL);
rewrite.markAsModified(type, modifiedNode);
List superInterfaces= type.superInterfaces();
assertTrue("Has super interfaces", !superInterfaces.isEmpty());
rewrite.markAsRemoved((ASTNode) superInterfaces.get(0));
List members= type.bodyDeclarations();
assertTrue("Has declarations", members.size() == 1);
rewrite.markAsRemoved((ASTNode) members.get(0));
}
{ // remove class G
TypeDeclaration type= findTypeDeclaration(astRoot, "G");
rewrite.markAsRemoved(type);
}
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null);
proposal.getCompilationUnitChange().setSave(true);
proposal.apply(null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("interface E extends Serializable {\n");
buf.append(" public static class EInner {\n");
buf.append(" public void xee() {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" private int k;\n");
buf.append(" public E() {\n");
buf.append(" }\n");
buf.append(" public void gee() {\n");
buf.append(" }\n");
buf.append("}\n");
buf.append("final interface F {\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
clearRewrite(rewrite);
}
public void testTypeDeclInserts() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends Exception implements Runnable, Serializable {\n");
buf.append(" public static class EInner {\n");
buf.append(" public void xee() {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" private int i;\n");
buf.append(" private int k;\n");
buf.append(" public E() {\n");
buf.append(" }\n");
buf.append(" public void gee() {\n");
buf.append(" }\n");
buf.append(" public void hee() {\n");
buf.append(" }\n");
buf.append("}\n");
buf.append("class F implements Runnable {\n");
buf.append(" public void foo() {\n");
buf.append(" }\n");
buf.append("}\n");
buf.append("interface G {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, false);
ASTRewrite rewrite= new ASTRewrite(astRoot);
assertTrue("Errors in AST", (astRoot.getFlags() & ASTNode.MALFORMED) == 0);
AST ast= astRoot.getAST();
{ // add interface & set to final
TypeDeclaration type= findTypeDeclaration(astRoot, "E");
// change flags
TypeDeclaration modifiedNode= ast.newTypeDeclaration();
modifiedNode.setInterface(type.isInterface()); // no change
modifiedNode.setModifiers(Modifier.PUBLIC | Modifier.FINAL);
rewrite.markAsModified(type, modifiedNode);
List superInterfaces= type.superInterfaces();
assertTrue("Has super interfaces", !superInterfaces.isEmpty());
SimpleName newSuperinterface= ast.newSimpleName("Cloneable");
superInterfaces.add(0, newSuperinterface);
rewrite.markAsInserted(newSuperinterface);
List members= type.bodyDeclarations();
assertTrue("Has declarations", !members.isEmpty());
assertTrue("Cannot find inner class", members.get(0) instanceof TypeDeclaration);
TypeDeclaration innerType= (TypeDeclaration) members.get(0);
/* bug 22161
SimpleName newSuperclass= ast.newSimpleName("Exception");
innerType.setSuperclass(newSuperclass);
rewrite.markAsInserted(newSuperclass);
*/
FieldDeclaration newField= createNewField(ast, "fCount");
List innerMembers= innerType.bodyDeclarations();
innerMembers.add(0, newField);
rewrite.markAsInserted(newField);
MethodDeclaration newMethodDecl= createNewMethod(ast, "newMethod", false);
members.add(4, newMethodDecl);
rewrite.markAsInserted(newMethodDecl);
}
{ // add exception, add method
TypeDeclaration type= findTypeDeclaration(astRoot, "F");
SimpleName newSuperclass= ast.newSimpleName("Exception");
type.setSuperclass(newSuperclass);
rewrite.markAsInserted(newSuperclass);
List members= type.bodyDeclarations();
MethodDeclaration newMethodDecl= createNewMethod(ast, "newMethod", false);
members.add(newMethodDecl);
rewrite.markAsInserted(newMethodDecl);
}
{ // insert interface
TypeDeclaration type= findTypeDeclaration(astRoot, "G");
SimpleName newInterface= ast.newSimpleName("Runnable");
type.superInterfaces().add(newInterface);
rewrite.markAsInserted(newInterface);
List members= type.bodyDeclarations();
MethodDeclaration newMethodDecl= createNewMethod(ast, "newMethod", true);
members.add(newMethodDecl);
rewrite.markAsInserted(newMethodDecl);
}
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null);
proposal.getCompilationUnitChange().setSave(true);
proposal.apply(null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public final class E extends Exception implements Cloneable, Runnable, Serializable {\n");
buf.append(" public static class EInner {\n");
buf.append(" private double fCount;\n");
buf.append(" public void xee() {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" private int i;\n");
buf.append(" private int k;\n");
buf.append(" public E() {\n");
buf.append(" }\n");
buf.append(" private void newMethod(String str) {\n");
buf.append(" }\n");
buf.append(" public void gee() {\n");
buf.append(" }\n");
buf.append(" public void hee() {\n");
buf.append(" }\n");
buf.append("}\n");
buf.append("class F extends Exception implements Runnable {\n");
buf.append(" public void foo() {\n");
buf.append(" }\n");
buf.append(" private void newMethod(String str) {\n");
buf.append(" }\n");
buf.append("}\n");
buf.append("interface G extends Runnable {\n");
buf.append(" private abstract void newMethod(String str);\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
clearRewrite(rewrite);
}
public void testBug22161() throws Exception {
// System.out.println(getClass().getName()+"::" + getName() +" disabled (bug 22161)");
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class T extends Exception implements Runnable, Serializable {\n");
buf.append(" public static class EInner {\n");
buf.append(" public void xee() {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("T.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, false);
assertTrue("Errors in AST", (astRoot.getFlags() & ASTNode.MALFORMED) == 0);
TypeDeclaration type= findTypeDeclaration(astRoot, "T");
assertTrue("Outer type not found", type != null);
List members= type.bodyDeclarations();
assertTrue("Cannot find inner class", members.size() == 1 && members.get(0) instanceof TypeDeclaration);
TypeDeclaration innerType= (TypeDeclaration) members.get(0);
SimpleName name= innerType.getName();
assertTrue("Name positions not correct", name.getStartPosition() != -1 && name.getLength() > 0);
}
public void testAnonymousClassDeclaration() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E2 {\n");
buf.append(" public void foo() {\n");
buf.append(" new Runnable() {\n");
buf.append(" };\n");
buf.append(" new Runnable() {\n");
buf.append(" int i= 8;\n");
buf.append(" };\n");
buf.append(" new Runnable() {\n");
buf.append(" int i= 8;\n");
buf.append(" };\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E2.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, false);
ASTRewrite rewrite= new ASTRewrite(astRoot);
AST ast= astRoot.getAST();
assertTrue("Parse errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0);
TypeDeclaration type= findTypeDeclaration(astRoot, "E2");
MethodDeclaration methodDecl= findMethodDeclaration(type, "foo");
Block block= methodDecl.getBody();
List statements= block.statements();
assertTrue("Number of statements not 3", statements.size() == 3);
{ // insert body decl in AnonymousClassDeclaration
ExpressionStatement stmt= (ExpressionStatement) statements.get(0);
ClassInstanceCreation creation= (ClassInstanceCreation) stmt.getExpression();
AnonymousClassDeclaration anonym= creation.getAnonymousClassDeclaration();
assertTrue("no anonym class decl", anonym != null);
List decls= anonym.bodyDeclarations();
assertTrue("Number of bodyDeclarations not 0", decls.size() == 0);
MethodDeclaration newMethod= createNewMethod(ast, "newMethod", false);
decls.add(newMethod);
rewrite.markAsInserted(newMethod);
}
{ // remove body decl in AnonymousClassDeclaration
ExpressionStatement stmt= (ExpressionStatement) statements.get(1);
ClassInstanceCreation creation= (ClassInstanceCreation) stmt.getExpression();
AnonymousClassDeclaration anonym= creation.getAnonymousClassDeclaration();
assertTrue("no anonym class decl", anonym != null);
List decls= anonym.bodyDeclarations();
assertTrue("Number of bodyDeclarations not 1", decls.size() == 1);
rewrite.markAsRemoved((ASTNode) decls.get(0));
}
{ // replace body decl in AnonymousClassDeclaration
ExpressionStatement stmt= (ExpressionStatement) statements.get(2);
ClassInstanceCreation creation= (ClassInstanceCreation) stmt.getExpression();
AnonymousClassDeclaration anonym= creation.getAnonymousClassDeclaration();
assertTrue("no anonym class decl", anonym != null);
List decls= anonym.bodyDeclarations();
assertTrue("Number of bodyDeclarations not 1", decls.size() == 1);
MethodDeclaration newMethod= createNewMethod(ast, "newMethod", false);
rewrite.markAsReplaced((ASTNode) decls.get(0), newMethod);
}
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null);
proposal.getCompilationUnitChange().setSave(true);
proposal.apply(null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E2 {\n");
buf.append(" public void foo() {\n");
buf.append(" new Runnable() {\n");
buf.append(" private void newMethod(String str) {\n");
buf.append(" }\n");
buf.append(" };\n");
buf.append(" new Runnable() {\n");
buf.append(" };\n");
buf.append(" new Runnable() {\n");
buf.append(" private void newMethod(String str) {\n");
buf.append(" }\n");
buf.append(" };\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
clearRewrite(rewrite);
}
public void testImportDeclaration() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("import java.util.Vector;\n");
buf.append("import java.net.*;\n");
buf.append("import java.text.*;\n");
buf.append("public class Z {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("Z.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, false);
ASTRewrite rewrite= new ASTRewrite(astRoot);
AST ast= astRoot.getAST();
assertTrue("Parse errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0);
List imports= astRoot.imports();
assertTrue("Number of imports not 4", imports.size() == 4);
{ // rename import
ImportDeclaration imp= (ImportDeclaration) imports.get(0);
Name name= ast.newName(new String[] { "org", "eclipse", "X" });
rewrite.markAsReplaced(imp.getName(), name);
}
{ // change to import on demand
ImportDeclaration imp= (ImportDeclaration) imports.get(1);
Name name= ast.newName(new String[] { "java", "util" });
rewrite.markAsReplaced(imp.getName(), name);
ImportDeclaration modifedNode= (ImportDeclaration) ast.newImportDeclaration();
modifedNode.setOnDemand(true);
rewrite.markAsModified(imp, modifedNode);
}
{ // change to single import
ImportDeclaration imp= (ImportDeclaration) imports.get(2);
ImportDeclaration modifedNode= (ImportDeclaration) ast.newImportDeclaration();
modifedNode.setOnDemand(false);
rewrite.markAsModified(imp, modifedNode);
}
{ // rename import
ImportDeclaration imp= (ImportDeclaration) imports.get(3);
Name name= ast.newName(new String[] { "org", "eclipse" });
rewrite.markAsReplaced(imp.getName(), name);
}
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null);
proposal.getCompilationUnitChange().setSave(true);
proposal.apply(null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import org.eclipse.X;\n");
buf.append("import java.util.*;\n");
buf.append("import java.net;\n");
buf.append("import org.eclipse.*;\n");
buf.append("public class Z {\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
clearRewrite(rewrite);
}
public void testPackageDeclaration() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class Z {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("Z.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, false);
ASTRewrite rewrite= new ASTRewrite(astRoot);
AST ast= astRoot.getAST();
assertTrue("Parse errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0);
{ // rename package
PackageDeclaration packageDeclaration= astRoot.getPackage();
Name name= ast.newName(new String[] { "org", "eclipse" });
rewrite.markAsReplaced(packageDeclaration.getName(), name);
}
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null);
proposal.getCompilationUnitChange().setSave(true);
proposal.apply(null);
buf= new StringBuffer();
buf.append("package org.eclipse;\n");
buf.append("public class Z {\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
clearRewrite(rewrite);
}
public void testSingleVariableDeclaration() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i, final int[] k, int[] x[]) {\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, false);
ASTRewrite rewrite= new ASTRewrite(astRoot);
AST ast= astRoot.getAST();
assertTrue("Parse errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0);
TypeDeclaration type= findTypeDeclaration(astRoot, "E");
MethodDeclaration methodDecl= findMethodDeclaration(type, "foo");
List arguments= methodDecl.parameters();
{ // add modifier, change type, change name, add extra dimension
SingleVariableDeclaration decl= (SingleVariableDeclaration) arguments.get(0);
SingleVariableDeclaration modifierNode= ast.newSingleVariableDeclaration();
modifierNode.setModifiers(Modifier.FINAL);
modifierNode.setExtraDimensions(1);
rewrite.markAsModified(decl, modifierNode);
ArrayType newVarType= ast.newArrayType(ast.newPrimitiveType(PrimitiveType.FLOAT), 2);
rewrite.markAsReplaced(decl.getType(), newVarType);
Name newName= ast.newSimpleName("count");
rewrite.markAsReplaced(decl.getName(), newName);
}
{ // remove modifier, change type
SingleVariableDeclaration decl= (SingleVariableDeclaration) arguments.get(1);
SingleVariableDeclaration modifierNode= ast.newSingleVariableDeclaration();
modifierNode.setModifiers(0);
modifierNode.setExtraDimensions(decl.getExtraDimensions()); // no change
rewrite.markAsModified(decl, modifierNode);
Type newVarType= ast.newPrimitiveType(PrimitiveType.FLOAT);
rewrite.markAsReplaced(decl.getType(), newVarType);
}
{ // remove extra dim
SingleVariableDeclaration decl= (SingleVariableDeclaration) arguments.get(2);
SingleVariableDeclaration modifierNode= ast.newSingleVariableDeclaration();
modifierNode.setModifiers(decl.getModifiers()); // no change
modifierNode.setExtraDimensions(0);
rewrite.markAsModified(decl, modifierNode);
}
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null);
proposal.getCompilationUnitChange().setSave(true);
proposal.apply(null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(final float[][] count[], float k, int[] x) {\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
clearRewrite(rewrite);
}
public void testVariableDeclarationFragment() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" int i, j, k= 0, x[][], y[]= {0, 1};\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, false);
ASTRewrite rewrite= new ASTRewrite(astRoot);
AST ast= astRoot.getAST();
assertTrue("Parse errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0);
TypeDeclaration type= findTypeDeclaration(astRoot, "E");
MethodDeclaration methodDecl= findMethodDeclaration(type, "foo");
Block block= methodDecl.getBody();
List statements= block.statements();
assertTrue("Number of statements not 1", statements.size() == 1);
VariableDeclarationStatement variableDeclStatement= (VariableDeclarationStatement) statements.get(0);
List fragments= variableDeclStatement.fragments();
assertTrue("Number of fragments not 5", fragments.size() == 5);
{ // rename var, add dimension
VariableDeclarationFragment fragment= (VariableDeclarationFragment) fragments.get(0);
ASTNode name= ast.newSimpleName("a");
rewrite.markAsReplaced(fragment.getName(), name);
VariableDeclarationFragment modifierNode= ast.newVariableDeclarationFragment();
modifierNode.setExtraDimensions(2);
rewrite.markAsModified(fragment, modifierNode);
}
{ // add initializer
VariableDeclarationFragment fragment= (VariableDeclarationFragment) fragments.get(1);
Expression initializer= ast.newNumberLiteral("1");
rewrite.markAsInserted(initializer);
assertTrue("Has initializer", fragment.getInitializer() == null);
fragment.setInitializer(initializer);
}
{ // remove initializer
VariableDeclarationFragment fragment= (VariableDeclarationFragment) fragments.get(2);
assertTrue("Has no initializer", fragment.getInitializer() != null);
rewrite.markAsRemoved(fragment.getInitializer());
}
{ // add dimension, add initializer
VariableDeclarationFragment fragment= (VariableDeclarationFragment) fragments.get(3);
VariableDeclarationFragment modifierNode= ast.newVariableDeclarationFragment();
modifierNode.setExtraDimensions(4);
rewrite.markAsModified(fragment, modifierNode);
Expression initializer= ast.newNullLiteral();
rewrite.markAsInserted(initializer);
assertTrue("Has initializer", fragment.getInitializer() == null);
fragment.setInitializer(initializer);
}
{ // remove dimension
VariableDeclarationFragment fragment= (VariableDeclarationFragment) fragments.get(4);
VariableDeclarationFragment modifierNode= ast.newVariableDeclarationFragment();
modifierNode.setExtraDimensions(0);
rewrite.markAsModified(fragment, modifierNode);
}
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null);
proposal.getCompilationUnitChange().setSave(true);
proposal.apply(null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" int a[][], j = 1, k, x[][][][] = null, y= {0, 1};\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
clearRewrite(rewrite);
}
}
|
25,152 |
Bug 25152 Code format too tight when creating a missing method [code manipulation]
|
When you choose the quick fix 'create method', the code generated butts up below the method without a new line: } /** * Method precompile. */ private void precompile() { } instead of: } /** * Method precompile. */ private void precompile() { }
|
resolved fixed
|
027c529
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-09T09:53:35Z | 2002-10-21T22:40:00Z |
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/AssistQuickFixTest.java
|
package org.eclipse.jdt.ui.tests.quickfix;
import java.util.ArrayList;
import java.util.Hashtable;
import org.eclipse.swt.graphics.Point;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.Document;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.testplugin.JavaProjectHelper;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.correction.AssignToVariableAssistProposal;
import org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal;
import org.eclipse.jdt.internal.ui.text.correction.CorrectionContext;
import org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionProcessor;
public class AssistQuickFixTest extends QuickFixTest {
private static final Class THIS= AssistQuickFixTest.class;
private IJavaProject fJProject1;
private IPackageFragmentRoot fSourceFolder;
public AssistQuickFixTest(String name) {
super(name);
}
public static Test suite() {
if (true) {
return new TestSuite(THIS);
} else {
TestSuite suite= new TestSuite();
suite.addTest(new AssistQuickFixTest("testUnimplementedMethods2"));
return suite;
}
}
protected void setUp() throws Exception {
Hashtable options= JavaCore.getDefaultOptions();
options.put(JavaCore.FORMATTER_TAB_CHAR, JavaCore.SPACE);
options.put(JavaCore.FORMATTER_TAB_SIZE, "4");
JavaCore.setOptions(options);
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
store.setValue(PreferenceConstants.CODEGEN__FILE_COMMENTS, false);
store.setValue(PreferenceConstants.CODEGEN__JAVADOC_STUBS, false);
store.setValue(PreferenceConstants.CODEGEN_GETTERSETTER_PREFIX, "f");
store.setValue(PreferenceConstants.CODEGEN_GETTERSETTER_SUFFIX, "_m");
fJProject1= JavaProjectHelper.createJavaProject("TestProject1", "bin");
assertTrue("rt not found", JavaProjectHelper.addRTJar(fJProject1) != null);
fSourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
}
protected void tearDown() throws Exception {
JavaProjectHelper.delete(fJProject1);
}
public void testAssignToLocal() throws Exception {
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
store.setValue(PreferenceConstants.CODEGEN_USE_GETTERSETTER_PREFIX, true);
store.setValue(PreferenceConstants.CODEGEN_USE_GETTERSETTER_SUFFIX, false);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" getClass();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
int offset= buf.toString().indexOf("getClass()");
CorrectionContext context= getCorrectionContext(cu, offset, 0);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
boolean doField= true, doLocal= true;
for (int i= 0; i < proposals.size(); i++) {
Object curr= proposals.get(i);
if (!(curr instanceof AssignToVariableAssistProposal)) {
continue;
}
AssignToVariableAssistProposal proposal= (AssignToVariableAssistProposal) curr;
if (proposal.getVariableKind() == AssignToVariableAssistProposal.FIELD) {
assertTrue("same proposal kind", doField);
doField= false;
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private Class fClass;\n");
buf.append(" public void foo() {\n");
buf.append(" fClass = getClass();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
Point selection= proposal.getSelection(new Document(preview));
assertEquals("wrong selection", "fClass", preview.substring(selection.x, selection.x + selection.y));
} else if (proposal.getVariableKind() == AssignToVariableAssistProposal.LOCAL) {
assertTrue("same proposal kind", doLocal);
doLocal= false;
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" Class c = getClass();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
Point selection= proposal.getSelection(new Document(preview));
assertEquals("wrong selection", "c", preview.substring(selection.x, selection.x + selection.y));
}
}
}
public void testAssignToLocal2() throws Exception {
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
store.setValue(PreferenceConstants.CODEGEN_USE_GETTERSETTER_PREFIX, true);
store.setValue(PreferenceConstants.CODEGEN_USE_GETTERSETTER_SUFFIX, false);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" public Vector goo() {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" goo().iterator();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
int offset= buf.toString().indexOf("goo().iterator()");
CorrectionContext context= getCorrectionContext(cu, offset, 0);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
boolean doField= true, doLocal= true;
for (int i= 0; i < proposals.size(); i++) {
Object curr= proposals.get(i);
if (!(curr instanceof AssignToVariableAssistProposal)) {
continue;
}
AssignToVariableAssistProposal proposal= (AssignToVariableAssistProposal) curr;
if (proposal.getVariableKind() == AssignToVariableAssistProposal.FIELD) {
assertTrue("same proposal kind", doField);
doField= false;
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Iterator;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" private Iterator fIterator;\n");
buf.append(" public Vector goo() {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" fIterator = goo().iterator();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
Point selection= proposal.getSelection(new Document(preview));
assertEquals("wrong selection", "fIterator", preview.substring(selection.x, selection.x + selection.y));
} else if (proposal.getVariableKind() == AssignToVariableAssistProposal.LOCAL) {
assertTrue("same proposal kind", doLocal);
doLocal= false;
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Iterator;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" public Vector goo() {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" Iterator iterator = goo().iterator();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
Point selection= proposal.getSelection(new Document(preview));
assertEquals("wrong selection", "iterator", preview.substring(selection.x, selection.x + selection.y));
}
}
}
public void testAssignToLocal2CursorAtEnd() throws Exception {
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
store.setValue(PreferenceConstants.CODEGEN_USE_GETTERSETTER_PREFIX, false);
store.setValue(PreferenceConstants.CODEGEN_USE_GETTERSETTER_SUFFIX, true);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" public Vector goo() {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" goo().toArray();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
String str= "goo().toArray();";
CorrectionContext context= getCorrectionContext(cu, buf.toString().indexOf(str) + str.length(), 0);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
boolean doField= true, doLocal= true;
for (int i= 0; i < proposals.size(); i++) {
AssignToVariableAssistProposal proposal= (AssignToVariableAssistProposal) proposals.get(i);
if (proposal.getVariableKind() == AssignToVariableAssistProposal.FIELD) {
assertTrue("same proposal kind", doField);
doField= false;
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" private Object[] objects_m;\n");
buf.append(" public Vector goo() {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" objects_m = goo().toArray();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
Point selection= proposal.getSelection(new Document(preview));
assertEquals("wrong selection", "objects_m", preview.substring(selection.x, selection.x + selection.y));
} else if (proposal.getVariableKind() == AssignToVariableAssistProposal.LOCAL) {
assertTrue("same proposal kind", doLocal);
doLocal= false;
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" public Vector goo() {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" Object[] objects = goo().toArray();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
Point selection= proposal.getSelection(new Document(preview));
assertEquals("wrong selection", "objects", preview.substring(selection.x, selection.x + selection.y));
}
}
}
public void testReplaceCatchClauseWithThrowsWithFinally() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" } finally {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
String str= "(IOException e)";
CorrectionContext context= getCorrectionContext(cu, buf.toString().indexOf(str), 0);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void foo() throws IOException {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } finally {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testReplaceSingleCatchClauseWithThrows() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
String str= "(IOException e)";
CorrectionContext context= getCorrectionContext(cu, buf.toString().indexOf(str) + str.length(), 0);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void foo() throws IOException {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
}
|
25,152 |
Bug 25152 Code format too tight when creating a missing method [code manipulation]
|
When you choose the quick fix 'create method', the code generated butts up below the method without a new line: } /** * Method precompile. */ private void precompile() { } instead of: } /** * Method precompile. */ private void precompile() { }
|
resolved fixed
|
027c529
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-09T09:53:35Z | 2002-10-21T22:40:00Z |
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/LocalCorrectionsQuickFixTest.java
|
package org.eclipse.jdt.ui.tests.quickfix;
import java.util.ArrayList;
import java.util.Hashtable;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.testplugin.JavaProjectHelper;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal;
import org.eclipse.jdt.internal.ui.text.correction.CorrectionContext;
import org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionProcessor;
public class LocalCorrectionsQuickFixTest extends QuickFixTest {
private static final Class THIS= LocalCorrectionsQuickFixTest.class;
private IJavaProject fJProject1;
private IPackageFragmentRoot fSourceFolder;
public LocalCorrectionsQuickFixTest(String name) {
super(name);
}
public static Test suite() {
if (true) {
return new TestSuite(THIS);
} else {
TestSuite suite= new TestSuite();
suite.addTest(new LocalCorrectionsQuickFixTest("testUncaughtExceptionOnThis"));
return suite;
}
}
protected void setUp() throws Exception {
Hashtable options= JavaCore.getDefaultOptions();
options.put(JavaCore.FORMATTER_TAB_CHAR, JavaCore.SPACE);
options.put(JavaCore.FORMATTER_TAB_SIZE, "4");
options.put(JavaCore.COMPILER_PB_STATIC_ACCESS_RECEIVER, JavaCore.ERROR);
JavaCore.setOptions(options);
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
store.setValue(PreferenceConstants.CODEGEN__FILE_COMMENTS, false);
store.setValue(PreferenceConstants.CODEGEN__JAVADOC_STUBS, false);
fJProject1= JavaProjectHelper.createJavaProject("TestProject1", "bin");
assertTrue("rt not found", JavaProjectHelper.addRTJar(fJProject1) != null);
fSourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
}
protected void tearDown() throws Exception {
JavaProjectHelper.delete(fJProject1);
}
public void testFieldAccessToStatic() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.File;\n");
buf.append("public class E {\n");
buf.append(" public char foo() {\n");
buf.append(" return (new File(\"x.txt\")).separatorChar;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.File;\n");
buf.append("public class E {\n");
buf.append(" public char foo() {\n");
buf.append(" return File.separatorChar;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testInheritedAccessOnStatic() throws Exception {
IPackageFragment pack0= fSourceFolder.createPackageFragment("pack", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package pack;\n");
buf.append("public class A {\n");
buf.append(" public static void foo() {\n");
buf.append(" }\n");
buf.append("}\n");
pack0.createCompilationUnit("A.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package pack;\n");
buf.append("public class B extends A {\n");
buf.append("}\n");
pack0.createCompilationUnit("B.java", buf.toString(), false, null);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import pack.B;\n");
buf.append("public class E {\n");
buf.append(" public void foo(B b) {\n");
buf.append(" b.foo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import pack.B;\n");
buf.append("public class E {\n");
buf.append(" public void foo(B b) {\n");
buf.append(" B.foo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import pack.A;\n");
buf.append("import pack.B;\n");
buf.append("public class E {\n");
buf.append(" public void foo(B b) {\n");
buf.append(" A.foo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testQualifiedAccessToStatic() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Thread t) {\n");
buf.append(" t.sleep(10);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Thread t) {\n");
buf.append(" Thread.sleep(10);\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testThisAccessToStatic() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public static void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" this.goo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public static void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" E.goo();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testCastMissingInVarDecl() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Object o) {\n");
buf.append(" Thread th= o;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Object o) {\n");
buf.append(" Thread th= (Thread) o;\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Object o) {\n");
buf.append(" Object th= o;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testCastMissingInVarDecl2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.List;\n");
buf.append("public class Container {\n");
buf.append(" public List[] getLists() {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("Container.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Container c) {\n");
buf.append(" ArrayList[] lists= c.getLists();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Container c) {\n");
buf.append(" ArrayList[] lists= (ArrayList[]) c.getLists();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Container c) {\n");
buf.append(" List[] lists= c.getLists();\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testCastMissingInFieldDecl() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" int time= System.currentTimeMillis();\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" int time= (int) System.currentTimeMillis();\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" long time= System.currentTimeMillis();\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testCastMissingInAssignment() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Iterator;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Iterator iter) {\n");
buf.append(" String str;\n");
buf.append(" str= iter.next();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Iterator;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Iterator iter) {\n");
buf.append(" String str;\n");
buf.append(" str= (String) iter.next();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testCastMissingInExpression() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public String[] foo(List list) {\n");
buf.append(" return list.toArray(new List[list.size()]);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public String[] foo(List list) {\n");
buf.append(" return (String[]) list.toArray(new List[list.size()]);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public Object[] foo(List list) {\n");
buf.append(" return list.toArray(new List[list.size()]);\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testCastOnCastExpression() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public void foo(List list) {\n");
buf.append(" ArrayList a= (Cloneable) list;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public void foo(List list) {\n");
buf.append(" ArrayList a= (ArrayList) list;\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public void foo(List list) {\n");
buf.append(" Cloneable a= (Cloneable) list;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUncaughtException() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() throws IOException {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUncaughtException2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public String goo() throws IOException {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" goo().substring(2);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public String goo() throws IOException {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append(" public void foo() throws IOException {\n");
buf.append(" goo().substring(2);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public String goo() throws IOException {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo().substring(2);\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUncaughtExceptionRemoveMoreSpecific() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.net.SocketException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" public void foo() throws SocketException {\n");
buf.append(" this.goo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.net.SocketException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" public void foo() throws IOException {\n");
buf.append(" this.goo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.net.SocketException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" public void foo() throws SocketException {\n");
buf.append(" try {\n");
buf.append(" this.goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUncaughtExceptionOnSuper() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.FileInputStream;\n");
buf.append("public class E extends FileInputStream {\n");
buf.append(" public E() {\n");
buf.append(" super(\"x\");\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.FileInputStream;\n");
buf.append("import java.io.FileNotFoundException;\n");
buf.append("public class E extends FileInputStream {\n");
buf.append(" public E() throws FileNotFoundException {\n");
buf.append(" super(\"x\");\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUncaughtExceptionOnThis() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public E() {\n");
buf.append(" this(null);\n");
buf.append(" }\n");
buf.append(" public E(Object x) throws IOException {\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public E() throws IOException {\n");
buf.append(" this(null);\n");
buf.append(" }\n");
buf.append(" public E(Object x) throws IOException {\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
boolean BUG_25417= true;
public void testUncaughtExceptionDuplicate() throws Exception {
if (BUG_25417) {
return;
}
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class MyException extends Exception {\n");
buf.append("}\n");
pack1.createCompilationUnit("MyException.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void m1() throws IOException {\n");
buf.append(" m2();\n");
buf.append(" }\n");
buf.append(" public void m2() throws IOException, ParseException, MyException {\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 2);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void m1() throws IOException, ParseException, MyException {\n");
buf.append(" m2();\n");
buf.append(" }\n");
buf.append(" public void m2() throws IOException, ParseException, MyException {\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void m1() throws IOException {\n");
buf.append(" try {\n");
buf.append(" m2();\n");
buf.append(" } catch (ParseException e) {\n");
buf.append(" } catch (MyException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" public void m2() throws IOException, ParseException, MyException {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testMultipleUncaughtExceptions() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException, ParseException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 2); // 2 uncaught exceptions
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException, ParseException {\n");
buf.append(" }\n");
buf.append(" public void foo() throws IOException, ParseException {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException, ParseException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" } catch (ParseException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUnneededCatchBlock() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" } catch (ParseException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnneededCatchBlockSingle() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnneededCatchBlockWithFinally() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" } finally {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } finally {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnimplementedMethods() throws Exception {
IPackageFragment pack2= fSourceFolder.createPackageFragment("test2", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test2;\n");
buf.append("import java.io.IOException;\n");
buf.append("public interface Inter {\n");
buf.append(" int getCount(Object[] o) throws IOException;\n");
buf.append("}\n");
pack2.createCompilationUnit("Inter.java", buf.toString(), false, null);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import test2.Inter;\n");
buf.append("public class E implements Inter{\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import test2.Inter;\n");
buf.append("public abstract class E implements Inter{\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("\n");
buf.append("import test2.Inter;\n");
buf.append("public class E implements Inter{\n");
buf.append(" public int getCount(Object[] o) throws IOException {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUnimplementedMethods2() throws Exception {
IPackageFragment pack2= fSourceFolder.createPackageFragment("test2", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test2;\n");
buf.append("import java.io.IOException;\n");
buf.append("public interface Inter {\n");
buf.append(" int getCount(Object[] o) throws IOException;\n");
buf.append("}\n");
pack2.createCompilationUnit("Inter.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test2;\n");
buf.append("import java.io.IOException;\n");
buf.append("public abstract class InterImpl implements Inter {\n");
buf.append(" protected abstract int[] getMusic() throws IOException;\n");
buf.append("}\n");
pack2.createCompilationUnit("InterImpl.java", buf.toString(), false, null);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import test2.InterImpl;\n");
buf.append("public class E extends InterImpl {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 2);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import test2.InterImpl;\n");
buf.append("public abstract class E extends InterImpl {\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("\n");
buf.append("import test2.InterImpl;\n");
buf.append("public class E extends InterImpl {\n");
buf.append(" protected int[] getMusic() throws IOException {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append(" public int getCount(Object[] o) throws IOException {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUnitializedVariable() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" int s;\n");
buf.append(" try {\n");
buf.append(" s= 1;\n");
buf.append(" } catch (Exception e) {\n");
buf.append(" System.out.println(s);\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" int s = 0;\n");
buf.append(" try {\n");
buf.append(" s= 1;\n");
buf.append(" } catch (Exception e) {\n");
buf.append(" System.out.println(s);\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
}
|
25,152 |
Bug 25152 Code format too tight when creating a missing method [code manipulation]
|
When you choose the quick fix 'create method', the code generated butts up below the method without a new line: } /** * Method precompile. */ private void precompile() { } instead of: } /** * Method precompile. */ private void precompile() { }
|
resolved fixed
|
027c529
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-09T09:53:35Z | 2002-10-21T22:40:00Z |
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/UnresolvedMethodsQuickFixTest.java
|
package org.eclipse.jdt.ui.tests.quickfix;
import java.util.ArrayList;
import java.util.Hashtable;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.testplugin.JavaProjectHelper;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.correction.CorrectionContext;
import org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionProcessor;
import org.eclipse.jdt.internal.ui.text.correction.NewMethodCompletionProposal;
public class UnresolvedMethodsQuickFixTest extends QuickFixTest {
private static final Class THIS= UnresolvedMethodsQuickFixTest.class;
private IJavaProject fJProject1;
private IPackageFragmentRoot fSourceFolder;
public UnresolvedMethodsQuickFixTest(String name) {
super(name);
}
public static Test suite() {
if (false) {
return new TestSuite(THIS);
} else {
TestSuite suite= new TestSuite();
suite.addTest(new UnresolvedMethodsQuickFixTest("testSuperMethodInvocation"));
return suite;
}
}
protected void setUp() throws Exception {
Hashtable options= JavaCore.getDefaultOptions();
options.put(JavaCore.FORMATTER_TAB_CHAR, JavaCore.SPACE);
options.put(JavaCore.FORMATTER_TAB_SIZE, "4");
JavaCore.setOptions(options);
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
store.setValue(PreferenceConstants.CODEGEN__FILE_COMMENTS, false);
store.setValue(PreferenceConstants.CODEGEN__JAVADOC_STUBS, false);
fJProject1= JavaProjectHelper.createJavaProject("TestProject1", "bin");
assertTrue("rt not found", JavaProjectHelper.addRTJar(fJProject1) != null);
fSourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
}
protected void tearDown() throws Exception {
JavaProjectHelper.delete(fJProject1);
}
public void testMethodInSameType() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append(" private int goo(Vector vec, boolean b) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodInSameTypeUsingThis() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= this.goo(vec, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= this.goo(vec, true);\n");
buf.append(" }\n");
buf.append(" private int goo(Vector vec, boolean b) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodInDifferentClass() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" void foo(X x) {\n");
buf.append(" boolean i= x.goo(1, 2.1);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append("}\n");
pack1.createCompilationUnit("X.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public boolean goo(int i, double d) {\n");
buf.append(" return false;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodInDifferentInterface() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" void foo(X x) {\n");
buf.append(" boolean i= x.goo(getClass());\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public interface X {\n");
buf.append("}\n");
pack1.createCompilationUnit("X.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public interface X {\n");
buf.append(" boolean goo(Class c);\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testSuperConstructor() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends A {\n");
buf.append(" public E(int i) {\n");
buf.append(" super(i);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1=pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append("}\n");
pack1.createCompilationUnit("A.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu1, problems[0]);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append(" public A(int i) {\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testClassInstanceCreation() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" A a= new A(i);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1=pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append("}\n");
pack1.createCompilationUnit("A.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu1, problems[0]);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append(" public A(int i) {\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testConstructorInvocation() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public E(int i) {\n");
buf.append(" this(i, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1=pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu1, problems[0]);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public E(int i) {\n");
buf.append(" this(i, true);\n");
buf.append(" }\n");
buf.append(" public E(int i, boolean b) {\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testSuperMethodInvocation() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends A {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" super.foo(i);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1=pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append("}\n");
pack1.createCompilationUnit("A.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu1, problems[0]);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
}
|
25,152 |
Bug 25152 Code format too tight when creating a missing method [code manipulation]
|
When you choose the quick fix 'create method', the code generated butts up below the method without a new line: } /** * Method precompile. */ private void precompile() { } instead of: } /** * Method precompile. */ private void precompile() { }
|
resolved fixed
|
027c529
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-09T09:53:35Z | 2002-10-21T22:40:00Z |
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/UnresolvedVariablesQuickFixTest.java
|
package org.eclipse.jdt.ui.tests.quickfix;
import java.util.ArrayList;
import java.util.Hashtable;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.testplugin.JavaProjectHelper;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal;
import org.eclipse.jdt.internal.ui.text.correction.CorrectionContext;
import org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionProcessor;
import org.eclipse.jdt.internal.ui.text.correction.NewCUCompletionUsingWizardProposal;
import org.eclipse.jdt.internal.ui.text.correction.NewVariableCompletionProposal;
public class UnresolvedVariablesQuickFixTest extends QuickFixTest {
private static final Class THIS= UnresolvedVariablesQuickFixTest.class;
private IJavaProject fJProject1;
private IPackageFragmentRoot fSourceFolder;
public UnresolvedVariablesQuickFixTest(String name) {
super(name);
}
public static Test suite() {
if (false) {
return new TestSuite(THIS);
} else {
TestSuite suite= new TestSuite();
suite.addTest(new UnresolvedVariablesQuickFixTest("testVarAndTypeRef"));
return suite;
}
}
protected void setUp() throws Exception {
Hashtable options= JavaCore.getDefaultOptions();
options.put(JavaCore.FORMATTER_TAB_CHAR, JavaCore.SPACE);
options.put(JavaCore.FORMATTER_TAB_SIZE, "4");
options.put(JavaCore.COMPILER_PB_UNUSED_IMPORT, JavaCore.IGNORE);
JavaCore.setOptions(options);
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
store.setValue(PreferenceConstants.CODEGEN__FILE_COMMENTS, false);
store.setValue(PreferenceConstants.CODEGEN__JAVADOC_STUBS, false);
fJProject1= JavaProjectHelper.createJavaProject("TestProject1", "bin");
assertTrue("rt not found", JavaProjectHelper.addRTJar(fJProject1) != null);
fSourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
}
protected void tearDown() throws Exception {
JavaProjectHelper.delete(fJProject1);
}
public void testVarInAssignment() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" iter= vec.iterator();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
boolean doField= true, doParam= true, doLocal= true;
for (int i= 0; i < proposals.size(); i++) {
NewVariableCompletionProposal proposal= (NewVariableCompletionProposal) proposals.get(i);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
if (proposal.getVariableKind() == NewVariableCompletionProposal.FIELD) {
assertTrue("2 field proposals", doField);
doField= false;
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Iterator;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" private Iterator iter;\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" iter= vec.iterator();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
} else if (proposal.getVariableKind() == NewVariableCompletionProposal.LOCAL) {
assertTrue("2 local proposals", doLocal);
doLocal= false;
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Iterator;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" Iterator iter = vec.iterator();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
} else if (proposal.getVariableKind() == NewVariableCompletionProposal.PARAM) {
assertTrue("2 param proposals", doParam);
doParam= false;
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Iterator;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" void foo(Vector vec, Iterator iter) {\n");
buf.append(" iter= vec.iterator();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
} else {
assertTrue("unknown type", false);
}
}
}
public void testVarInForInitializer() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" void foo() {\n");
buf.append(" for (i= 0;;) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
boolean doField= true, doParam= true, doLocal= true;
for (int i= 0; i < proposals.size(); i++) {
NewVariableCompletionProposal proposal= (NewVariableCompletionProposal) proposals.get(i);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
if (proposal.getVariableKind() == NewVariableCompletionProposal.FIELD) {
assertTrue("2 field proposals", doField);
doField= false;
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private int i;\n");
buf.append(" void foo() {\n");
buf.append(" for (i= 0;;) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
} else if (proposal.getVariableKind() == NewVariableCompletionProposal.LOCAL) {
assertTrue("2 local proposals", doLocal);
doLocal= false;
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" void foo() {\n");
buf.append(" for (int i = 0;;) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
} else if (proposal.getVariableKind() == NewVariableCompletionProposal.PARAM) {
assertTrue("2 param proposals", doParam);
doParam= false;
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" void foo(int i) {\n");
buf.append(" for (i= 0;;) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
} else {
assertTrue("unknown type", false);
}
}
}
public void testVarInInitializer() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private int i= k;\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewVariableCompletionProposal proposal= (NewVariableCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private int k;\n");
buf.append(" private int i= k;\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testVarInOtherType() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class F {\n");
buf.append(" void foo(E e) {\n");
buf.append(" e.var2= 2;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("F.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private int var1;\n");
buf.append("}\n");
pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu1, problems[0]);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
boolean doNew= true, doChange= true;
for (int i= 0; i < proposals.size(); i++) {
Object curr= proposals.get(i);
if (curr instanceof NewVariableCompletionProposal) {
assertTrue("2 new proposals", doNew);
doNew= false;
NewVariableCompletionProposal proposal= (NewVariableCompletionProposal) curr;
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private int var1;\n");
buf.append(" public int var2;\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
} else if (curr instanceof CUCorrectionProposal) {
assertTrue("2 replace proposals", doChange);
doChange= false;
CUCorrectionProposal proposal= (CUCorrectionProposal) curr;
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class F {\n");
buf.append(" void foo(E e) {\n");
buf.append(" e.var1= 2;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
}
}
public void testLongVarRef() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class F {\n");
buf.append(" void foo(E e) {\n");
buf.append(" e.var.x= 2;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("F.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public F var;\n");
buf.append("}\n");
pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu1, problems[0]);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewVariableCompletionProposal proposal= (NewVariableCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class F {\n");
buf.append(" private int x;\n");
buf.append(" void foo(E e) {\n");
buf.append(" e.var.x= 2;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testVarAndTypeRef() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.File;\n");
buf.append("public class F {\n");
buf.append(" void foo() {\n");
buf.append(" char ch= Fixe.pathSeparatorChar;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("F.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu1, problems[0]);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 6);
assertCorrectLabels(proposals);
boolean doField= true, doParam= true, doLocal= true, doInterface= true, doClass= true, doChange= true;
for (int i= 0; i < proposals.size(); i++) {
Object curr= proposals.get(i);
if (curr instanceof NewVariableCompletionProposal) {
NewVariableCompletionProposal proposal= (NewVariableCompletionProposal) proposals.get(i);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
if (proposal.getVariableKind() == NewVariableCompletionProposal.FIELD) {
assertTrue("2 field proposals", doField);
doField= false;
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.File;\n");
buf.append("public class F {\n");
buf.append(" private Object Fixe;\n");
buf.append(" void foo() {\n");
buf.append(" char ch= Fixe.pathSeparatorChar;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
} else if (proposal.getVariableKind() == NewVariableCompletionProposal.LOCAL) {
assertTrue("2 local proposals", doLocal);
doLocal= false;
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.File;\n");
buf.append("public class F {\n");
buf.append(" void foo() {\n");
buf.append(" Object Fixe = null;\n");
buf.append(" char ch= Fixe.pathSeparatorChar;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
} else if (proposal.getVariableKind() == NewVariableCompletionProposal.PARAM) {
assertTrue("2 param proposals", doParam);
doParam= false;
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.File;\n");
buf.append("public class F {\n");
buf.append(" void foo(Object Fixe) {\n");
buf.append(" char ch= Fixe.pathSeparatorChar;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
} else {
assertTrue("unknown type", false);
}
} else if (curr instanceof NewCUCompletionUsingWizardProposal) {
NewCUCompletionUsingWizardProposal proposal= (NewCUCompletionUsingWizardProposal) curr;
proposal.setShowDialog(false);
proposal.apply(null);
ICompilationUnit newCU= pack1.getCompilationUnit("Fixe.java");
assertTrue("Nothing created", newCU.exists());
if (proposal.isClass()) {
assertTrue("2 class proposals", doClass);
doClass= false;
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("\n");
buf.append("public class Fixe {\n");
buf.append("\n");
buf.append("}\n");
assertEqualStringIgnoreDelim(newCU.getSource(), buf.toString());
JavaProjectHelper.performDummySearch();
newCU.delete(true, null);
} else {
assertTrue("2 interface proposals", doInterface);
doInterface= false;
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("\n");
buf.append("public interface Fixe {\n");
buf.append("\n");
buf.append("}\n");
assertEqualStringIgnoreDelim(newCU.getSource(), buf.toString());
JavaProjectHelper.performDummySearch();
newCU.delete(true, null);
}
} else {
assertTrue("2 replace proposals", doChange);
doChange= false;
CUCorrectionProposal proposal= (CUCorrectionProposal) curr;
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.File;\n");
buf.append("public class F {\n");
buf.append(" void foo() {\n");
buf.append(" char ch= File.pathSeparatorChar;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
}
}
}
|
25,152 |
Bug 25152 Code format too tight when creating a missing method [code manipulation]
|
When you choose the quick fix 'create method', the code generated butts up below the method without a new line: } /** * Method precompile. */ private void precompile() { } instead of: } /** * Method precompile. */ private void precompile() { }
|
resolved fixed
|
027c529
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-09T09:53:35Z | 2002-10-21T22:40:00Z |
org.eclipse.jdt.ui/core
| |
25,152 |
Bug 25152 Code format too tight when creating a missing method [code manipulation]
|
When you choose the quick fix 'create method', the code generated butts up below the method without a new line: } /** * Method precompile. */ private void precompile() { } instead of: } /** * Method precompile. */ private void precompile() { }
|
resolved fixed
|
027c529
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-09T09:53:35Z | 2002-10-21T22:40:00Z |
extension/org/eclipse/jdt/internal/corext/dom/ASTRewriteAnalyzer.java
| |
29,161 |
Bug 29161 Quickfix can't fix a simple fix [quick fix]
|
If I have a class like this: public class Foo { private static final String BAR = "bar"; public Foo () { System.out.println(this.BAR); } } There's a light bulb on the 'this.BAR' line, which says "The static field Foo.BAR should be accessed in a static way", but says "No corrections available" when I click on it. The fix is simply removing 'this', ie "this.BAR" becomes only "BAR". It's a very simple correction, I think quick fix should know about it.
|
resolved fixed
|
c3ce08e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-09T11:31:10Z | 2003-01-08T18:20:00Z |
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/LocalCorrectionsQuickFixTest.java
|
package org.eclipse.jdt.ui.tests.quickfix;
import java.util.ArrayList;
import java.util.Hashtable;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.testplugin.JavaProjectHelper;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal;
import org.eclipse.jdt.internal.ui.text.correction.CorrectionContext;
import org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionProcessor;
public class LocalCorrectionsQuickFixTest extends QuickFixTest {
private static final Class THIS= LocalCorrectionsQuickFixTest.class;
private IJavaProject fJProject1;
private IPackageFragmentRoot fSourceFolder;
public LocalCorrectionsQuickFixTest(String name) {
super(name);
}
public static Test suite() {
if (true) {
return new TestSuite(THIS);
} else {
TestSuite suite= new TestSuite();
suite.addTest(new LocalCorrectionsQuickFixTest("testUncaughtExceptionOnThis"));
return suite;
}
}
protected void setUp() throws Exception {
Hashtable options= JavaCore.getDefaultOptions();
options.put(JavaCore.FORMATTER_TAB_CHAR, JavaCore.SPACE);
options.put(JavaCore.FORMATTER_TAB_SIZE, "4");
options.put(JavaCore.COMPILER_PB_STATIC_ACCESS_RECEIVER, JavaCore.ERROR);
JavaCore.setOptions(options);
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
store.setValue(PreferenceConstants.CODEGEN__FILE_COMMENTS, false);
store.setValue(PreferenceConstants.CODEGEN__JAVADOC_STUBS, false);
fJProject1= JavaProjectHelper.createJavaProject("TestProject1", "bin");
assertTrue("rt not found", JavaProjectHelper.addRTJar(fJProject1) != null);
fSourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
}
protected void tearDown() throws Exception {
JavaProjectHelper.delete(fJProject1);
}
public void testFieldAccessToStatic() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.File;\n");
buf.append("public class E {\n");
buf.append(" public char foo() {\n");
buf.append(" return (new File(\"x.txt\")).separatorChar;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.File;\n");
buf.append("public class E {\n");
buf.append(" public char foo() {\n");
buf.append(" return File.separatorChar;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testInheritedAccessOnStatic() throws Exception {
IPackageFragment pack0= fSourceFolder.createPackageFragment("pack", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package pack;\n");
buf.append("public class A {\n");
buf.append(" public static void foo() {\n");
buf.append(" }\n");
buf.append("}\n");
pack0.createCompilationUnit("A.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package pack;\n");
buf.append("public class B extends A {\n");
buf.append("}\n");
pack0.createCompilationUnit("B.java", buf.toString(), false, null);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import pack.B;\n");
buf.append("public class E {\n");
buf.append(" public void foo(B b) {\n");
buf.append(" b.foo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import pack.B;\n");
buf.append("public class E {\n");
buf.append(" public void foo(B b) {\n");
buf.append(" B.foo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import pack.A;\n");
buf.append("import pack.B;\n");
buf.append("public class E {\n");
buf.append(" public void foo(B b) {\n");
buf.append(" A.foo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testQualifiedAccessToStatic() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Thread t) {\n");
buf.append(" t.sleep(10);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Thread t) {\n");
buf.append(" Thread.sleep(10);\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testThisAccessToStatic() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public static void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" this.goo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public static void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" E.goo();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testCastMissingInVarDecl() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Object o) {\n");
buf.append(" Thread th= o;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Object o) {\n");
buf.append(" Thread th= (Thread) o;\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Object o) {\n");
buf.append(" Object th= o;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testCastMissingInVarDecl2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.List;\n");
buf.append("public class Container {\n");
buf.append(" public List[] getLists() {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("Container.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Container c) {\n");
buf.append(" ArrayList[] lists= c.getLists();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Container c) {\n");
buf.append(" ArrayList[] lists= (ArrayList[]) c.getLists();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Container c) {\n");
buf.append(" List[] lists= c.getLists();\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testCastMissingInFieldDecl() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" int time= System.currentTimeMillis();\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" int time= (int) System.currentTimeMillis();\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" long time= System.currentTimeMillis();\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testCastMissingInAssignment() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Iterator;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Iterator iter) {\n");
buf.append(" String str;\n");
buf.append(" str= iter.next();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Iterator;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Iterator iter) {\n");
buf.append(" String str;\n");
buf.append(" str= (String) iter.next();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testCastMissingInExpression() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public String[] foo(List list) {\n");
buf.append(" return list.toArray(new List[list.size()]);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public String[] foo(List list) {\n");
buf.append(" return (String[]) list.toArray(new List[list.size()]);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public Object[] foo(List list) {\n");
buf.append(" return list.toArray(new List[list.size()]);\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testCastOnCastExpression() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public void foo(List list) {\n");
buf.append(" ArrayList a= (Cloneable) list;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public void foo(List list) {\n");
buf.append(" ArrayList a= (ArrayList) list;\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public void foo(List list) {\n");
buf.append(" Cloneable a= (Cloneable) list;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUncaughtException() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() throws IOException {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUncaughtException2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public String goo() throws IOException {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" goo().substring(2);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public String goo() throws IOException {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append(" public void foo() throws IOException {\n");
buf.append(" goo().substring(2);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public String goo() throws IOException {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo().substring(2);\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUncaughtExceptionRemoveMoreSpecific() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.net.SocketException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" public void foo() throws SocketException {\n");
buf.append(" this.goo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.net.SocketException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" public void foo() throws IOException {\n");
buf.append(" this.goo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.net.SocketException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" public void foo() throws SocketException {\n");
buf.append(" try {\n");
buf.append(" this.goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUncaughtExceptionOnSuper() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.FileInputStream;\n");
buf.append("public class E extends FileInputStream {\n");
buf.append(" public E() {\n");
buf.append(" super(\"x\");\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.FileInputStream;\n");
buf.append("import java.io.FileNotFoundException;\n");
buf.append("public class E extends FileInputStream {\n");
buf.append(" public E() throws FileNotFoundException {\n");
buf.append(" super(\"x\");\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUncaughtExceptionOnThis() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public E() {\n");
buf.append(" this(null);\n");
buf.append(" }\n");
buf.append(" public E(Object x) throws IOException {\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public E() throws IOException {\n");
buf.append(" this(null);\n");
buf.append(" }\n");
buf.append(" public E(Object x) throws IOException {\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
boolean BUG_25417= true;
public void testUncaughtExceptionDuplicate() throws Exception {
if (BUG_25417) {
return;
}
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class MyException extends Exception {\n");
buf.append("}\n");
pack1.createCompilationUnit("MyException.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void m1() throws IOException {\n");
buf.append(" m2();\n");
buf.append(" }\n");
buf.append(" public void m2() throws IOException, ParseException, MyException {\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 2);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void m1() throws IOException, ParseException, MyException {\n");
buf.append(" m2();\n");
buf.append(" }\n");
buf.append(" public void m2() throws IOException, ParseException, MyException {\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void m1() throws IOException {\n");
buf.append(" try {\n");
buf.append(" m2();\n");
buf.append(" } catch (ParseException e) {\n");
buf.append(" } catch (MyException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" public void m2() throws IOException, ParseException, MyException {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testMultipleUncaughtExceptions() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException, ParseException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 2); // 2 uncaught exceptions
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException, ParseException {\n");
buf.append(" }\n");
buf.append(" public void foo() throws IOException, ParseException {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException, ParseException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" } catch (ParseException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUnneededCatchBlock() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" } catch (ParseException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnneededCatchBlockSingle() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnneededCatchBlockWithFinally() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" } finally {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } finally {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnimplementedMethods() throws Exception {
IPackageFragment pack2= fSourceFolder.createPackageFragment("test2", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test2;\n");
buf.append("import java.io.IOException;\n");
buf.append("public interface Inter {\n");
buf.append(" int getCount(Object[] o) throws IOException;\n");
buf.append("}\n");
pack2.createCompilationUnit("Inter.java", buf.toString(), false, null);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import test2.Inter;\n");
buf.append("public class E implements Inter{\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import test2.Inter;\n");
buf.append("public abstract class E implements Inter{\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("\n");
buf.append("import test2.Inter;\n");
buf.append("public class E implements Inter{\n");
buf.append("\n");
buf.append(" public int getCount(Object[] o) throws IOException {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUnimplementedMethods2() throws Exception {
IPackageFragment pack2= fSourceFolder.createPackageFragment("test2", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test2;\n");
buf.append("import java.io.IOException;\n");
buf.append("public interface Inter {\n");
buf.append(" int getCount(Object[] o) throws IOException;\n");
buf.append("}\n");
pack2.createCompilationUnit("Inter.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test2;\n");
buf.append("import java.io.IOException;\n");
buf.append("public abstract class InterImpl implements Inter {\n");
buf.append(" protected abstract int[] getMusic() throws IOException;\n");
buf.append("}\n");
pack2.createCompilationUnit("InterImpl.java", buf.toString(), false, null);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import test2.InterImpl;\n");
buf.append("public class E extends InterImpl {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 2);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import test2.InterImpl;\n");
buf.append("public abstract class E extends InterImpl {\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("\n");
buf.append("import test2.InterImpl;\n");
buf.append("public class E extends InterImpl {\n");
buf.append("\n");
buf.append(" protected int[] getMusic() throws IOException {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" public int getCount(Object[] o) throws IOException {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUnitializedVariable() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" int s;\n");
buf.append(" try {\n");
buf.append(" s= 1;\n");
buf.append(" } catch (Exception e) {\n");
buf.append(" System.out.println(s);\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 1);
CorrectionContext context= getCorrectionContext(cu, problems[0]);
assertCorrectContext(context);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, proposals);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" int s = 0;\n");
buf.append(" try {\n");
buf.append(" s= 1;\n");
buf.append(" } catch (Exception e) {\n");
buf.append(" System.out.println(s);\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
}
|
29,161 |
Bug 29161 Quickfix can't fix a simple fix [quick fix]
|
If I have a class like this: public class Foo { private static final String BAR = "bar"; public Foo () { System.out.println(this.BAR); } } There's a light bulb on the 'this.BAR' line, which says "The static field Foo.BAR should be accessed in a static way", but says "No corrections available" when I click on it. The fix is simply removing 'this', ie "this.BAR" becomes only "BAR". It's a very simple correction, I think quick fix should know about it.
|
resolved fixed
|
c3ce08e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-09T11:31:10Z | 2003-01-08T18:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/LocalCorrectionsSubProcessor.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Renaud Waldura <[email protected]> - Access to static proposal
******************************************************************************/
package org.eclipse.jdt.internal.ui.text.correction;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.graphics.Image;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.dom.*;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.codemanipulation.ImportEdit;
import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory;
import org.eclipse.jdt.internal.corext.dom.ASTNodes;
import org.eclipse.jdt.internal.corext.dom.ASTRewrite;
import org.eclipse.jdt.internal.corext.dom.Selection;
import org.eclipse.jdt.internal.corext.refactoring.changes.CompilationUnitChange;
import org.eclipse.jdt.internal.corext.refactoring.nls.NLSRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.nls.NLSUtil;
import org.eclipse.jdt.internal.corext.refactoring.surround.ExceptionAnalyzer;
import org.eclipse.jdt.internal.corext.refactoring.surround.SurroundWithTryCatchRefactoring;
import org.eclipse.jdt.internal.corext.textmanipulation.TextEdit;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter;
import org.eclipse.jdt.internal.ui.refactoring.nls.ExternalizeWizard;
/**
*/
public class LocalCorrectionsSubProcessor {
public static void addCastProposals(ICorrectionContext context, List proposals) throws CoreException {
String[] args= context.getProblemArguments();
if (args.length != 2) {
return;
}
ICompilationUnit cu= context.getCompilationUnit();
String castType= args[1];
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= context.getCoveredNode();
if (!(selectedNode instanceof Expression)) {
return;
}
Expression nodeToCast= (Expression) selectedNode;
int parentNodeType= selectedNode.getParent().getNodeType();
if (parentNodeType == ASTNode.ASSIGNMENT) {
Assignment assign= (Assignment) selectedNode.getParent();
if (selectedNode.equals(assign.getLeftHandSide())) {
nodeToCast= assign.getRightHandSide();
}
} else if (parentNodeType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
VariableDeclarationFragment frag= (VariableDeclarationFragment) selectedNode.getParent();
if (selectedNode.equals(frag.getName())) {
nodeToCast= frag.getInitializer();
}
}
{
ASTRewrite rewrite= new ASTRewrite(nodeToCast.getParent());
String label;
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 1, image);
String simpleCastType= proposal.addImport(castType);
if (nodeToCast.getNodeType() == ASTNode.CAST_EXPRESSION) {
label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.changecast.description", castType); //$NON-NLS-1$
CastExpression expression= (CastExpression) nodeToCast;
rewrite.markAsReplaced(expression.getType(), rewrite.createPlaceholder(simpleCastType, ASTRewrite.TYPE));
} else {
label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.addcast.description", castType); //$NON-NLS-1$
Expression expressionCopy= (Expression) rewrite.createCopy(nodeToCast);
Type typeCopy= (Type) rewrite.createPlaceholder(simpleCastType, ASTRewrite.TYPE);
CastExpression castExpression= astRoot.getAST().newCastExpression();
castExpression.setExpression(expressionCopy);
castExpression.setType(typeCopy);
rewrite.markAsReplaced(nodeToCast, castExpression);
}
proposal.setDisplayName(label);
proposal.ensureNoModifications();
proposals.add(proposal);
}
// change method return statement to actual type
if (parentNodeType == ASTNode.RETURN_STATEMENT) {
ITypeBinding binding= nodeToCast.resolveTypeBinding();
BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode);
if (binding != null && decl instanceof MethodDeclaration) {
MethodDeclaration methodDeclaration= (MethodDeclaration) decl;
ASTRewrite rewrite= new ASTRewrite(methodDeclaration);
Type newReturnType= ASTResolving.getTypeFromTypeBinding(astRoot.getAST(), binding);
rewrite.markAsReplaced(methodDeclaration.getReturnType(), newReturnType);
String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.changereturntype.description", binding.getName()); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 2, image);
proposal.addImport(binding);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
if (parentNodeType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
VariableDeclarationFragment fragment= (VariableDeclarationFragment) selectedNode.getParent();
ASTNode parent= fragment.getParent();
Type type= null;
if (parent instanceof VariableDeclarationStatement) {
VariableDeclarationStatement stmt= (VariableDeclarationStatement) parent;
if (stmt.fragments().size() == 1) {
type= stmt.getType();
}
} else if (parent instanceof FieldDeclaration) {
FieldDeclaration decl= (FieldDeclaration) parent;
if (decl.fragments().size() == 1) {
type= decl.getType();
}
}
if (type != null) {
ImportEdit edit= new ImportEdit(cu, JavaPreferencesSettings.getCodeGenerationSettings());
String typeName= edit.addImport(args[0]);
String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.addcast_var.description", typeName); //$NON-NLS-1$
ReplaceCorrectionProposal varProposal= new ReplaceCorrectionProposal(label, cu, type.getStartPosition(), type.getLength(), typeName, 1);
varProposal.getRootTextEdit().add(edit);
proposals.add(varProposal);
}
}
}
public static void addUncaughtExceptionProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= context.getCoveredNode();
if (selectedNode == null) {
return;
}
while (selectedNode != null && !(selectedNode instanceof Statement)) {
selectedNode= selectedNode.getParent();
}
if (selectedNode == null) {
return;
}
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
SurroundWithTryCatchRefactoring refactoring= new SurroundWithTryCatchRefactoring(cu, selectedNode.getStartPosition(), selectedNode.getLength(), settings, null);
refactoring.setSaveChanges(false);
if (refactoring.checkActivationBasics(astRoot, null).isOK()) {
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.surroundwith.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
CUCorrectionProposal proposal= new CUCorrectionProposal(label, (CompilationUnitChange) refactoring.createChange(null), 4, image);
proposals.add(proposal);
}
BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode);
if (decl == null) {
return;
}
ITypeBinding[] uncaughtExceptions= ExceptionAnalyzer.perform(decl, Selection.createFromStartLength(selectedNode.getStartPosition(), selectedNode.getLength()));
if (uncaughtExceptions.length == 0) {
return;
}
TryStatement surroundingTry= (TryStatement) ASTNodes.getParent(selectedNode, ASTNode.TRY_STATEMENT);
if (surroundingTry != null) {
ASTRewrite rewrite= new ASTRewrite(surroundingTry);
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.addadditionalcatch.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 5, image);
AST ast= astRoot.getAST();
List catchClauses= surroundingTry.catchClauses();
for (int i= 0; i < uncaughtExceptions.length; i++) {
String imp= proposal.addImport(uncaughtExceptions[i]);
Name name= ASTNodeFactory.newName(ast, imp);
SingleVariableDeclaration var= ast.newSingleVariableDeclaration();
var.setName(ast.newSimpleName("e"));
var.setType(ast.newSimpleType(name));
CatchClause newClause= ast.newCatchClause();
newClause.setException(var);
rewrite.markAsInserted(newClause);
catchClauses.add(newClause);
}
proposal.ensureNoModifications();
proposals.add(proposal);
}
if (decl instanceof MethodDeclaration) {
ASTRewrite rewrite= new ASTRewrite(astRoot);
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.addthrows.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 6, image);
AST ast= astRoot.getAST();
MethodDeclaration methodDecl= (MethodDeclaration) decl;
List exceptions= methodDecl.thrownExceptions();
for (int i= 0; i < uncaughtExceptions.length; i++) {
String imp= proposal.addImport(uncaughtExceptions[i]);
Name name= ASTNodeFactory.newName(ast, imp);
rewrite.markAsInserted(name);
exceptions.add(name);
}
for (int i= 0; i < exceptions.size(); i++) {
Name elem= (Name) exceptions.get(i);
if (canRemove(elem.resolveTypeBinding(), uncaughtExceptions)) {
rewrite.markAsRemoved(elem);
}
}
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
private static boolean canRemove(ITypeBinding curr, ITypeBinding[] addedExceptions) {
while (curr != null) {
for (int i= 0; i < addedExceptions.length; i++) {
if (curr == addedExceptions[i]) {
return true;
}
}
curr= curr.getSuperclass();
}
return false;
}
public static void addUnreachableCatchProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= context.getCoveringNode();
if (selectedNode == null) {
return;
}
if (selectedNode.getNodeType() == ASTNode.BLOCK && selectedNode.getParent().getNodeType() == ASTNode.CATCH_CLAUSE ) {
CatchClause clause= (CatchClause) selectedNode.getParent();
TryStatement tryStatement= (TryStatement) clause.getParent();
ASTRewrite rewrite= new ASTRewrite(tryStatement.getParent());
if (tryStatement.catchClauses().size() > 1 || tryStatement.getFinally() != null) {
rewrite.markAsRemoved(clause);
} else {
List statements= tryStatement.getBody().statements();
if (statements.size() > 0) {
ASTNode placeholder= rewrite.createCopy((ASTNode) statements.get(0), (ASTNode) statements.get(statements.size() - 1));
rewrite.markAsReplaced(tryStatement, placeholder);
} else {
rewrite.markAsRemoved(tryStatement);
}
}
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.removecatchclause.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 6, image);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
public static void addNLSProposals(ICorrectionContext context, List proposals) throws CoreException {
final ICompilationUnit cu= context.getCompilationUnit();
String name= CorrectionMessages.getString("LocalCorrectionsSubProcessor.externalizestrings.description"); //$NON-NLS-1$
ChangeCorrectionProposal proposal= new ChangeCorrectionProposal(name, null, 0) {
public void apply(IDocument document) {
try {
NLSRefactoring refactoring= new NLSRefactoring(cu);
ExternalizeWizard wizard= new ExternalizeWizard(refactoring);
String dialogTitle= CorrectionMessages.getString("LocalCorrectionsSubProcessor.externalizestrings.dialog.title"); //$NON-NLS-1$
new RefactoringStarter().activate(refactoring, wizard, JavaPlugin.getActiveWorkbenchShell(), dialogTitle, true);
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
};
proposals.add(proposal);
TextEdit edit= NLSUtil.createNLSEdit(cu, context.getOffset());
if (edit != null) {
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.addnon-nls.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_NLS_NEVER_TRANSLATE);
CUCorrectionProposal nlsProposal= new CUCorrectionProposal(label, cu, 6, image);
nlsProposal.getRootTextEdit().add(edit);
proposals.add(nlsProposal);
}
}
/**
* A static field or method is accessed using a non-static reference. E.g.
* <pre>
* File f = new File();
* f.pathSeparator;
* </pre>
* This correction changes <code>f</code> above to <code>File</code>.
*
* @param context
* @param proposals
*/
public static void addInstanceAccessToStaticProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= context.getCoveredNode();
if (selectedNode == null) {
return;
}
Expression qualifier= null;
IBinding accessBinding= null;
if (selectedNode instanceof QualifiedName) {
QualifiedName name= (QualifiedName) selectedNode;
qualifier= name.getQualifier();
accessBinding= name.resolveBinding();
} else if (selectedNode instanceof SimpleName) {
ASTNode parent= selectedNode.getParent();
if (parent instanceof FieldAccess) {
FieldAccess fieldAccess= (FieldAccess) parent;
qualifier= fieldAccess.getExpression();
accessBinding= fieldAccess.getName().resolveBinding();
}
} else if (selectedNode instanceof MethodInvocation) {
MethodInvocation methodInvocation= (MethodInvocation) selectedNode;
qualifier= methodInvocation.getExpression();
accessBinding= methodInvocation.getName().resolveBinding();
}
ITypeBinding declaringTypeBinding= null;
if (accessBinding != null) {
if (accessBinding instanceof IMethodBinding) {
declaringTypeBinding= ((IMethodBinding) accessBinding).getDeclaringClass();
} else if (accessBinding instanceof IVariableBinding) {
declaringTypeBinding= ((IVariableBinding) accessBinding).getDeclaringClass();
}
if (declaringTypeBinding != null) {
ASTRewrite rewrite= new ASTRewrite(selectedNode.getParent());
rewrite.markAsReplaced(qualifier, astRoot.getAST().newSimpleName(declaringTypeBinding.getName()));
String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.changeaccesstostaticdefining.description", declaringTypeBinding.getName());
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 2, image);
proposal.addImport(declaringTypeBinding);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
if (qualifier != null) {
ITypeBinding instanceTypeBinding= ASTResolving.normalizeTypeBinding(qualifier.resolveTypeBinding());
if (instanceTypeBinding != null && instanceTypeBinding != declaringTypeBinding) {
ASTRewrite rewrite= new ASTRewrite(selectedNode.getParent());
rewrite.markAsReplaced(qualifier, astRoot.getAST().newSimpleName(instanceTypeBinding.getName()));
String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.changeaccesstostatic.description", instanceTypeBinding.getName());
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 1, image);
proposal.addImport(instanceTypeBinding);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
}
public static void addUnimplementedMethodsProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= context.getCoveringNode();
if (selectedNode == null) {
return;
}
ASTNode typeNode= null;
if (selectedNode.getNodeType() == ASTNode.SIMPLE_NAME && selectedNode.getParent().getNodeType() == ASTNode.TYPE_DECLARATION) {
typeNode= selectedNode.getParent();
} else if (selectedNode.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION) {
ClassInstanceCreation creation= (ClassInstanceCreation) selectedNode;
typeNode= creation.getAnonymousClassDeclaration();
}
if (typeNode != null) {
UnimplementedMethodsCompletionProposal proposal= new UnimplementedMethodsCompletionProposal(cu, typeNode, 10);
proposals.add(proposal);
}
if (typeNode instanceof TypeDeclaration) {
TypeDeclaration typeDeclaration= (TypeDeclaration) typeNode;
ASTRewriteCorrectionProposal proposal= ModifierCorrectionSubProcessor.getMakeTypeStaticProposal(cu, typeDeclaration);
proposals.add(proposal);
}
}
public static void addUninitializedLocalVariableProposal(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= context.getCoveringNode();
if (!(selectedNode instanceof Name)) {
return;
}
Name name= (Name) selectedNode;
IBinding binding= name.resolveBinding();
if (!(binding instanceof IVariableBinding)) {
return;
}
IVariableBinding varBinding= (IVariableBinding) binding;
CompilationUnit astRoot= context.getASTRoot();
ASTNode node= astRoot.findDeclaringNode(binding);
if (node instanceof VariableDeclarationFragment) {
ASTRewrite rewrite= new ASTRewrite(node.getParent());
VariableDeclarationFragment fragment= (VariableDeclarationFragment) node;
if (fragment.getInitializer() != null) {
return;
}
Expression expression= ASTResolving.getInitExpression(astRoot.getAST(), varBinding.getType());
if (expression == null) {
return;
}
fragment.setInitializer(expression);
rewrite.markAsInserted(expression);
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.uninitializedvariable.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 6, image);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
}
|
29,156 |
Bug 29156 Highlight all occurances of local Java variable
|
Sorry if this is a duplicate of the one I wrote this morning as I did not get any confirmation. My browser didn't show the confirmation either. Earlier I had requested this feature and I was told that API did not support this kind of search. I recently discovered CTL-1 mechanism and found that it allowed me to rename local variables. I see an opportunity here. If CTL-1 can rename all occurances of a local variable, data member etc, it should also be able to provide an option "highlight all occurances" in the same drop down box. It is a natural place as before I rename I should be able to view all occurance that I am renaming. I hope this makes sense and will fulfill a long time request to bring about ease of development and maintanance of code.
|
resolved fixed
|
f87a738
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-09T11:44:56Z | 2003-01-08T18:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/JavaCorrectionProcessor.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.internal.ui.text.correction;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
import org.eclipse.jface.text.contentassist.IContextInformation;
import org.eclipse.jface.text.contentassist.IContextInformationValidator;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IMarkerHelpRegistry;
import org.eclipse.ui.IMarkerResolution;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.texteditor.MarkerAnnotation;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaModelMarker;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.javaeditor.IProblemAnnotation;
import org.eclipse.jdt.internal.ui.javaeditor.ProblemAnnotationIterator;
import org.eclipse.jdt.internal.ui.text.java.IJavaCompletionProposal;
public class JavaCorrectionProcessor implements IContentAssistProcessor {
private static class CorrectionsComparator implements Comparator {
private static Collator fgCollator= Collator.getInstance();
public int compare(Object o1, Object o2) {
if ((o1 instanceof IJavaCompletionProposal) && (o2 instanceof IJavaCompletionProposal)) {
IJavaCompletionProposal e1= (IJavaCompletionProposal) o1;
IJavaCompletionProposal e2= (IJavaCompletionProposal) o2;
int del= e2.getRelevance() - e1.getRelevance();
if (del != 0) {
return del;
}
return fgCollator.compare(e1.getDisplayString(), e1.getDisplayString());
}
return fgCollator.compare(((ICompletionProposal) o1).getDisplayString(), ((ICompletionProposal) o1).getDisplayString());
}
}
private static ICorrectionProcessor[] fCodeManipulationProcessors= null;
public static ICorrectionProcessor[] getCodeManipulationProcessors() {
if (fCodeManipulationProcessors == null) {
fCodeManipulationProcessors= new ICorrectionProcessor[] {
new QuickFixProcessor(),
new QuickAssistProcessor()
};
}
return fCodeManipulationProcessors;
}
public static boolean hasCorrections(int problemId) {
return QuickFixProcessor.hasCorrections(problemId);
}
public static boolean hasCorrections(IProblemAnnotation annotation) {
int problemId= annotation.getId();
if (problemId == -1) {
if (annotation instanceof MarkerAnnotation) {
return hasCorrections(((MarkerAnnotation) annotation).getMarker());
}
return false;
} else {
return hasCorrections(problemId);
}
}
public static boolean hasCorrections(IMarker marker) {
try {
if (marker.isSubtypeOf(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER)) {
int problemId= marker.getAttribute(IJavaModelMarker.ID, -1);
return problemId != -1 && hasCorrections(problemId);
} else {
IMarkerHelpRegistry registry= PlatformUI.getWorkbench().getMarkerHelpRegistry();
return registry != null && registry.hasResolutions(marker);
}
} catch (CoreException e) {
JavaPlugin.log(e);
return false;
}
}
private IEditorPart fEditor;
/**
* Constructor for JavaCorrectionProcessor.
*/
public JavaCorrectionProcessor(IEditorPart editor) {
fEditor= editor;
}
/*
* @see IContentAssistProcessor#computeCompletionProposals(ITextViewer, int)
*/
public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int documentOffset) {
ICompilationUnit cu= JavaUI.getWorkingCopyManager().getWorkingCopy(fEditor.getEditorInput());
IAnnotationModel model= JavaUI.getDocumentProvider().getAnnotationModel(fEditor.getEditorInput());
ArrayList proposals= new ArrayList();
if (model != null) {
int length= viewer != null ? viewer.getSelectedRange().y : 0;
processProblemAnnotations(cu, model, documentOffset, length, proposals);
}
if (proposals.isEmpty()) {
proposals.add(new NoCorrectionProposal(null, null));
}
ICompletionProposal[] res= (ICompletionProposal[]) proposals.toArray(new ICompletionProposal[proposals.size()]);
Arrays.sort(res, new CorrectionsComparator());
return res;
}
private boolean isAtPosition(int offset, Position pos) {
return (pos != null) && (offset >= pos.getOffset() && offset <= (pos.getOffset() + pos.getLength()));
}
private void processProblemAnnotations(ICompilationUnit cu, IAnnotationModel model, int offset, int length, ArrayList proposals) {
CorrectionContext context= new CorrectionContext(cu);
boolean noProbemFound= true;
HashSet idsProcessed= new HashSet();
Iterator iter= new ProblemAnnotationIterator(model, true);
while (iter.hasNext()) {
IProblemAnnotation annot= (IProblemAnnotation) iter.next();
Position pos= model.getPosition((Annotation) annot);
if (isAtPosition(offset, pos)) {
int problemId= annot.getId();
if (problemId != -1) {
if (idsProcessed.add(new Integer(problemId))) { // collect only once per problem id
context.initialize(pos.getOffset(), pos.getLength(), annot.getId(), annot.getArguments());
collectCorrections(context, proposals);
if (proposals.isEmpty()) {
//proposals.add(new NoCorrectionProposal(pp, annot.getMessage()));
}
}
} else {
if (annot instanceof MarkerAnnotation) {
IMarker marker= ((MarkerAnnotation) annot).getMarker();
IMarkerResolution[] res= PlatformUI.getWorkbench().getMarkerHelpRegistry().getResolutions(marker);
for (int i= 0; i < res.length; i++) {
proposals.add(new MarkerResolutionProposal(res[i], marker));
}
}
}
noProbemFound= false;
}
}
if (noProbemFound) {
context.initialize(offset, length, 0, null);
collectCorrections(context, proposals);
}
}
public static void collectCorrections(CorrectionContext context, ArrayList proposals) {
ICorrectionProcessor[] processors= getCodeManipulationProcessors();
for (int i= 0; i < processors.length; i++) {
try {
processors[i].process(context, proposals);
} catch (CoreException e) {
JavaPlugin.log(e);
}
}
}
/*
* @see IContentAssistProcessor#computeContextInformation(ITextViewer, int)
*/
public IContextInformation[] computeContextInformation(ITextViewer viewer, int documentOffset) {
return null;
}
/*
* @see IContentAssistProcessor#getCompletionProposalAutoActivationCharacters()
*/
public char[] getCompletionProposalAutoActivationCharacters() {
return null;
}
/*
* @see IContentAssistProcessor#getContextInformationAutoActivationCharacters()
*/
public char[] getContextInformationAutoActivationCharacters() {
return null;
}
/*
* @see IContentAssistProcessor#getContextInformationValidator()
*/
public IContextInformationValidator getContextInformationValidator() {
return null;
}
/*
* @see IContentAssistProcessor#getErrorMessage()
*/
public String getErrorMessage() {
return null;
}
}
|
29,091 |
Bug 29091 Protected method created when overridding public method from super class
|
M4 Using org.eclipse.jdt.internal.debug.ui.launcher.MainTypeSelectionDialog, override TwoPaneElementSelector#createDialogArea(Composite) createDialogArea is created but is has protected visibility. I believe it should have public visibility as TwoPaneElementSelector#createDialogArea(Composite) is public and one cannot reduce the visibility of the inherited method.
|
resolved fixed
|
2be043e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-09T14:47:38Z | 2003-01-07T17:20:00Z |
org.eclipse.jdt.ui/core
| |
29,091 |
Bug 29091 Protected method created when overridding public method from super class
|
M4 Using org.eclipse.jdt.internal.debug.ui.launcher.MainTypeSelectionDialog, override TwoPaneElementSelector#createDialogArea(Composite) createDialogArea is created but is has protected visibility. I believe it should have public visibility as TwoPaneElementSelector#createDialogArea(Composite) is public and one cannot reduce the visibility of the inherited method.
|
resolved fixed
|
2be043e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-09T14:47:38Z | 2003-01-07T17:20:00Z |
extension/org/eclipse/jdt/internal/corext/codemanipulation/AddMethodStubOperation.java
| |
29,091 |
Bug 29091 Protected method created when overridding public method from super class
|
M4 Using org.eclipse.jdt.internal.debug.ui.launcher.MainTypeSelectionDialog, override TwoPaneElementSelector#createDialogArea(Composite) createDialogArea is created but is has protected visibility. I believe it should have public visibility as TwoPaneElementSelector#createDialogArea(Composite) is public and one cannot reduce the visibility of the inherited method.
|
resolved fixed
|
2be043e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-09T14:47:38Z | 2003-01-07T17:20:00Z |
org.eclipse.jdt.ui/core
| |
29,091 |
Bug 29091 Protected method created when overridding public method from super class
|
M4 Using org.eclipse.jdt.internal.debug.ui.launcher.MainTypeSelectionDialog, override TwoPaneElementSelector#createDialogArea(Composite) createDialogArea is created but is has protected visibility. I believe it should have public visibility as TwoPaneElementSelector#createDialogArea(Composite) is public and one cannot reduce the visibility of the inherited method.
|
resolved fixed
|
2be043e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-09T14:47:38Z | 2003-01-07T17:20:00Z |
extension/org/eclipse/jdt/internal/corext/codemanipulation/StubUtility.java
| |
29,091 |
Bug 29091 Protected method created when overridding public method from super class
|
M4 Using org.eclipse.jdt.internal.debug.ui.launcher.MainTypeSelectionDialog, override TwoPaneElementSelector#createDialogArea(Composite) createDialogArea is created but is has protected visibility. I believe it should have public visibility as TwoPaneElementSelector#createDialogArea(Composite) is public and one cannot reduce the visibility of the inherited method.
|
resolved fixed
|
2be043e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-09T14:47:38Z | 2003-01-07T17:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/MethodStubCompletionProposal.java
|
/*******************************************************************************
* Copyright (c) 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.internal.ui.text.java;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.util.Assert;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.internal.corext.codemanipulation.ImportsStructure;
import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility;
import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility.GenStubSettings;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.corext.util.Strings;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
public class MethodStubCompletionProposal extends JavaTypeCompletionProposal {
private String fTypeName;
private String fMethodName;
private String[] fParamTypes;
private IJavaProject fJavaProject;
public MethodStubCompletionProposal(IJavaProject jproject, ICompilationUnit cu, String declaringTypeName, String methodName, String[] paramTypes, int start, int length, String displayName, String completionProposal) {
super(completionProposal, cu, start, length, null, displayName, 0);
Assert.isNotNull(jproject);
Assert.isNotNull(methodName);
Assert.isNotNull(declaringTypeName);
Assert.isNotNull(paramTypes);
fTypeName= declaringTypeName;
fParamTypes= paramTypes;
fMethodName= methodName;
fJavaProject= jproject;
}
/* (non-Javadoc)
* @see JavaTypeCompletionProposal#updateReplacementString(IDocument, char, int, ImportsStructure)
*/
protected String updateReplacementString(IDocument document, char trigger, int offset, ImportsStructure impStructure) throws CoreException, BadLocationException {
IType declaringType= fJavaProject.findType(fTypeName);
if (declaringType != null) {
IMethod method= JavaModelUtil.findMethod(fMethodName, fParamTypes, false, declaringType);
if (method != null) {
GenStubSettings settings= new GenStubSettings(JavaPreferencesSettings.getCodeGenerationSettings());
IType definingType= null;
if (impStructure != null) {
IJavaElement currElem= impStructure.getCompilationUnit().getElementAt(offset);
if (currElem != null) {
definingType= (IType) currElem.getAncestor(IJavaElement.TYPE);
}
}
settings.noBody= (definingType != null) && definingType.isInterface();
settings.callSuper= declaringType.isClass() && !Flags.isAbstract(method.getFlags()) && !Flags.isStatic(method.getFlags());
settings.methodOverwrites= !Flags.isStatic(method.getFlags());
String stub= StubUtility.genStub(fTypeName, method, settings, impStructure);
// use the code formatter
String lineDelim= StubUtility.getLineDelimiterFor(document);
IRegion region= document.getLineInformationOfOffset(getReplacementOffset());
int lineStart= region.getOffset();
int indent= Strings.computeIndent(document.get(lineStart, getReplacementOffset() - lineStart), settings.tabWidth);
String replacement= StubUtility.codeFormat(stub, indent, lineDelim);
return Strings.trimLeadingTabsAndSpaces(replacement);
}
}
return null;
}
}
|
29,078 |
Bug 29078 Completion for anonymous inner class results in syntax error
|
1) enable smart brackets 2) type in Runnable runnable= new Runnable(<code assist>) ->you get the code below with one superflus parenthesis: Runnable runnable= new Runnable() { public void run() { } })
|
resolved fixed
|
649753e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-09T15:31:11Z | 2003-01-07T11:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/AnonymousTypeCompletionProposal.java
|
/*******************************************************************************
* Copyright (c) 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.internal.ui.text.java;
import org.eclipse.swt.graphics.Image;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.util.Assert;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.codemanipulation.ImportsStructure;
import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility;
import org.eclipse.jdt.internal.corext.util.Strings;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.actions.OverrideMethodQuery;
import org.eclipse.jdt.internal.ui.preferences.CodeFormatterPreferencePage;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
public class AnonymousTypeCompletionProposal extends JavaTypeCompletionProposal {
private IType fDeclaringType;
public AnonymousTypeCompletionProposal(IJavaProject jproject, ICompilationUnit cu, int start, int length, String constructorCompletion, String displayName, String declaringTypeName, int relevance) {
super(constructorCompletion, cu, start, length, null, displayName, relevance);
Assert.isNotNull(declaringTypeName);
Assert.isNotNull(jproject);
fDeclaringType= getDeclaringType(jproject, declaringTypeName);
setImage(getImageForType(fDeclaringType));
setCursorPosition(constructorCompletion.indexOf('(') + 1);
}
private Image getImageForType(IType type) {
String imageName= JavaPluginImages.IMG_OBJS_CLASS; // default
if (type != null) {
try {
if (type.isInterface()) {
imageName= JavaPluginImages.IMG_OBJS_INTERFACE;
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
return JavaPluginImages.get(imageName);
}
private IType getDeclaringType(IJavaProject project, String typeName) {
try {
return project.findType(typeName);
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
return null;
}
/* (non-Javadoc)
* @see JavaTypeCompletionProposal#updateReplacementString(char, int, ImportsStructure)
*/
protected String updateReplacementString(IDocument document, char trigger, int offset, ImportsStructure impStructure) throws CoreException, BadLocationException {
String replacementString= getReplacementString();
// construct replacement text
StringBuffer buf= new StringBuffer();
buf.append(replacementString);
if (!replacementString.endsWith(")")) { //$NON-NLS-1$
buf.append(')');
}
buf.append(" {\n"); //$NON-NLS-1$
if (!createStubs(buf, impStructure)) {
return null;
}
buf.append("}"); //$NON-NLS-1$
// use the code formatter
String lineDelim= StubUtility.getLineDelimiterFor(document);
int tabWidth= CodeFormatterPreferencePage.getTabSize();
IRegion region= document.getLineInformationOfOffset(getReplacementOffset());
int indent= Strings.computeIndent(document.get(region.getOffset(), region.getLength()), tabWidth);
String replacement= StubUtility.codeFormat(buf.toString(), indent, lineDelim);
return Strings.trimLeadingTabsAndSpaces(replacement);
}
private boolean createStubs(StringBuffer buf, ImportsStructure imports) throws JavaModelException {
if (fDeclaringType == null) {
return true;
}
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
ITypeHierarchy hierarchy= fDeclaringType.newSupertypeHierarchy(null);
OverrideMethodQuery selectionQuery= fDeclaringType.isClass() ? new OverrideMethodQuery(JavaPlugin.getActiveWorkbenchShell(), true) : null;
String[] unimplemented= StubUtility.evalUnimplementedMethods(fDeclaringType, hierarchy, true, settings, selectionQuery, imports);
if (unimplemented != null) {
for (int i= 0; i < unimplemented.length; i++) {
buf.append(unimplemented[i]);
if (i < unimplemented.length - 1) {
buf.append('\n');
}
}
return true;
}
return false;
}
}
|
29,078 |
Bug 29078 Completion for anonymous inner class results in syntax error
|
1) enable smart brackets 2) type in Runnable runnable= new Runnable(<code assist>) ->you get the code below with one superflus parenthesis: Runnable runnable= new Runnable() { public void run() { } })
|
resolved fixed
|
649753e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-09T15:31:11Z | 2003-01-07T11:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/JavaTypeCompletionProposal.java
|
/*******************************************************************************
* Copyright (c) 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.internal.ui.text.java;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.graphics.Image;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.corext.codemanipulation.ImportsStructure;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
/**
* If passed compilation unit is not null, the replacement string will be seen as a qualified type name.
*/
public class JavaTypeCompletionProposal extends JavaCompletionProposal {
private final ICompilationUnit fCompilationUnit;
/** The type name. */
private final String fTypeName;
/** The package name. */
private final String fPackageName;
/** The unqualified type name. */
private final String fUnqualifiedTypeName;
/** The fully qualified type name. */
private final String fFullyQualifiedTypeName;
private static String unqualify(String typeName) {
if (typeName == null)
return null;
final int index= typeName.lastIndexOf('.');
return index == -1 ? typeName : typeName.substring(index + 1);
}
private static String qualify(String typeName, String packageName) {
if (packageName == null)
return typeName;
if (typeName == null)
return null;
if (packageName.length() == 0)
return typeName;
return packageName + "." + typeName;
}
public JavaTypeCompletionProposal(String replacementString, ICompilationUnit cu, int replacementOffset, int replacementLength, Image image, String displayString, int relevance) {
this(replacementString, cu, replacementOffset, replacementLength, image, displayString, relevance, null, null);
}
public JavaTypeCompletionProposal(String replacementString, ICompilationUnit cu, int replacementOffset, int replacementLength, Image image, String displayString, int relevance,
String typeName, String packageName)
{
super(replacementString, replacementOffset, replacementLength, image, displayString, relevance);
fCompilationUnit= cu;
fTypeName= typeName;
fPackageName= packageName;
fUnqualifiedTypeName= unqualify(typeName);
fFullyQualifiedTypeName= qualify(typeName, packageName);
}
/**
* To be o
*/
protected String updateReplacementString(IDocument document, char trigger, int offset, ImportsStructure impStructure) throws CoreException, BadLocationException {
if (impStructure != null) {
IType[] types= impStructure.getCompilationUnit().getTypes();
if (types.length > 0 && types[0].getSourceRange().getOffset() <= offset) {
// ignore positions above type.
return impStructure.addImport(getReplacementString());
}
}
return null;
}
/* (non-Javadoc)
* @see ICompletionProposalExtension#apply(IDocument, char, int)
*/
public void apply(IDocument document, char trigger, int offset) {
try {
ImportsStructure impStructure= null;
if (fCompilationUnit != null) {
IPreferenceStore store= PreferenceConstants.getPreferenceStore();
String[] prefOrder= JavaPreferencesSettings.getImportOrderPreference(store);
int threshold= JavaPreferencesSettings.getImportNumberThreshold(store);
impStructure= new ImportsStructure(fCompilationUnit, prefOrder, threshold, true);
}
String replacementString= updateReplacementString(document, trigger, offset, impStructure);
if (replacementString != null) {
setReplacementString(replacementString);
setCursorPosition(replacementString.length());
}
super.apply(document, trigger, offset);
if (impStructure != null) {
int oldLen= document.getLength();
impStructure.create(false, null);
setReplacementOffset(getReplacementOffset() + document.getLength() - oldLen);
}
} catch (CoreException e) {
JavaPlugin.log(e);
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
}
/*
* @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension#isValidFor(IDocument, int)
*/
public boolean isValidFor(IDocument document, int offset) {
boolean isValid= super.isValidFor(document, offset);
if (isValid)
return true;
return
(fUnqualifiedTypeName != null && startsWith(document, offset, fUnqualifiedTypeName)) ||
(fFullyQualifiedTypeName != null && startsWith(document, offset, fFullyQualifiedTypeName));
}
}
|
29,078 |
Bug 29078 Completion for anonymous inner class results in syntax error
|
1) enable smart brackets 2) type in Runnable runnable= new Runnable(<code assist>) ->you get the code below with one superflus parenthesis: Runnable runnable= new Runnable() { public void run() { } })
|
resolved fixed
|
649753e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-09T15:31:11Z | 2003-01-07T11:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/MethodStubCompletionProposal.java
|
/*******************************************************************************
* Copyright (c) 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.internal.ui.text.java;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.util.Assert;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.internal.corext.codemanipulation.ImportsStructure;
import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility;
import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility.GenStubSettings;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.corext.util.Strings;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
public class MethodStubCompletionProposal extends JavaTypeCompletionProposal {
private String fTypeName;
private String fMethodName;
private String[] fParamTypes;
private IJavaProject fJavaProject;
public MethodStubCompletionProposal(IJavaProject jproject, ICompilationUnit cu, String declaringTypeName, String methodName, String[] paramTypes, int start, int length, String displayName, String completionProposal) {
super(completionProposal, cu, start, length, null, displayName, 0);
Assert.isNotNull(jproject);
Assert.isNotNull(methodName);
Assert.isNotNull(declaringTypeName);
Assert.isNotNull(paramTypes);
fTypeName= declaringTypeName;
fParamTypes= paramTypes;
fMethodName= methodName;
fJavaProject= jproject;
}
/* (non-Javadoc)
* @see JavaTypeCompletionProposal#updateReplacementString(IDocument, char, int, ImportsStructure)
*/
protected String updateReplacementString(IDocument document, char trigger, int offset, ImportsStructure impStructure) throws CoreException, BadLocationException {
IType declaringType= fJavaProject.findType(fTypeName);
if (declaringType != null) {
IMethod method= JavaModelUtil.findMethod(fMethodName, fParamTypes, false, declaringType);
if (method != null) {
GenStubSettings settings= new GenStubSettings(JavaPreferencesSettings.getCodeGenerationSettings());
IType definingType= null;
if (impStructure != null) {
IJavaElement currElem= impStructure.getCompilationUnit().getElementAt(offset);
if (currElem != null) {
definingType= (IType) currElem.getAncestor(IJavaElement.TYPE);
}
}
settings.noBody= (definingType != null) && definingType.isInterface();
settings.callSuper= declaringType.isClass() && !Flags.isAbstract(method.getFlags()) && !Flags.isStatic(method.getFlags());
settings.methodOverwrites= !Flags.isStatic(method.getFlags());
String stub= StubUtility.genStub(fTypeName, method, definingType, settings, impStructure);
// use the code formatter
String lineDelim= StubUtility.getLineDelimiterFor(document);
IRegion region= document.getLineInformationOfOffset(getReplacementOffset());
int lineStart= region.getOffset();
int indent= Strings.computeIndent(document.get(lineStart, getReplacementOffset() - lineStart), settings.tabWidth);
String replacement= StubUtility.codeFormat(stub, indent, lineDelim);
return Strings.trimLeadingTabsAndSpaces(replacement);
}
}
return null;
}
}
|
29,003 |
Bug 29003 Preferences 'Output Folder Name' needs to allow '/' in the path [build path]
|
In the window/preferences/Java/New Project panel, when 'Folders' radio button is set, the 'output folder name' cannot be set to something like 'WEB- INF/classes'. The error message "'/' is an invalid character" appears. However, when setting the output path on the project (project/properties), 'WEB- INF/classes' is allowed, as the '/' is valid. Please change the window/preferences to allow a '/' in output folder name, so this value can be set by default.
|
resolved fixed
|
d30c738
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-09T16:07:03Z | 2003-01-04T14:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/NewJavaProjectPreferencePage.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
// AW
package org.eclipse.jdt.internal.ui.preferences;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Widget;
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.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.JavaConventions;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaUIMessages;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.dialogs.StatusUtil;
/*
* The page for defaults for classpath entries in new java projects.
* See PreferenceConstants to access or change these values through public API.
*/
public class NewJavaProjectPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
private static final String SRCBIN_FOLDERS_IN_NEWPROJ= PreferenceConstants.SRCBIN_FOLDERS_IN_NEWPROJ;
private static final String SRCBIN_SRCNAME= PreferenceConstants.SRCBIN_SRCNAME;
private static final String SRCBIN_BINNAME= PreferenceConstants.SRCBIN_BINNAME;
private static final String CLASSPATH_JRELIBRARY_INDEX= PreferenceConstants.NEWPROJECT_JRELIBRARY_INDEX;
private static final String CLASSPATH_JRELIBRARY_LIST= PreferenceConstants.NEWPROJECT_JRELIBRARY_LIST;
/**
* @deprecated Inline to avoid reference to preference page
*/
public static boolean useSrcAndBinFolders() {
return PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.SRCBIN_FOLDERS_IN_NEWPROJ);
}
/**
* @deprecated Inline to avoid reference to preference page
*/
public static String getSourceFolderName() {
return PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.SRCBIN_SRCNAME);
}
/**
* @deprecated Inline to avoid reference to preference page
*/
public static String getOutputLocationName() {
return PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.SRCBIN_BINNAME);
}
public static IClasspathEntry[] getDefaultJRELibrary() {
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
String str= store.getString(CLASSPATH_JRELIBRARY_LIST);
int index= store.getInt(CLASSPATH_JRELIBRARY_INDEX);
StringTokenizer tok= new StringTokenizer(str, ";"); //$NON-NLS-1$
while (tok.hasMoreTokens() && index > 0) {
tok.nextToken();
index--;
}
if (tok.hasMoreTokens()) {
IClasspathEntry[] res= decodeJRELibraryClasspathEntries(tok.nextToken());
if (res.length > 0) {
return res;
}
}
return new IClasspathEntry[] { getJREContainerEntry() };
}
// JRE Entry
public static String decodeJRELibraryDescription(String encoded) {
int end= encoded.indexOf(' ');
if (end != -1) {
return URLDecoder.decode(encoded.substring(0, end));
}
return ""; //$NON-NLS-1$
}
public static IClasspathEntry[] decodeJRELibraryClasspathEntries(String encoded) {
StringTokenizer tok= new StringTokenizer(encoded, " "); //$NON-NLS-1$
ArrayList res= new ArrayList();
while (tok.hasMoreTokens()) {
try {
tok.nextToken(); // desc: ignore
int kind= Integer.parseInt(tok.nextToken());
IPath path= decodePath(tok.nextToken());
IPath attachPath= decodePath(tok.nextToken());
IPath attachRoot= decodePath(tok.nextToken());
boolean isExported= Boolean.valueOf(tok.nextToken()).booleanValue();
switch (kind) {
case IClasspathEntry.CPE_SOURCE:
res.add(JavaCore.newSourceEntry(path));
break;
case IClasspathEntry.CPE_LIBRARY:
res.add(JavaCore.newLibraryEntry(path, attachPath, attachRoot, isExported));
break;
case IClasspathEntry.CPE_VARIABLE:
res.add(JavaCore.newVariableEntry(path, attachPath, attachRoot, isExported));
break;
case IClasspathEntry.CPE_PROJECT:
res.add(JavaCore.newProjectEntry(path, isExported));
break;
case IClasspathEntry.CPE_CONTAINER:
res.add(JavaCore.newContainerEntry(path, isExported));
break;
}
} catch (NumberFormatException e) {
String message= JavaUIMessages.getString("NewJavaProjectPreferencePage.error.decode"); //$NON-NLS-1$
JavaPlugin.log(new Status(Status.ERROR, JavaUI.ID_PLUGIN, Status.ERROR, message, e));
} catch (NoSuchElementException e) {
String message= JavaUIMessages.getString("NewJavaProjectPreferencePage.error.decode"); //$NON-NLS-1$
JavaPlugin.log(new Status(Status.ERROR, JavaUI.ID_PLUGIN, Status.ERROR, message, e));
}
}
return (IClasspathEntry[]) res.toArray(new IClasspathEntry[res.size()]);
}
public static String encodeJRELibrary(String desc, IClasspathEntry[] cpentries) {
StringBuffer buf= new StringBuffer();
for (int i= 0; i < cpentries.length; i++) {
IClasspathEntry entry= cpentries[i];
buf.append(URLEncoder.encode(desc));
buf.append(' ');
buf.append(entry.getEntryKind());
buf.append(' ');
buf.append(encodePath(entry.getPath()));
buf.append(' ');
buf.append(encodePath(entry.getSourceAttachmentPath()));
buf.append(' ');
buf.append(encodePath(entry.getSourceAttachmentRootPath()));
buf.append(' ');
buf.append(entry.isExported());
buf.append(' ');
}
return buf.toString();
}
private static String encodePath(IPath path) {
if (path == null) {
return "#"; //$NON-NLS-1$
} else if (path.isEmpty()) {
return "&"; //$NON-NLS-1$
} else {
return URLEncoder.encode(path.toString());
}
}
private static IPath decodePath(String str) {
if ("#".equals(str)) { //$NON-NLS-1$
return null;
} else if ("&".equals(str)) { //$NON-NLS-1$
return Path.EMPTY;
} else {
return new Path(URLDecoder.decode(str));
}
}
private ArrayList fCheckBoxes;
private ArrayList fRadioButtons;
private ArrayList fTextControls;
private SelectionListener fSelectionListener;
private ModifyListener fModifyListener;
private Text fBinFolderNameText;
private Text fSrcFolderNameText;
private Combo fJRECombo;
private Button fProjectAsSourceFolder;
private Button fFoldersAsSourceFolder;
private Label fSrcFolderNameLabel;
private Label fBinFolderNameLabel;
public NewJavaProjectPreferencePage() {
super();
setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore());
setDescription(JavaUIMessages.getString("NewJavaProjectPreferencePage.description")); //$NON-NLS-1$
fRadioButtons= new ArrayList();
fCheckBoxes= new ArrayList();
fTextControls= new ArrayList();
fSelectionListener= new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {}
public void widgetSelected(SelectionEvent e) {
controlChanged(e.widget);
}
};
fModifyListener= new ModifyListener() {
public void modifyText(ModifyEvent e) {
controlModified(e.widget);
}
};
}
public static void initDefaults(IPreferenceStore store) {
store.setDefault(SRCBIN_FOLDERS_IN_NEWPROJ, false);
store.setDefault(SRCBIN_SRCNAME, "src"); //$NON-NLS-1$
store.setDefault(SRCBIN_BINNAME, "bin"); //$NON-NLS-1$
store.setDefault(CLASSPATH_JRELIBRARY_LIST, getDefaultJRELibraries());
store.setDefault(CLASSPATH_JRELIBRARY_INDEX, 0); //$NON-NLS-1$
}
private static String getDefaultJRELibraries() {
StringBuffer buf= new StringBuffer();
IClasspathEntry cntentry= getJREContainerEntry();
buf.append(encodeJRELibrary(JavaUIMessages.getString("NewJavaProjectPreferencePage.jre_container.description"), new IClasspathEntry[] { cntentry} )); //$NON-NLS-1$
buf.append(';');
IClasspathEntry varentry= getJREVariableEntry();
buf.append(encodeJRELibrary(JavaUIMessages.getString("NewJavaProjectPreferencePage.jre_variable.description"), new IClasspathEntry[] { varentry })); //$NON-NLS-1$
buf.append(';');
return buf.toString();
}
private static IClasspathEntry getJREContainerEntry() {
return JavaCore.newContainerEntry(new Path("org.eclipse.jdt.launching.JRE_CONTAINER"));
}
private static IClasspathEntry getJREVariableEntry() {
return JavaCore.newVariableEntry(new Path("JRE_LIB"), new Path("JRE_SRC"), new Path("JRE_SRCROOT"));
}
/*
* @see IWorkbenchPreferencePage#init(IWorkbench)
*/
public void init(IWorkbench workbench) {
}
/**
* @see PreferencePage#createControl(Composite)
*/
public void createControl(Composite parent) {
super.createControl(parent);
WorkbenchHelp.setHelp(getControl(), IJavaHelpContextIds.NEW_JAVA_PROJECT_PREFERENCE_PAGE);
}
private Button addRadioButton(Composite parent, String label, String key, String value, int indent) {
GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= 2;
gd.horizontalIndent= indent;
Button button= new Button(parent, SWT.RADIO);
button.setText(label);
button.setData(new String[] { key, value });
button.setLayoutData(gd);
button.setSelection(value.equals(getPreferenceStore().getString(key)));
fRadioButtons.add(button);
return button;
}
private Text addTextControl(Composite parent, Label labelControl, String key, int indent) {
GridData gd= new GridData();
gd.horizontalIndent= indent;
labelControl.setLayoutData(gd);
gd= new GridData(GridData.FILL_HORIZONTAL);
gd.widthHint= convertWidthInCharsToPixels(40);
Text text= new Text(parent, SWT.SINGLE | SWT.BORDER);
text.setText(getPreferenceStore().getString(key));
text.setData(key);
text.setLayoutData(gd);
fTextControls.add(text);
return text;
}
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);
layout.numColumns= 2;
result.setLayout(layout);
GridData gd= new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan= 2;
Group sourceFolderGroup= new Group(result, SWT.WRAP);
layout= new GridLayout();
layout.numColumns= 2;
sourceFolderGroup.setLayout(layout);
sourceFolderGroup.setLayoutData(gd);
sourceFolderGroup.setText(JavaUIMessages.getString("NewJavaProjectPreferencePage.sourcefolder.label")); //$NON-NLS-1$
int indent= 0;
fProjectAsSourceFolder= addRadioButton(sourceFolderGroup, JavaUIMessages.getString("NewJavaProjectPreferencePage.sourcefolder.project"), SRCBIN_FOLDERS_IN_NEWPROJ, IPreferenceStore.FALSE, indent); //$NON-NLS-1$
fProjectAsSourceFolder.addSelectionListener(fSelectionListener);
fFoldersAsSourceFolder= addRadioButton(sourceFolderGroup, JavaUIMessages.getString("NewJavaProjectPreferencePage.sourcefolder.folder"), SRCBIN_FOLDERS_IN_NEWPROJ, IPreferenceStore.TRUE, indent); //$NON-NLS-1$
fFoldersAsSourceFolder.addSelectionListener(fSelectionListener);
indent= convertWidthInCharsToPixels(4);
fSrcFolderNameLabel= new Label(sourceFolderGroup, SWT.NONE);
fSrcFolderNameLabel.setText(JavaUIMessages.getString("NewJavaProjectPreferencePage.folders.src")); //$NON-NLS-1$
fSrcFolderNameText= addTextControl(sourceFolderGroup, fSrcFolderNameLabel, SRCBIN_SRCNAME, indent); //$NON-NLS-1$
fSrcFolderNameText.addModifyListener(fModifyListener);
fBinFolderNameLabel= new Label(sourceFolderGroup, SWT.NONE);
fBinFolderNameLabel.setText(JavaUIMessages.getString("NewJavaProjectPreferencePage.folders.bin")); //$NON-NLS-1$
fBinFolderNameText= addTextControl(sourceFolderGroup, fBinFolderNameLabel, SRCBIN_BINNAME, indent); //$NON-NLS-1$
fBinFolderNameText.addModifyListener(fModifyListener);
String[] jreNames= getJRENames();
if (jreNames.length > 0) {
Label jreSelectionLabel= new Label(result, SWT.NONE);
jreSelectionLabel.setText(JavaUIMessages.getString("NewJavaProjectPreferencePage.jrelibrary.label")); //$NON-NLS-1$
jreSelectionLabel.setLayoutData(new GridData());
int index= getPreferenceStore().getInt(CLASSPATH_JRELIBRARY_INDEX);
fJRECombo= new Combo(result, SWT.READ_ONLY);
fJRECombo.setItems(jreNames);
fJRECombo.select(index);
fJRECombo.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
}
validateFolders();
return result;
}
private void validateFolders() {
boolean useFolders= fFoldersAsSourceFolder.getSelection();
fSrcFolderNameText.setEnabled(useFolders);
fBinFolderNameText.setEnabled(useFolders);
fSrcFolderNameLabel.setEnabled(useFolders);
fBinFolderNameLabel.setEnabled(useFolders);
if (useFolders) {
String srcName= fSrcFolderNameText.getText();
String binName= fBinFolderNameText.getText();
if (srcName.length() + binName.length() == 0) {
updateStatus(new StatusInfo(IStatus.ERROR, JavaUIMessages.getString("NewJavaProjectPreferencePage.folders.error.namesempty"))); //$NON-NLS-1$
return;
}
IWorkspace workspace= JavaPlugin.getWorkspace();
IStatus status;
if (srcName.length() != 0) {
status= workspace.validateName(srcName, IResource.FOLDER);
if (!status.isOK()) {
String message= JavaUIMessages.getFormattedString("NewJavaProjectPreferencePage.folders.error.invalidsrcname", status.getMessage()); //$NON-NLS-1$
updateStatus(new StatusInfo(IStatus.ERROR, message));
return;
}
}
status= workspace.validateName(binName, IResource.FOLDER);
if (!status.isOK()) {
String message= JavaUIMessages.getFormattedString("NewJavaProjectPreferencePage.folders.error.invalidbinname", status.getMessage()); //$NON-NLS-1$
updateStatus(new StatusInfo(IStatus.ERROR, message));
return;
}
IProject dmy= workspace.getRoot().getProject("dmy"); //$NON-NLS-1$
IClasspathEntry entry= JavaCore.newSourceEntry(dmy.getFullPath().append(srcName));
IPath outputLocation= dmy.getFullPath().append(binName);
status= JavaConventions.validateClasspath(JavaCore.create(dmy), new IClasspathEntry[] { entry }, outputLocation);
if (!status.isOK()) {
updateStatus(status);
return;
}
}
updateStatus(new StatusInfo()); // set to OK
}
private void updateStatus(IStatus status) {
setValid(!status.matches(IStatus.ERROR));
StatusUtil.applyToStatusLine(this, status);
}
private void controlChanged(Widget widget) {
if (widget == fFoldersAsSourceFolder || widget == fProjectAsSourceFolder) {
validateFolders();
}
}
private void controlModified(Widget widget) {
if (widget == fSrcFolderNameText || widget == fBinFolderNameText) {
validateFolders();
}
}
/*
* @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));
}
if (fJRECombo != null) {
fJRECombo.select(store.getDefaultInt(CLASSPATH_JRELIBRARY_INDEX));
}
validateFolders();
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());
}
if (fJRECombo != null) {
store.setValue(CLASSPATH_JRELIBRARY_INDEX, fJRECombo.getSelectionIndex());
}
JavaPlugin.getDefault().savePluginPreferences();
return super.performOk();
}
private String[] getJRENames() {
String prefString= getPreferenceStore().getString(CLASSPATH_JRELIBRARY_LIST);
ArrayList list= new ArrayList();
StringTokenizer tok= new StringTokenizer(prefString, ";"); //$NON-NLS-1$
while (tok.hasMoreTokens()) {
list.add(decodeJRELibraryDescription(tok.nextToken()));
}
return (String[]) list.toArray(new String[list.size()]);
}
}
|
28,824 |
Bug 28824 Quick Fix: Type Mismatch -> Cast bug [quick fix]
|
When using code assist to apply a cast to the following statement: DefaultMutableTreeNode root = getParentContainer().treeMapperTree.getModel ().getRoot(); You get: DefaultMutableTreeNode root = getParentContainer().(DefaultMutableTreeNode) treeMapperTree.getModel().getRoot(); When you should get: DefaultMutableTreeNode root = (DefaultMutableTreeNode) getParentContainer ().treeMapperTree.getModel().getRoot(); Seems to be getting confused about where the cast statement should go because the treeMapperTree isn't using getters (i.e. getTreeMapperTree()). When using getters then the cast works fine... Should also work without getters, hence bug.
|
verified fixed
|
af53044
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-09T16:45:21Z | 2002-12-23T10:40:00Z |
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/astrewrite/ASTRewritingExpressionsTest.java
|
package org.eclipse.jdt.ui.tests.astrewrite;
import java.util.Hashtable;
import java.util.List;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.dom.*;
import org.eclipse.jdt.testplugin.JavaProjectHelper;
import org.eclipse.jdt.internal.corext.dom.ASTRewrite;
import org.eclipse.jdt.internal.ui.text.correction.ASTRewriteCorrectionProposal;
public class ASTRewritingExpressionsTest extends ASTRewritingTest {
private static final Class THIS= ASTRewritingExpressionsTest.class;
private IJavaProject fJProject1;
private IPackageFragmentRoot fSourceFolder;
public ASTRewritingExpressionsTest(String name) {
super(name);
}
public static Test suite() {
if (false) {
return new TestSuite(THIS);
} else {
TestSuite suite= new TestSuite();
suite.addTest(new ASTRewritingExpressionsTest("testMethodInvocation1"));
return suite;
}
}
protected void setUp() throws Exception {
Hashtable options= JavaCore.getOptions();
options.put(JavaCore.FORMATTER_TAB_CHAR, JavaCore.SPACE);
options.put(JavaCore.FORMATTER_TAB_SIZE, "4");
JavaCore.setOptions(options);
fJProject1= JavaProjectHelper.createJavaProject("TestProject1", "bin");
assertTrue("rt not found", JavaProjectHelper.addRTJar(fJProject1) != null);
fSourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
}
protected void tearDown() throws Exception {
JavaProjectHelper.delete(fJProject1);
}
public void testArrayAccess() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" int[] o= new int[] { 1, 2, 3 };\n");
buf.append(" public void foo() {\n");
buf.append(" o[3 /* comment*/ - 1]= this.o[3 - 1];\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, false);
ASTRewrite rewrite= new ASTRewrite(astRoot);
AST ast= astRoot.getAST();
assertTrue("Parse errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0);
TypeDeclaration type= findTypeDeclaration(astRoot, "E");
MethodDeclaration methodDecl= findMethodDeclaration(type, "foo");
Block block= methodDecl.getBody();
List statements= block.statements();
assertTrue("Number of statements not 1", statements.size() == 1);
{ // replace left hand side index, replace right hand side index by left side index
ExpressionStatement stmt= (ExpressionStatement) statements.get(0);
Assignment assignment= (Assignment) stmt.getExpression();
ArrayAccess left= (ArrayAccess) assignment.getLeftHandSide();
ArrayAccess right= (ArrayAccess) assignment.getRightHandSide();
NumberLiteral name= ast.newNumberLiteral("1");
rewrite.markAsReplaced(left.getIndex(), name, "Replace left array index with 1");
ASTNode placeHolder= rewrite.createCopy(left.getIndex());
rewrite.markAsReplaced(right.getIndex(), placeHolder, "Replace right array index with left array index");
SimpleName newName= ast.newSimpleName("o");
rewrite.markAsReplaced(right.getArray(), newName, "Rename array");
}
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null);
proposal.getCompilationUnitChange().setSave(true);
proposal.apply(null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" int[] o= new int[] { 1, 2, 3 };\n");
buf.append(" public void foo() {\n");
buf.append(" o[1]= o[3 /* comment*/ - 1];\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
clearRewrite(rewrite);
}
public void testArrayCreation() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" goo(new int[] { 1, 2, 3 },\n");
buf.append(" new int[] { 1, 2, 3 },\n");
buf.append(" new int[2][][],\n");
buf.append(" new int[2][][],\n");
buf.append(" new int[2][][],\n");
buf.append(" new int[2][][]);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, false);
ASTRewrite rewrite= new ASTRewrite(astRoot);
AST ast= astRoot.getAST();
assertTrue("Parse errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0);
TypeDeclaration type= findTypeDeclaration(astRoot, "E");
MethodDeclaration methodDecl= findMethodDeclaration(type, "foo");
Block block= methodDecl.getBody();
List statements= block.statements();
assertTrue("Number of statements not 1", statements.size() == 1);
ExpressionStatement statement= (ExpressionStatement) statements.get(0);
MethodInvocation invocation= (MethodInvocation) statement.getExpression();
List args= invocation.arguments();
assertTrue("Number of arguments not 6", args.size() == 6);
{ // replace the element type and increase the dimension
ArrayCreation arrayCreation= (ArrayCreation) args.get(0);
ArrayType arrayType= arrayCreation.getType();
PrimitiveType floatType= ast.newPrimitiveType(PrimitiveType.FLOAT);
ArrayType newArrayType= ast.newArrayType(floatType, 2);
rewrite.markAsReplaced(arrayType, newArrayType);
}
{ // remove the initializer, add a dimension expression
ArrayCreation arrayCreation= (ArrayCreation) args.get(1);
rewrite.markAsRemoved(arrayCreation.getInitializer());
List dimensions= arrayCreation.dimensions();
assertTrue("Number of dimension expressions not 0", dimensions.size() == 0);
NumberLiteral literal= ast.newNumberLiteral("10");
dimensions.add(literal);
rewrite.markAsInserted(literal);
}
{ // remove all dimension except one, no dimension expression
// insert the initializer: formatter problems
ArrayCreation arrayCreation= (ArrayCreation) args.get(2);
ArrayType arrayType= arrayCreation.getType();
PrimitiveType intType= ast.newPrimitiveType(PrimitiveType.INT);
ArrayType newArrayType= ast.newArrayType(intType, 1);
rewrite.markAsReplaced(arrayType, newArrayType);
List dimensions= arrayCreation.dimensions();
assertTrue("Number of dimension expressions not 1", dimensions.size() == 1);
rewrite.markAsRemoved((ASTNode) dimensions.get(0));
ArrayInitializer initializer= ast.newArrayInitializer();
List expressions= initializer.expressions();
expressions.add(ast.newNumberLiteral("10"));
}
{ // add 2 dimension expressions
ArrayCreation arrayCreation= (ArrayCreation) args.get(3);
List dimensions= arrayCreation.dimensions();
assertTrue("Number of dimension expressions not 1", dimensions.size() == 1);
NumberLiteral literal1= ast.newNumberLiteral("10");
dimensions.add(literal1);
rewrite.markAsInserted(literal1);
NumberLiteral literal2= ast.newNumberLiteral("11");
dimensions.add(literal2);
rewrite.markAsInserted(literal2);
}
{ // add 2 empty dimensions
ArrayCreation arrayCreation= (ArrayCreation) args.get(4);
ArrayType arrayType= arrayCreation.getType();
assertTrue("Number of dimension not 3", arrayType.getDimensions() == 3);
PrimitiveType intType= ast.newPrimitiveType(PrimitiveType.INT);
ArrayType newArrayType= ast.newArrayType(intType, 5);
rewrite.markAsReplaced(arrayType, newArrayType);
}
{ // replace dimension expression, add a dimension expression
ArrayCreation arrayCreation= (ArrayCreation) args.get(5);
List dimensions= arrayCreation.dimensions();
assertTrue("Number of dimension expressions not 1", dimensions.size() == 1);
NumberLiteral literal1= ast.newNumberLiteral("10");
rewrite.markAsReplaced((ASTNode) dimensions.get(0), literal1);
NumberLiteral literal2= ast.newNumberLiteral("11");
dimensions.add(literal2);
rewrite.markAsInserted(literal2);
}
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null);
proposal.getCompilationUnitChange().setSave(true);
proposal.apply(null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" goo(new float[][] { 1, 2, 3 },\n");
buf.append(" new int[10],\n");
buf.append(" new int[],\n");
buf.append(" new int[2][10][11],\n");
buf.append(" new int[2][][][][],\n");
buf.append(" new int[10][11][]);\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
clearRewrite(rewrite);
}
public void testArrayInitializer() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" goo(new int[] { 1, 2, 3 },\n");
buf.append(" new int[] { 1, 2, 3 },\n");
buf.append(" new int[] { 1, 2, 3 });\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, false);
ASTRewrite rewrite= new ASTRewrite(astRoot);
AST ast= astRoot.getAST();
assertTrue("Parse errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0);
TypeDeclaration type= findTypeDeclaration(astRoot, "E");
MethodDeclaration methodDecl= findMethodDeclaration(type, "foo");
Block block= methodDecl.getBody();
List statements= block.statements();
assertTrue("Number of statements not 1", statements.size() == 1);
ExpressionStatement statement= (ExpressionStatement) statements.get(0);
MethodInvocation invocation= (MethodInvocation) statement.getExpression();
List args= invocation.arguments();
{ // remove first and last initializer expression
ArrayCreation arrayCreation= (ArrayCreation) args.get(0);
ArrayInitializer initializer= arrayCreation.getInitializer();
List expressions= initializer.expressions();
assertTrue("Number of initializer expressions not 3", expressions.size() == 3);
rewrite.markAsRemoved((ASTNode) expressions.get(0));
rewrite.markAsRemoved((ASTNode) expressions.get(2));
}
{ // insert at second and last position
ArrayCreation arrayCreation= (ArrayCreation) args.get(1);
ArrayInitializer initializer= arrayCreation.getInitializer();
List expressions= initializer.expressions();
assertTrue("Number of initializer expressions not 3", expressions.size() == 3);
NumberLiteral literal1= ast.newNumberLiteral("10");
expressions.add(1, literal1);
rewrite.markAsInserted(literal1);
NumberLiteral literal2= ast.newNumberLiteral("11");
expressions.add(literal2);
rewrite.markAsInserted(literal2);
}
{ // replace first and last initializer expression
ArrayCreation arrayCreation= (ArrayCreation) args.get(2);
ArrayInitializer initializer= arrayCreation.getInitializer();
List expressions= initializer.expressions();
assertTrue("Number of initializer expressions not 3", expressions.size() == 3);
NumberLiteral literal1= ast.newNumberLiteral("10");
NumberLiteral literal2= ast.newNumberLiteral("11");
rewrite.markAsReplaced((ASTNode) expressions.get(0), literal1);
rewrite.markAsReplaced((ASTNode) expressions.get(2), literal2);
}
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null);
proposal.getCompilationUnitChange().setSave(true);
proposal.apply(null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" goo(new int[] { 2 },\n");
buf.append(" new int[] { 1, 10, 2, 3, 11 },\n");
buf.append(" new int[] { 10, 2, 11 });\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
clearRewrite(rewrite);
}
public void testAssignment() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" int i, j;\n");
buf.append(" i= 0;\n");
buf.append(" i-= j= 3;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, false);
ASTRewrite rewrite= new ASTRewrite(astRoot);
AST ast= astRoot.getAST();
assertTrue("Parse errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0);
TypeDeclaration type= findTypeDeclaration(astRoot, "E");
MethodDeclaration methodDecl= findMethodDeclaration(type, "foo");
Block block= methodDecl.getBody();
List statements= block.statements();
assertTrue("Number of statements not 3", statements.size() == 3);
{ // change left side & right side
ExpressionStatement stmt= (ExpressionStatement) statements.get(1);
Assignment assignment= (Assignment) stmt.getExpression();
SimpleName name= ast.newSimpleName("j");
rewrite.markAsReplaced(assignment.getLeftHandSide(), name);
MethodInvocation invocation= ast.newMethodInvocation();
invocation.setName(ast.newSimpleName("goo"));
invocation.setExpression(ast.newSimpleName("other"));
rewrite.markAsReplaced(assignment.getRightHandSide(), invocation);
}
{ // change operator and operator of inner
ExpressionStatement stmt= (ExpressionStatement) statements.get(2);
Assignment assignment= (Assignment) stmt.getExpression();
Assignment modifiedNode= ast.newAssignment();
modifiedNode.setOperator(Assignment.Operator.DIVIDE_ASSIGN);
rewrite.markAsModified(assignment, modifiedNode);
Assignment inner= (Assignment) assignment.getRightHandSide();
Assignment modifiedInner= ast.newAssignment();
modifiedInner.setOperator(Assignment.Operator.RIGHT_SHIFT_UNSIGNED_ASSIGN);
rewrite.markAsModified(inner, modifiedInner);
}
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null);
proposal.getCompilationUnitChange().setSave(true);
proposal.apply(null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" int i, j;\n");
buf.append(" j= other.goo();\n");
buf.append(" i/= j>>>= 3;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
clearRewrite(rewrite);
}
public void testCastExpression() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" x= (E) clone();\n");
buf.append(" z= y.toList();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, false);
ASTRewrite rewrite= new ASTRewrite(astRoot);
AST ast= astRoot.getAST();
assertTrue("Parse errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0);
TypeDeclaration type= findTypeDeclaration(astRoot, "E");
MethodDeclaration methodDecl= findMethodDeclaration(type, "foo");
Block block= methodDecl.getBody();
List statements= block.statements();
assertTrue("Number of statements not 2", statements.size() == 2);
{ // change cast type and cast expression
ExpressionStatement stmt= (ExpressionStatement) statements.get(0);
Assignment assignment= (Assignment) stmt.getExpression();
CastExpression expression= (CastExpression) assignment.getRightHandSide();
SimpleType newType= ast.newSimpleType(ast.newSimpleName("SuperE"));
rewrite.markAsReplaced(expression.getType(), newType);
SimpleName newExpression= ast.newSimpleName("a");
rewrite.markAsReplaced(expression.getExpression(), newExpression);
}
{ // create cast
ExpressionStatement stmt= (ExpressionStatement) statements.get(1);
Assignment assignment= (Assignment) stmt.getExpression();
Expression rightHand= assignment.getRightHandSide();
Expression placeholder= (Expression) rewrite.createCopy(rightHand);
CastExpression newCastExpression= ast.newCastExpression();
newCastExpression.setType(ast.newSimpleType(ast.newSimpleName("List")));
newCastExpression.setExpression(placeholder);
rewrite.markAsReplaced(rightHand, newCastExpression);
}
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null);
proposal.getCompilationUnitChange().setSave(true);
proposal.apply(null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" x= (SuperE) a;\n");
buf.append(" z= (List) y.toList();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
clearRewrite(rewrite);
}
public void testCatchClause() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" } catch (CoreException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, false);
ASTRewrite rewrite= new ASTRewrite(astRoot);
AST ast= astRoot.getAST();
assertTrue("Parse errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0);
TypeDeclaration type= findTypeDeclaration(astRoot, "E");
MethodDeclaration methodDecl= findMethodDeclaration(type, "foo");
Block block= methodDecl.getBody();
List statements= block.statements();
assertTrue("Number of statements not 3", statements.size() == 1);
List catchClauses= ((TryStatement) statements.get(0)).catchClauses();
assertTrue("Number of catchClauses not 2", catchClauses.size() == 2);
{ // change exception type
CatchClause clause= (CatchClause) catchClauses.get(0);
SingleVariableDeclaration exception= clause.getException();
SingleVariableDeclaration newException= ast.newSingleVariableDeclaration();
newException.setType(ast.newSimpleType(ast.newSimpleName("NullPointerException")));
newException.setName(ast.newSimpleName("ex"));
rewrite.markAsReplaced(exception, newException);
}
{ // change body
CatchClause clause= (CatchClause) catchClauses.get(1);
Block body= clause.getBody();
Block newBody= ast.newBlock();
ReturnStatement returnStatement= ast.newReturnStatement();
newBody.statements().add(returnStatement);
rewrite.markAsReplaced(body, newBody);
}
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null);
proposal.getCompilationUnitChange().setSave(true);
proposal.apply(null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" } catch (NullPointerException ex) {\n");
buf.append(" } catch (CoreException e) {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
clearRewrite(rewrite);
}
public void testClassInstanceCreation() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" goo().new Inner();\n");
buf.append(" new Runnable(\"Hello\") {\n");
buf.append(" public void run() {\n");
buf.append(" }\n");
buf.append(" };\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, false);
ASTRewrite rewrite= new ASTRewrite(astRoot);
AST ast= astRoot.getAST();
assertTrue("Parse errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0);
TypeDeclaration type= findTypeDeclaration(astRoot, "E");
MethodDeclaration methodDecl= findMethodDeclaration(type, "foo");
Block block= methodDecl.getBody();
List statements= block.statements();
assertTrue("Number of statements not 2", statements.size() == 2);
{ // remove expression, change type name, add argument, add anonym decl
ExpressionStatement stmt= (ExpressionStatement) statements.get(0);
ClassInstanceCreation creation= (ClassInstanceCreation) stmt.getExpression();
rewrite.markAsRemoved(creation.getExpression());
SimpleName newName= ast.newSimpleName("NewInner");
rewrite.markAsReplaced(creation.getName(), newName);
List arguments= creation.arguments();
StringLiteral stringLiteral1= ast.newStringLiteral();
stringLiteral1.setLiteralValue("Hello");
arguments.add(stringLiteral1);
rewrite.markAsInserted(stringLiteral1);
StringLiteral stringLiteral2= ast.newStringLiteral();
stringLiteral2.setLiteralValue("World");
arguments.add(stringLiteral2);
rewrite.markAsInserted(stringLiteral2);
assertTrue("Has anonym class decl", creation.getAnonymousClassDeclaration() == null);
AnonymousClassDeclaration anonymDecl= ast.newAnonymousClassDeclaration();
MethodDeclaration anonymMethDecl= createNewMethod(ast, "newMethod", false);
anonymDecl.bodyDeclarations().add(anonymMethDecl);
creation.setAnonymousClassDeclaration(anonymDecl);
rewrite.markAsInserted(anonymDecl);
}
{ // add expression, remove argument, remove anonym decl
ExpressionStatement stmt= (ExpressionStatement) statements.get(1);
ClassInstanceCreation creation= (ClassInstanceCreation) stmt.getExpression();
assertTrue("Has expression", creation.getExpression() == null);
SimpleName newExpression= ast.newSimpleName("x");
creation.setExpression(newExpression);
rewrite.markAsInserted(newExpression);
List arguments= creation.arguments();
assertTrue("Must have 1 argument", arguments.size() == 1);
rewrite.markAsRemoved((ASTNode) arguments.get(0));
rewrite.markAsRemoved(creation.getAnonymousClassDeclaration());
}
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null);
proposal.getCompilationUnitChange().setSave(true);
proposal.apply(null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" new NewInner(\"Hello\", \"World\") {\n");
buf.append(" private void newMethod(String str) {\n");
buf.append(" }\n");
buf.append(" };\n");
buf.append(" x.new Runnable();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
clearRewrite(rewrite);
}
public void testConditionalExpression() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" i= (k == 0) ? 1 : 2;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, false);
ASTRewrite rewrite= new ASTRewrite(astRoot);
AST ast= astRoot.getAST();
assertTrue("Parse errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0);
TypeDeclaration type= findTypeDeclaration(astRoot, "E");
MethodDeclaration methodDecl= findMethodDeclaration(type, "foo");
Block block= methodDecl.getBody();
List statements= block.statements();
assertTrue("Number of statements not 1", statements.size() == 1);
{ // change compare expression, then expression & else expression
ExpressionStatement stmt= (ExpressionStatement) statements.get(0);
Assignment assignment= (Assignment) stmt.getExpression();
ConditionalExpression condExpression= (ConditionalExpression) assignment.getRightHandSide();
BooleanLiteral literal= ast.newBooleanLiteral(true);
rewrite.markAsReplaced(condExpression.getExpression(), literal);
SimpleName newThenExpre= ast.newSimpleName("x");
rewrite.markAsReplaced(condExpression.getThenExpression(), newThenExpre);
InfixExpression infixExpression= ast.newInfixExpression();
infixExpression.setLeftOperand(ast.newNumberLiteral("1"));
infixExpression.setRightOperand(ast.newNumberLiteral("2"));
infixExpression.setOperator(InfixExpression.Operator.PLUS);
rewrite.markAsReplaced(condExpression.getElseExpression(), infixExpression);
}
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null);
proposal.getCompilationUnitChange().setSave(true);
proposal.apply(null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" i= true ? x : 1 + 2;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
clearRewrite(rewrite);
}
public void testFieldAccess() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" foo().i= goo().i;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, false);
ASTRewrite rewrite= new ASTRewrite(astRoot);
AST ast= astRoot.getAST();
assertTrue("Parse errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0);
TypeDeclaration type= findTypeDeclaration(astRoot, "E");
MethodDeclaration methodDecl= findMethodDeclaration(type, "foo");
Block block= methodDecl.getBody();
List statements= block.statements();
assertTrue("Number of statements not 1", statements.size() == 1);
{ // replace field expression, replace field name
ExpressionStatement stmt= (ExpressionStatement) statements.get(0);
Assignment assignment= (Assignment) stmt.getExpression();
FieldAccess leftFieldAccess= (FieldAccess) assignment.getLeftHandSide();
FieldAccess rightFieldAccess= (FieldAccess) assignment.getRightHandSide();
MethodInvocation invocation= ast.newMethodInvocation();
invocation.setName(ast.newSimpleName("xoo"));
rewrite.markAsReplaced(leftFieldAccess.getExpression(), invocation);
SimpleName newName= ast.newSimpleName("x");
rewrite.markAsReplaced(leftFieldAccess.getName(), newName);
SimpleName rightHand= ast.newSimpleName("b");
rewrite.markAsReplaced(rightFieldAccess.getExpression(), rightHand);
}
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null);
proposal.getCompilationUnitChange().setSave(true);
proposal.apply(null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" xoo().x= b.i;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
clearRewrite(rewrite);
}
public void testInfixExpression() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" i= 1 + 2;\n");
buf.append(" j= 1 + 2 + 3 + 4 + 5;\n");
buf.append(" k= 1 + 2 + 3 + 4 + 5;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, false);
ASTRewrite rewrite= new ASTRewrite(astRoot);
AST ast= astRoot.getAST();
assertTrue("Parse errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0);
TypeDeclaration type= findTypeDeclaration(astRoot, "E");
MethodDeclaration methodDecl= findMethodDeclaration(type, "foo");
Block block= methodDecl.getBody();
List statements= block.statements();
assertTrue("Number of statements not 3", statements.size() == 3);
{ // change left side & right side & operand
ExpressionStatement stmt= (ExpressionStatement) statements.get(0);
Assignment assignment= (Assignment) stmt.getExpression();
InfixExpression expr= (InfixExpression) assignment.getRightHandSide();
SimpleName leftOp= ast.newSimpleName("k");
rewrite.markAsReplaced(expr.getLeftOperand(), leftOp);
SimpleName rightOp= ast.newSimpleName("j");
rewrite.markAsReplaced(expr.getRightOperand(), rightOp);
// change operand
InfixExpression modifiedNode= ast.newInfixExpression();
modifiedNode.setOperator(InfixExpression.Operator.MINUS);
rewrite.markAsModified(expr, modifiedNode);
}
{ // remove an ext. operand, add one and replace one
ExpressionStatement stmt= (ExpressionStatement) statements.get(1);
Assignment assignment= (Assignment) stmt.getExpression();
InfixExpression expr= (InfixExpression) assignment.getRightHandSide();
List extendedOperands= expr.extendedOperands();
assertTrue("Number of extendedOperands not 3", extendedOperands.size() == 3);
rewrite.markAsRemoved((ASTNode) extendedOperands.get(0));
SimpleName newOp1= ast.newSimpleName("k");
rewrite.markAsReplaced((ASTNode) extendedOperands.get(1), newOp1);
SimpleName newOp2= ast.newSimpleName("n");
rewrite.markAsInserted(newOp2);
extendedOperands.add(newOp2);
}
{ // change operand
ExpressionStatement stmt= (ExpressionStatement) statements.get(2);
Assignment assignment= (Assignment) stmt.getExpression();
InfixExpression expr= (InfixExpression) assignment.getRightHandSide();
InfixExpression modifiedNode= ast.newInfixExpression();
modifiedNode.setOperator(InfixExpression.Operator.TIMES);
rewrite.markAsModified(expr, modifiedNode);
}
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null);
proposal.getCompilationUnitChange().setSave(true);
proposal.apply(null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" i= k - j;\n");
buf.append(" j= 1 + 2 + k + 5 + n;\n");
buf.append(" k= 1 * 2 * 3 * 4 * 5;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
clearRewrite(rewrite);
}
public void testInstanceofExpression() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" goo(k instanceof Vector);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, false);
ASTRewrite rewrite= new ASTRewrite(astRoot);
AST ast= astRoot.getAST();
assertTrue("Parse errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0);
TypeDeclaration type= findTypeDeclaration(astRoot, "E");
MethodDeclaration methodDecl= findMethodDeclaration(type, "foo");
Block block= methodDecl.getBody();
List statements= block.statements();
assertTrue("Number of statements not 1", statements.size() == 1);
{ // change left side & right side
ExpressionStatement stmt= (ExpressionStatement) statements.get(0);
MethodInvocation invocation= (MethodInvocation) stmt.getExpression();
List arguments= invocation.arguments();
InstanceofExpression expr= (InstanceofExpression) arguments.get(0);
SimpleName name= ast.newSimpleName("x");
rewrite.markAsReplaced(expr.getLeftOperand(), name);
Type newCastType= ast.newSimpleType(ast.newSimpleName("List"));
rewrite.markAsReplaced(expr.getRightOperand(), newCastType);
}
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null);
proposal.getCompilationUnitChange().setSave(true);
proposal.apply(null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" goo(x instanceof List);\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
clearRewrite(rewrite);
}
public void testMethodInvocation() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" foo(1, 2).goo();\n");
buf.append(" foo(1, 2).goo();\n");
buf.append(" foo(1, 2).goo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, false);
ASTRewrite rewrite= new ASTRewrite(astRoot);
AST ast= astRoot.getAST();
assertTrue("Parse errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0);
TypeDeclaration type= findTypeDeclaration(astRoot, "E");
MethodDeclaration methodDecl= findMethodDeclaration(type, "foo");
Block block= methodDecl.getBody();
List statements= block.statements();
assertTrue("Number of statements not 3", statements.size() == 3);
{ // remove expression, add param, change name
ExpressionStatement stmt= (ExpressionStatement) statements.get(0);
MethodInvocation invocation= (MethodInvocation) stmt.getExpression();
rewrite.markAsRemoved(invocation.getExpression());
SimpleName name= ast.newSimpleName("x");
rewrite.markAsReplaced(invocation.getName(), name);
ASTNode arg= ast.newNumberLiteral("1");
rewrite.markAsInserted(arg);
invocation.arguments().add(arg);
}
{ // insert expression, delete params
ExpressionStatement stmt= (ExpressionStatement) statements.get(1);
MethodInvocation invocation= (MethodInvocation) stmt.getExpression();
MethodInvocation leftInvocation= (MethodInvocation) invocation.getExpression();
SimpleName newExpression= ast.newSimpleName("x");
rewrite.markAsInserted(newExpression);
leftInvocation.setExpression(newExpression);
List args= leftInvocation.arguments();
rewrite.markAsRemoved((ASTNode) args.get(0));
rewrite.markAsRemoved((ASTNode) args.get(1));
}
{ // remove expression, add it as parameter
ExpressionStatement stmt= (ExpressionStatement) statements.get(2);
MethodInvocation invocation= (MethodInvocation) stmt.getExpression();
ASTNode placeHolder= rewrite.createCopy(invocation.getExpression());
rewrite.markAsRemoved(invocation.getExpression());
rewrite.markAsInserted(placeHolder);
invocation.arguments().add(placeHolder);
}
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null);
proposal.getCompilationUnitChange().setSave(true);
proposal.apply(null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" x(1);\n");
buf.append(" x.foo().goo();\n");
buf.append(" goo(foo(1, 2));\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
clearRewrite(rewrite);
}
public void testMethodParamsRenameReorder() throws Exception {
if (true)
return;
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void m(boolean y, int a) {\n");
buf.append(" m(y, a);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, false);
ASTRewrite rewrite= new ASTRewrite(astRoot);
AST ast= astRoot.getAST();
assertTrue("Parse errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0);
TypeDeclaration type= findTypeDeclaration(astRoot, "E");
MethodDeclaration methodDecl= findMethodDeclaration(type, "m");
Block block= methodDecl.getBody();
List statements= block.statements();
assertTrue("Number of statements not 1", statements.size() == 1);
{
//params
List params= methodDecl.parameters();
SingleVariableDeclaration firstParam= (SingleVariableDeclaration) params.get(0);
SingleVariableDeclaration secondParam= (SingleVariableDeclaration) params.get(1);
//args
ExpressionStatement stmt= (ExpressionStatement) statements.get(0);
MethodInvocation invocation= (MethodInvocation) stmt.getExpression();
List arguments= invocation.arguments();
SimpleName first= (SimpleName) arguments.get(0);
SimpleName second= (SimpleName) arguments.get(1);
//rename args
SimpleName newFirstArg= methodDecl.getAST().newSimpleName("yyy");
SimpleName newSecondArg= methodDecl.getAST().newSimpleName("bb");
rewrite.markAsReplaced(first, newFirstArg);
rewrite.markAsReplaced(second, newSecondArg);
//rename params
SimpleName newFirstName= methodDecl.getAST().newSimpleName("yyy");
SimpleName newSecondName= methodDecl.getAST().newSimpleName("bb");
rewrite.markAsReplaced(firstParam.getName(), newFirstName);
rewrite.markAsReplaced(secondParam.getName(), newSecondName);
//reoder params
ASTNode paramplaceholder1= rewrite.createCopy(firstParam);
ASTNode paramplaceholder2= rewrite.createCopy(secondParam);
rewrite.markAsReplaced(firstParam, paramplaceholder2);
rewrite.markAsReplaced(secondParam, paramplaceholder1);
//reorder args
ASTNode placeholder1= rewrite.createCopy(first);
ASTNode placeholder2= rewrite.createCopy(second);
rewrite.markAsReplaced(first, placeholder2);
rewrite.markAsReplaced(second, placeholder1);
}
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null);
proposal.getCompilationUnitChange().setSave(true);
proposal.apply(null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void m(int bb, boolean yyy) {\n");
buf.append(" m(bb, yyy);\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
clearRewrite(rewrite);
}
public void testMethodInvocation1() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" foo(foo(1, 2), 3);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, false);
ASTRewrite rewrite= new ASTRewrite(astRoot);
assertTrue("Parse errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0);
TypeDeclaration type= findTypeDeclaration(astRoot, "E");
MethodDeclaration methodDecl= findMethodDeclaration(type, "foo");
Block block= methodDecl.getBody();
List statements= block.statements();
assertTrue("Number of statements not 1", statements.size() == 1);
{ // remove expression, add param, change name
ExpressionStatement stmt= (ExpressionStatement) statements.get(0);
MethodInvocation invocation= (MethodInvocation) stmt.getExpression();
List arguments= invocation.arguments();
MethodInvocation first= (MethodInvocation) arguments.get(0);
ASTNode second= (ASTNode) arguments.get(1);
ASTNode placeholder1= rewrite.createCopy(first);
ASTNode placeholder2= rewrite.createCopy(second);
rewrite.markAsReplaced(first, placeholder2);
rewrite.markAsReplaced(second, placeholder1);
List innerArguments= first.arguments();
ASTNode innerFirst= (ASTNode) innerArguments.get(0);
ASTNode innerSecond= (ASTNode) innerArguments.get(1);
ASTNode innerPlaceholder1= rewrite.createCopy(innerFirst);
ASTNode innerPlaceholder2= rewrite.createCopy(innerSecond);
rewrite.markAsReplaced(innerFirst, innerPlaceholder2);
rewrite.markAsReplaced(innerSecond, innerPlaceholder1);
}
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null);
proposal.getCompilationUnitChange().setSave(true);
proposal.apply(null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" foo(3, foo(2, 1));\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
clearRewrite(rewrite);
}
public void testParenthesizedExpression() throws Exception {
//System.out.println(getClass().getName()+"::" + getName() +" disabled (bug 23362)");
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" i= (1 + 2) * 3;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, false);
ASTRewrite rewrite= new ASTRewrite(astRoot);
AST ast= astRoot.getAST();
assertTrue("Parse errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0);
TypeDeclaration type= findTypeDeclaration(astRoot, "E");
MethodDeclaration methodDecl= findMethodDeclaration(type, "foo");
Block block= methodDecl.getBody();
List statements= block.statements();
assertTrue("Number of statements not 1", statements.size() == 1);
{ // replace expression
ExpressionStatement stmt= (ExpressionStatement) statements.get(0);
Assignment assignment= (Assignment) stmt.getExpression();
InfixExpression multiplication= (InfixExpression) assignment.getRightHandSide();
ParenthesizedExpression parenthesizedExpression= (ParenthesizedExpression) multiplication.getLeftOperand();
SimpleName name= ast.newSimpleName("x");
rewrite.markAsReplaced(parenthesizedExpression.getExpression(), name);
}
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null);
proposal.getCompilationUnitChange().setSave(true);
proposal.apply(null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" i= (x) * 3;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
clearRewrite(rewrite);
}
public void testPrefixExpression() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" i= --x;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, false);
ASTRewrite rewrite= new ASTRewrite(astRoot);
AST ast= astRoot.getAST();
assertTrue("Parse errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0);
TypeDeclaration type= findTypeDeclaration(astRoot, "E");
MethodDeclaration methodDecl= findMethodDeclaration(type, "foo");
Block block= methodDecl.getBody();
List statements= block.statements();
assertTrue("Number of statements not 1", statements.size() == 1);
{ // modify operand and operation
ExpressionStatement stmt= (ExpressionStatement) statements.get(0);
Assignment assignment= (Assignment) stmt.getExpression();
PrefixExpression preExpression= (PrefixExpression) assignment.getRightHandSide();
NumberLiteral newOperation= ast.newNumberLiteral("10");
rewrite.markAsReplaced(preExpression.getOperand(), newOperation);
PrefixExpression modifiedNode= ast.newPrefixExpression();
modifiedNode.setOperator(PrefixExpression.Operator.COMPLEMENT);
rewrite.markAsModified(preExpression, modifiedNode);
}
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null);
proposal.getCompilationUnitChange().setSave(true);
proposal.apply(null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" i= ~10;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
clearRewrite(rewrite);
}
public void testPostfixExpression() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" i= x--;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, false);
ASTRewrite rewrite= new ASTRewrite(astRoot);
AST ast= astRoot.getAST();
assertTrue("Parse errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0);
TypeDeclaration type= findTypeDeclaration(astRoot, "E");
MethodDeclaration methodDecl= findMethodDeclaration(type, "foo");
Block block= methodDecl.getBody();
List statements= block.statements();
assertTrue("Number of statements not 1", statements.size() == 1);
{ // modify operand and operation
ExpressionStatement stmt= (ExpressionStatement) statements.get(0);
Assignment assignment= (Assignment) stmt.getExpression();
PostfixExpression postExpression= (PostfixExpression) assignment.getRightHandSide();
NumberLiteral newOperation= ast.newNumberLiteral("10");
rewrite.markAsReplaced(postExpression.getOperand(), newOperation);
PostfixExpression modifiedNode= ast.newPostfixExpression();
modifiedNode.setOperator(PostfixExpression.Operator.INCREMENT);
rewrite.markAsModified(postExpression, modifiedNode);
}
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null);
proposal.getCompilationUnitChange().setSave(true);
proposal.apply(null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" i= 10++;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
clearRewrite(rewrite);
}
public void testSuperConstructorInvocation() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public E() {\n");
buf.append(" super();\n");
buf.append(" }\n");
buf.append(" public E(int i) {\n");
buf.append(" foo(i + i).super(i);\n");
buf.append(" }\n");
buf.append(" public E(int i, int k) {\n");
buf.append(" Outer.super(foo(goo(x)), 1);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, false);
ASTRewrite rewrite= new ASTRewrite(astRoot);
AST ast= astRoot.getAST();
assertTrue("Parse errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0);
TypeDeclaration type= findTypeDeclaration(astRoot, "E");
List bodyDeclarations= type.bodyDeclarations();
assertTrue("Number of bodyDeclarations not 3", bodyDeclarations.size() == 3);
{ // add expresssion & parameter
MethodDeclaration methodDecl= (MethodDeclaration) bodyDeclarations.get(0);
SuperConstructorInvocation invocation= (SuperConstructorInvocation) methodDecl.getBody().statements().get(0);
SimpleName newExpression= ast.newSimpleName("x");
rewrite.markAsInserted(newExpression);
invocation.setExpression(newExpression);
ASTNode arg= ast.newNumberLiteral("1");
rewrite.markAsInserted(arg);
invocation.arguments().add(arg);
}
{ // remove expression, replace argument with argument of expression
MethodDeclaration methodDecl= (MethodDeclaration) bodyDeclarations.get(1);
SuperConstructorInvocation invocation= (SuperConstructorInvocation) methodDecl.getBody().statements().get(0);
MethodInvocation expression= (MethodInvocation) invocation.getExpression();
rewrite.markAsRemoved(expression);
ASTNode placeHolder= rewrite.createCopy((ASTNode) expression.arguments().get(0));
ASTNode arg1= (ASTNode) invocation.arguments().get(0);
rewrite.markAsReplaced(arg1, placeHolder);
}
{ // remove argument, replace expression with part of argument
MethodDeclaration methodDecl= (MethodDeclaration) bodyDeclarations.get(2);
SuperConstructorInvocation invocation= (SuperConstructorInvocation) methodDecl.getBody().statements().get(0);
MethodInvocation arg1= (MethodInvocation) invocation.arguments().get(0);
rewrite.markAsRemoved(arg1);
ASTNode placeHolder= rewrite.createCopy((ASTNode) arg1.arguments().get(0));
rewrite.markAsReplaced((ASTNode) invocation.getExpression(), placeHolder);
}
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null);
proposal.getCompilationUnitChange().setSave(true);
proposal.apply(null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public E() {\n");
buf.append(" x.super(1);\n");
buf.append(" }\n");
buf.append(" public E(int i) {\n");
buf.append(" super(i + i);\n");
buf.append(" }\n");
buf.append(" public E(int i, int k) {\n");
buf.append(" goo(x).super(1);\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
clearRewrite(rewrite);
}
public void testSuperFieldInvocation() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" super.x= Outer.super.y;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, false);
ASTRewrite rewrite= new ASTRewrite(astRoot);
AST ast= astRoot.getAST();
assertTrue("Parse errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0);
TypeDeclaration type= findTypeDeclaration(astRoot, "E");
MethodDeclaration methodDecl= findMethodDeclaration(type, "foo");
Block block= methodDecl.getBody();
List statements= block.statements();
assertTrue("Number of statements not 1", statements.size() == 1);
{ // insert qualifier, replace field name, delete qualifier
ExpressionStatement stmt= (ExpressionStatement) statements.get(0);
Assignment assignment= (Assignment) stmt.getExpression();
SuperFieldAccess leftFieldAccess= (SuperFieldAccess) assignment.getLeftHandSide();
SuperFieldAccess rightFieldAccess= (SuperFieldAccess) assignment.getRightHandSide();
SimpleName newQualifier= ast.newSimpleName("X");
rewrite.markAsInserted(newQualifier);
leftFieldAccess.setQualifier(newQualifier);
SimpleName newName= ast.newSimpleName("y");
rewrite.markAsReplaced(leftFieldAccess.getName(), newName);
rewrite.markAsRemoved(rightFieldAccess.getQualifier());
}
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null);
proposal.getCompilationUnitChange().setSave(true);
proposal.apply(null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" X.super.y= super.y;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
clearRewrite(rewrite);
}
public void testSuperMethodInvocation() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" super.foo();\n");
buf.append(" Outer.super.foo(i);\n");
buf.append(" Outer.super.foo(foo(X.goo()), 1);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, false);
ASTRewrite rewrite= new ASTRewrite(astRoot);
AST ast= astRoot.getAST();
assertTrue("Parse errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0);
TypeDeclaration type= findTypeDeclaration(astRoot, "E");
MethodDeclaration methodDecl= findMethodDeclaration(type, "foo");
Block block= methodDecl.getBody();
List statements= block.statements();
assertTrue("Number of statements not 3", statements.size() == 3);
{ // add qualifier & parameter
ExpressionStatement statement= (ExpressionStatement) statements.get(0);
SuperMethodInvocation invocation= (SuperMethodInvocation) statement.getExpression();
SimpleName newExpression= ast.newSimpleName("X");
rewrite.markAsInserted(newExpression);
invocation.setQualifier(newExpression);
ASTNode arg= ast.newNumberLiteral("1");
rewrite.markAsInserted(arg);
invocation.arguments().add(arg);
}
{ // remove qualifier, replace argument with argument of expression
ExpressionStatement statement= (ExpressionStatement) statements.get(1);
SuperMethodInvocation invocation= (SuperMethodInvocation) statement.getExpression();
Name qualifier= (Name) invocation.getQualifier();
rewrite.markAsRemoved(qualifier);
Name placeHolder= (Name) rewrite.createCopy(qualifier);
FieldAccess newFieldAccess= ast.newFieldAccess();
newFieldAccess.setExpression(placeHolder);
newFieldAccess.setName(ast.newSimpleName("count"));
ASTNode arg1= (ASTNode) invocation.arguments().get(0);
rewrite.markAsReplaced(arg1, newFieldAccess);
}
{ // remove argument, replace qualifier with part argument qualifier
ExpressionStatement statement= (ExpressionStatement) statements.get(2);
SuperMethodInvocation invocation= (SuperMethodInvocation) statement.getExpression();
MethodInvocation arg1= (MethodInvocation) invocation.arguments().get(0);
rewrite.markAsRemoved(arg1);
MethodInvocation innerArg= (MethodInvocation) arg1.arguments().get(0);
ASTNode placeHolder= rewrite.createCopy((ASTNode) innerArg.getExpression());
rewrite.markAsReplaced((ASTNode) invocation.getQualifier(), placeHolder);
}
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null);
proposal.getCompilationUnitChange().setSave(true);
proposal.apply(null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" X.super.foo(1);\n");
buf.append(" super.foo(Outer.count);\n");
buf.append(" X.super.foo(1);\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
clearRewrite(rewrite);
}
public void testThisExpression() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" return this;\n");
buf.append(" return Outer.this;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, false);
ASTRewrite rewrite= new ASTRewrite(astRoot);
AST ast= astRoot.getAST();
assertTrue("Parse errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0);
TypeDeclaration type= findTypeDeclaration(astRoot, "E");
MethodDeclaration methodDecl= findMethodDeclaration(type, "foo");
Block block= methodDecl.getBody();
List statements= block.statements();
assertTrue("Number of statements not 2", statements.size() == 2);
{ // add qualifier
ReturnStatement returnStatement= (ReturnStatement) statements.get(0);
ThisExpression thisExpression= (ThisExpression) returnStatement.getExpression();
SimpleName newExpression= ast.newSimpleName("X");
rewrite.markAsInserted(newExpression);
thisExpression.setQualifier(newExpression);
}
{ // remove qualifier
ReturnStatement returnStatement= (ReturnStatement) statements.get(1);
ThisExpression thisExpression= (ThisExpression) returnStatement.getExpression();
rewrite.markAsRemoved(thisExpression.getQualifier());
}
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null);
proposal.getCompilationUnitChange().setSave(true);
proposal.apply(null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" return X.this;\n");
buf.append(" return this;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
clearRewrite(rewrite);
}
public void testTypeLiteral() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" return E.class;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, false);
ASTRewrite rewrite= new ASTRewrite(astRoot);
AST ast= astRoot.getAST();
assertTrue("Parse errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0);
TypeDeclaration type= findTypeDeclaration(astRoot, "E");
MethodDeclaration methodDecl= findMethodDeclaration(type, "foo");
Block block= methodDecl.getBody();
List statements= block.statements();
assertTrue("Number of statements not 1", statements.size() == 1);
{ // replace type
ReturnStatement returnStatement= (ReturnStatement) statements.get(0);
TypeLiteral typeLiteral= (TypeLiteral) returnStatement.getExpression();
Type newType= ast.newPrimitiveType(PrimitiveType.VOID);
rewrite.markAsReplaced(typeLiteral.getType(), newType);
}
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null);
proposal.getCompilationUnitChange().setSave(true);
proposal.apply(null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" return void.class;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(cu.getSource(), buf.toString());
clearRewrite(rewrite);
}
}
|
29,272 |
Bug 29272 Typo in warning
|
When renaming a method (refactoring) if you start the method name with an upper case letter, you get a warning of: "By convention, all names of methods start with uppercase letters" It should, of course, read: "By convention, all names of methods start with lowercase letters"
|
resolved fixed
|
ad0d061
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-10T09:03:35Z | 2003-01-10T09:13:20Z |
org.eclipse.jdt.ui/core
| |
29,272 |
Bug 29272 Typo in warning
|
When renaming a method (refactoring) if you start the method name with an upper case letter, you get a warning of: "By convention, all names of methods start with uppercase letters" It should, of course, read: "By convention, all names of methods start with lowercase letters"
|
resolved fixed
|
ad0d061
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-10T09:03:35Z | 2003-01-10T09:13:20Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/Checks.java
| |
29,200 |
Bug 29200 NPE from 'Occurences in File'
|
Found in my log (don't have the corresponding source anymore) java.lang.NullPointerException at org.eclipse.jdt.internal.ui.search.SearchUsagesInFileAction$NameUsagesFinder.mat ch(SearchUsagesInFileAction.java(Compiled Code)) at org.eclipse.jdt.internal.ui.search.SearchUsagesInFileAction$NameUsagesFinder.vis it(SearchUsagesInFileAction.java(Compiled Code)) at org.eclipse.jdt.core.dom.SimpleName.accept0(SimpleName.java(Compiled Code)) at org.eclipse.jdt.core.dom.ASTNode.acceptChild(ASTNode.java(Compiled Code)) at org.eclipse.jdt.core.dom.ASTNode.acceptChild(ASTNode.java(Compiled Code)) at org.eclipse.jdt.core.dom.LabeledStatement.accept0 (LabeledStatement.java:87) at org.eclipse.jdt.core.dom.ASTNode.accept(ASTNode.java(Compiled Code)) at org.eclipse.jdt.core.dom.ASTNode.acceptChildren(ASTNode.java (Compiled Code)) at org.eclipse.jdt.core.dom.Block.accept0(Block.java:81) at org.eclipse.jdt.core.dom.ASTNode.acceptChild(ASTNode.java(Compiled Code)) at org.eclipse.jdt.core.dom.ASTNode.acceptChild(ASTNode.java(Compiled Code)) at org.eclipse.jdt.core.dom.TryStatement.accept0(TryStatement.java:100) at org.eclipse.jdt.core.dom.ASTNode.accept(ASTNode.java(Compiled Code)) at org.eclipse.jdt.core.dom.ASTNode.acceptChildren(ASTNode.java (Compiled Code)) at org.eclipse.jdt.core.dom.Block.accept0(Block.java:81) at org.eclipse.jdt.core.dom.ASTNode.acceptChild(ASTNode.java(Compiled Code)) at org.eclipse.jdt.core.dom.ASTNode.acceptChild(ASTNode.java(Compiled Code)) at org.eclipse.jdt.core.dom.MethodDeclaration.accept0 (MethodDeclaration.java:179) at org.eclipse.jdt.core.dom.ASTNode.accept(ASTNode.java(Compiled Code)) at org.eclipse.jdt.core.dom.ASTNode.acceptChildren(ASTNode.java (Compiled Code)) at org.eclipse.jdt.core.dom.TypeDeclaration.accept0 (TypeDeclaration.java:161) at org.eclipse.jdt.core.dom.ASTNode.accept(ASTNode.java(Compiled Code)) at org.eclipse.jdt.core.dom.ASTNode.acceptChildren(ASTNode.java (Compiled Code)) at org.eclipse.jdt.core.dom.CompilationUnit.accept0 (CompilationUnit.java:158) at org.eclipse.jdt.core.dom.ASTNode.accept(ASTNode.java(Compiled Code)) at org.eclipse.jdt.internal.ui.search.SearchUsagesInFileAction$1.run (SearchUsagesInFileAction.java:209) at org.eclipse.core.internal.resources.Workspace.run (Workspace.java:1564) at org.eclipse.jdt.internal.ui.search.SearchUsagesInFileAction$2.run (SearchUsagesInFileAction.java:233) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java (Compiled Code)) at org.eclipse.jdt.internal.ui.search.SearchUsagesInFileAction.run (SearchUsagesInFileAction.java:229) at org.eclipse.jdt.internal.ui.search.SearchUsagesInFileAction.run (SearchUsagesInFileAction.java:225) at org.eclipse.jface.action.Action.runWithEvent(Action.java:769) at org.eclipse.ui.internal.WWinKeyBindingService.invoke (WWinKeyBindingService.java:139) at org.eclipse.ui.internal.WWinKeyBindingService.pressed (WWinKeyBindingService.java:120) at org.eclipse.ui.internal.WWinKeyBindingService$6.widgetSelected (WWinKeyBindingService.java:376) at org.eclipse.ui.internal.AcceleratorMenu$2.handleEvent (AcceleratorMenu.java:55) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1450) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:845) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:462) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539)
|
resolved fixed
|
a9e1a8f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-10T16:13:21Z | 2003-01-09T11:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/SearchUsagesInFileAction.java
|
/*******************************************************************************
* Copyright (c) 2003 International Business Machines Corp. and others. All
* rights reserved. This program and the accompanying materials are made
* available under the terms of the Common Public License v0.5 which accompanies
* this distribution, and is available at http://www.eclipse.org/legal/cpl-v05.
* html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.internal.ui.search;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.Assignment;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.FieldAccess;
import org.eclipse.jdt.core.dom.IBinding;
import org.eclipse.jdt.core.dom.IVariableBinding;
import org.eclipse.jdt.core.dom.Name;
import org.eclipse.jdt.core.dom.PostfixExpression;
import org.eclipse.jdt.core.dom.PrefixExpression;
import org.eclipse.jdt.core.dom.QualifiedName;
import org.eclipse.jdt.core.dom.SimpleName;
import org.eclipse.jdt.core.dom.SingleVariableDeclaration;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
import org.eclipse.jdt.internal.corext.dom.NodeFinder;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.javaeditor.IClassFileEditorInput;
import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.search.ui.IGroupByKeyComputer;
import org.eclipse.search.ui.ISearchResultView;
import org.eclipse.search.ui.SearchUI;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.texteditor.MarkerUtilities;
/**
* Searches for occurences of the element at the caret
* in a file using the AST.
*/
public class SearchUsagesInFileAction extends Action {
static public class NameUsagesFinder extends ASTVisitor {
private IBinding fTarget;
private List fUsages= new ArrayList();
private List fWriteUsages= new ArrayList();
public NameUsagesFinder(IBinding target) {
super();
fTarget= target;
}
public boolean visit(QualifiedName node) {
match(node, fUsages);
return super.visit(node);
}
public boolean visit(SimpleName node) {
match(node, fUsages);
return super.visit(node);
}
public boolean visit(Assignment node) {
Expression lhs= node.getLeftHandSide();
Name name= getName(lhs);
if (name != null)
match(name, fWriteUsages);
lhs.accept(this);
node.getRightHandSide().accept(this);
return false;
}
public boolean visit(SingleVariableDeclaration node) {
if (node.getInitializer() != null)
match(node.getName(), fWriteUsages);
return super.visit(node);
}
public boolean visit(VariableDeclarationFragment node) {
if (node.getInitializer() != null)
match(node.getName(), fWriteUsages);
return super.visit(node);
}
public boolean visit(PrefixExpression node) {
PrefixExpression.Operator operator= node.getOperator();
if (operator == PrefixExpression.Operator.INCREMENT || operator == PrefixExpression.Operator.DECREMENT) {
Expression operand= node.getOperand();
Name name= getName(operand);
if (name != null)
match(name, fWriteUsages);
}
return super.visit(node);
}
public boolean visit(PostfixExpression node) {
Expression operand= node.getOperand();
Name name= getName(operand);
if (name != null)
match(name, fWriteUsages);
return super.visit(node);
}
public List getUsages() {
return fUsages;
}
public List getWriteUsages() {
return fWriteUsages;
}
private void match(Name node, List result) {
IBinding binding= node.resolveBinding();
if (binding.equals(fTarget)) {
result.add(node);
return;
}
String otherKey= binding.getKey();
String targetKey= fTarget.getKey();
if (targetKey != null && otherKey != null) {
if (targetKey.equals(otherKey))
result.add(node);
}
}
private Name getName(Expression expression) {
if (expression instanceof SimpleName)
return ((SimpleName)expression);
else if (expression instanceof QualifiedName)
return ((QualifiedName)expression);
else if (expression instanceof FieldAccess)
return ((FieldAccess)expression).getName();
return null;
}
}
static class SearchGroupByKeyComputer implements IGroupByKeyComputer {
//TODO it seems that GroupByKeyComputers are obsolete...
public Object computeGroupByKey(IMarker marker) {
return marker;
}
}
public static final String SHOWREFERENCES= "ShowReferences"; //$NON-NLS-1$
public static final String IS_WRITEACCESS= "writeAccess"; //$NON-NLS-1$
public static final String IS_VARIABLE= "variable"; //$NON-NLS-1$
private JavaEditor fEditor;
private IRunnableWithProgress fNullOperation= getNullOperation();
public SearchUsagesInFileAction(JavaEditor editor) {
super(SearchMessages.getString("Search.FindUsageInFile.label")); //$NON-NLS-1$
setToolTipText(SearchMessages.getString("Search.FindUsageInFile.tooltip")); //$NON-NLS-1$
// TODO help context ID
fEditor= editor;
boolean enabled= false;
if (getClassFile() != null || SelectionConverter.getInputAsCompilationUnit(fEditor) != null)
enabled= true;
setEnabled(enabled);
}
/* (non-JavaDoc)
* Method declared in IAction.
*/
public final void run() {
ITextSelection ts= getTextSelection();
final CompilationUnit root= createAST();
if (root == null)
return;
ASTNode node= NodeFinder.perform(root, ts.getOffset(), ts.getLength());
if (!(node instanceof Name))
return;
final Name name= (Name)node;
final IBinding target= name.resolveBinding();
if (target == null)
return;
final IWorkspaceRunnable runnable= new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) throws CoreException {
IJavaElement element= getInput();
ISearchResultView view= startSearch(element.getElementName(), name);
NameUsagesFinder finder= new NameUsagesFinder(target);
root.accept(finder);
List matches= finder.getUsages();
List writeMatches= finder.getWriteUsages();
IResource file= getResource(element);
for (Iterator each= matches.iterator(); each.hasNext();) {
ASTNode node= (ASTNode) each.next();
addMatch(
view,
file,
createMarker(file, node, writeMatches.contains(node),
target instanceof IVariableBinding)
);
}
searchFinished(view);
}
};
run(runnable);
}
public CompilationUnit createAST() {
IEditorInput input= fEditor.getEditorInput();
if (input instanceof IClassFileEditorInput) {
IClassFile classFile= ((IClassFileEditorInput)input).getClassFile();
try {
String source= classFile.getSource();
return AST.parseCompilationUnit(source.toCharArray(), classFile.getElementName(), classFile.getJavaProject());
} catch (JavaModelException e) {
return null;
}
}
return AST.parseCompilationUnit(getCompilationUnit(), true);
}
public void run(final IWorkspaceRunnable runnable) {
BusyIndicator.showWhile(fEditor.getSite().getShell().getDisplay(),
new Runnable() {
public void run() {
try {
ResourcesPlugin.getWorkspace().run(runnable, null);
} catch (CoreException e) {
JavaPlugin.log(e);
}
}
}
);
}
public ISearchResultView startSearch(String fileName, final Name name) {
SearchUI.activateSearchResultView();
ISearchResultView view= SearchUI.getSearchResultView();
String elementName= getName(name);
if (view != null)
view.searchStarted(
null,
getSingularLabel(elementName, fileName),
getPluralLabel(elementName, fileName),
JavaPluginImages.DESC_OBJS_SEARCH_REF,
"org.eclipse.jdt.ui.JavaFileSearch", //$NON-NLS-1$
new SearchUsagesInFileLabelProvider(),
new GotoMarkerAction(),
new SearchGroupByKeyComputer(),
fNullOperation
);
return view;
}
public String getPluralLabel(String nodeContents, String elementName) {
String[] args= new String[] {nodeContents, "{0}", elementName}; //$NON-NLS-1$
return SearchMessages.getFormattedString("JavaSearchInFile.pluralPostfix", args); //$NON-NLS-1$
}
public String getSingularLabel(String nodeContents, String elementName) {
String[] args= new String[] {nodeContents, elementName}; //$NON-NLS-1$
return SearchMessages.getFormattedString("JavaSearchInFile.singularPostfix", args); //$NON-NLS-1$
}
public void addMatch(final ISearchResultView view, IResource file, IMarker marker) {
if (view != null)
view.addMatch("", getGroupByKey(marker), file, marker); //$NON-NLS-1$
}
private Object getGroupByKey(IMarker marker) {
try {
return marker.getAttribute(IMarker.LINE_NUMBER);
} catch (CoreException e) {
}
return marker;
}
public void searchFinished(final ISearchResultView view) {
if (view != null)
view.searchFinished();
}
public IRunnableWithProgress getNullOperation() {
return new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
}
};
}
private String getName(Name name) {
IDocument document= getDocument();
String result= ""; //$NON-NLS-1$
try {
result= document.get(name.getStartPosition(), name.getLength());
} catch (BadLocationException e) {
}
return result;
}
private IResource getResource(IJavaElement element) throws JavaModelException {
if (element instanceof ICompilationUnit) {
ICompilationUnit cu= (ICompilationUnit)element;
if (cu.isWorkingCopy()) {
IJavaElement original= cu.getOriginalElement();
return original.getUnderlyingResource();
}
return cu.getUnderlyingResource();
}
return element.getJavaProject().getProject();
}
private IMarker createMarker(IResource file, ASTNode element, boolean writeAccess, boolean isVariable) throws CoreException {
Map attributes= new HashMap(10);
IMarker marker= file.createMarker(SearchUI.SEARCH_MARKER);
int startPosition= element.getStartPosition();
MarkerUtilities.setCharStart(attributes, startPosition);
MarkerUtilities.setCharEnd(attributes, startPosition + element.getLength());
// for class files
if (!(file instanceof IFile)) {
attributes.put(IWorkbenchPage.EDITOR_ID_ATTR, JavaUI.ID_CF_EDITOR);
JavaCore.addJavaElementMarkerAttributes(attributes, getClassFile().getType());
attributes.put(IJavaSearchUIConstants.ATT_JE_HANDLE_ID, getClassFile().getType().getHandleIdentifier());
}
if(writeAccess)
attributes.put(IS_WRITEACCESS, new Boolean(true));
if(isVariable)
attributes.put(IS_VARIABLE, new Boolean(true));
IDocument document= getDocument();
try {
int line= document.getLineOfOffset(startPosition);
MarkerUtilities.setLineNumber(attributes, line);
IRegion region= document.getLineInformation(line);
String lineContents= document.get(region.getOffset(), region.getLength());
MarkerUtilities.setMessage(attributes, lineContents.trim());
} catch (BadLocationException e) {
}
marker.setAttributes(attributes);
return marker;
}
protected final IJavaElement getInput() {
IClassFile classFile= getClassFile();
if (classFile != null)
return classFile;
return getCompilationUnit();
}
protected ICompilationUnit getCompilationUnit() {
return JavaPlugin.getDefault().getWorkingCopyManager().getWorkingCopy(fEditor.getEditorInput());
}
protected final IClassFile getClassFile() {
IEditorInput input= fEditor.getEditorInput();
if (input instanceof IClassFileEditorInput)
return ((IClassFileEditorInput)input).getClassFile();
return null;
}
protected final IDocument getDocument() {
return fEditor.getDocumentProvider().getDocument(fEditor.getEditorInput());
}
protected final ITextSelection getTextSelection() {
return (ITextSelection)fEditor.getSelectionProvider().getSelection();
}
}
|
28,267 |
Bug 28267 55% of open type hiearchy spent in sorting [type hierarchy]
|
20021210+latest 1213 junit workspace typehierarchy on Object 55% is spent in sorting
|
resolved fixed
|
c1dd284
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-13T11:01:47Z | 2002-12-13T14:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/JavaElementAdapterFactory.java
|
/*
* (c) Copyright IBM Corp. 2000, 2002.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IAdapterFactory;
import org.eclipse.ui.IContributorResourceAdapter;
import org.eclipse.ui.IPersistableElement;
import org.eclipse.ui.model.IWorkbenchAdapter;
import org.eclipse.ui.views.properties.FilePropertySource;
import org.eclipse.ui.views.properties.IPropertySource;
import org.eclipse.ui.views.properties.ResourcePropertySource;
import org.eclipse.ui.views.tasklist.ITaskListResourceAdapter;
import org.eclipse.search.ui.ISearchPageScoreComputer;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.ui.search.JavaSearchPageScoreComputer;
import org.eclipse.jdt.internal.ui.search.SearchUtil;
/**
* Implements basic UI support for Java elements.
* Implements handle to persistent support for Java elements.
*/
public class JavaElementAdapterFactory implements IAdapterFactory, IContributorResourceAdapter{
private static Class[] PROPERTIES= new Class[] {
IPropertySource.class,
IResource.class,
IWorkbenchAdapter.class,
IResourceLocator.class,
IPersistableElement.class,
IProject.class,
IContributorResourceAdapter.class,
ITaskListResourceAdapter.class
};
private Object fSearchPageScoreComputer;
private static IResourceLocator fgResourceLocator= new ResourceLocator();
private static JavaWorkbenchAdapter fgJavaWorkbenchAdapter= new JavaWorkbenchAdapter();
private static ITaskListResourceAdapter fgTaskListAdapter= new JavaTaskListAdapter();
public Class[] getAdapterList() {
updateLazyLoadedAdapters();
return PROPERTIES;
}
public Object getAdapter(Object element, Class key) {
updateLazyLoadedAdapters();
IJavaElement java= (IJavaElement) element;
if (IPropertySource.class.equals(key)) {
return getProperties(java);
} if (IResource.class.equals(key)) {
return getResource(java);
} if (IProject.class.equals(key)) {
return getProject(java);
} if (fSearchPageScoreComputer != null && ISearchPageScoreComputer.class.equals(key)) {
return fSearchPageScoreComputer;
} if (IWorkbenchAdapter.class.equals(key)) {
return fgJavaWorkbenchAdapter;
} if (IResourceLocator.class.equals(key)) {
return fgResourceLocator;
} if (IPersistableElement.class.equals(key)) {
return new PersistableJavaElementFactory(java);
} if (IContributorResourceAdapter.class.equals(key)) {
return this;
} if (ITaskListResourceAdapter.class.equals(key)) {
return fgTaskListAdapter;
}
return null;
}
private IResource getResource(IJavaElement element) {
/*
* Map a type to the corresponding CU.
*/
if (element instanceof IType) {
IType type= (IType)element;
IJavaElement parent= type.getParent();
if (parent instanceof ICompilationUnit) {
ICompilationUnit cu= (ICompilationUnit)parent;
if (cu.isWorkingCopy())
element= cu.getOriginalElement();
else
element= cu;
}
}
try {
return element.getCorrespondingResource();
} catch (JavaModelException e) {
if (element instanceof ICompilationUnit)
return element.getResource(); //handles compilation units outside of the classpath
else
return null;
}
}
/*
* @see org.eclipse.ui.IContributorResourceAdapter#getAdaptedResource(org.eclipse.core.runtime.IAdaptable)
*/
public IResource getAdaptedResource(IAdaptable adaptable) {
return getResource((IJavaElement)adaptable);
}
private IResource getProject(IJavaElement element) {
return element.getJavaProject().getProject();
}
private IPropertySource getProperties(IJavaElement element) {
IResource resource= getResource(element);
if (resource == null)
return new JavaElementProperties(element);
if (resource.getType() == IResource.FILE)
return new FilePropertySource((IFile) resource);
return new ResourcePropertySource((IResource) resource);
}
private void updateLazyLoadedAdapters() {
if (fSearchPageScoreComputer == null && SearchUtil.isSearchPlugInActivated())
createSearchPageScoreComputer();
}
private void createSearchPageScoreComputer() {
fSearchPageScoreComputer= new JavaSearchPageScoreComputer();
PROPERTIES= new Class[] {
IPropertySource.class,
IResource.class,
ISearchPageScoreComputer.class,
IWorkbenchAdapter.class,
IResourceLocator.class,
IPersistableElement.class,
IProject.class,
IContributorResourceAdapter.class,
ITaskListResourceAdapter.class
};
}
}
|
29,375 |
Bug 29375 Search for reference gives strange results when references are in static initialisers [search]
|
[M4] When references to a class or method are in the static initialiser for a class (which is also in a package other than the default one) the results contain spurious nulls. Test case: package foo.bar; public class Test { static { new Test().toString(); } } Highlight "Test" (either place) and search for references in the workspace. The result will be: nullnullbar.Test.{...}
|
resolved fixed
|
b00b226
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-13T15:26:03Z | 2003-01-13T12:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/viewsupport/JavaElementLabels.java
|
package org.eclipse.jdt.internal.ui.viewsupport;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.ui.model.IWorkbenchAdapter;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IInitializer;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
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;
public class JavaElementLabels {
/**
* Method names contain parameter types.
* e.g. <code>foo(int)</code>
*/
public final static int M_PARAMETER_TYPES= 1 << 0;
/**
* Method names contain parameter names.
* e.g. <code>foo(index)</code>
*/
public final static int M_PARAMETER_NAMES= 1 << 1;
/**
* Method names contain thrown exceptions.
* e.g. <code>foo throws IOException</code>
*/
public final static int M_EXCEPTIONS= 1 << 2;
/**
* Method names contain return type (appended)
* e.g. <code>foo : int</code>
*/
public final static int M_APP_RETURNTYPE= 1 << 3;
/**
* Method names contain return type (appended)
* e.g. <code>int foo</code>
*/
public final static int M_PRE_RETURNTYPE= 1 << 4;
/**
* Method names are fully qualified.
* e.g. <code>java.util.Vector.size</code>
*/
public final static int M_FULLY_QUALIFIED= 1 << 5;
/**
* Method names are post qualified.
* e.g. <code>size - java.util.Vector</code>
*/
public final static int M_POST_QUALIFIED= 1 << 6;
/**
* Initializer names are fully qualified.
* e.g. <code>java.util.Vector.{ ... }</code>
*/
public final static int I_FULLY_QUALIFIED= 1 << 7;
/**
* Type names are post qualified.
* e.g. <code>{ ... } - java.util.Map</code>
*/
public final static int I_POST_QUALIFIED= 1 << 8;
/**
* Field names contain the declared type (appended)
* e.g. <code>int fHello</code>
*/
public final static int F_APP_TYPE_SIGNATURE= 1 << 9;
/**
* Field names contain the declared type (prepended)
* e.g. <code>fHello : int</code>
*/
public final static int F_PRE_TYPE_SIGNATURE= 1 << 10;
/**
* Fields names are fully qualified.
* e.g. <code>java.lang.System.out</code>
*/
public final static int F_FULLY_QUALIFIED= 1 << 11;
/**
* Fields names are post qualified.
* e.g. <code>out - java.lang.System</code>
*/
public final static int F_POST_QUALIFIED= 1 << 12;
/**
* Type names are fully qualified.
* e.g. <code>java.util.Map.MapEntry</code>
*/
public final static int T_FULLY_QUALIFIED= 1 << 13;
/**
* Type names are type container qualified.
* e.g. <code>Map.MapEntry</code>
*/
public final static int T_CONTAINER_QUALIFIED= 1 << 14;
/**
* Type names are post qualified.
* e.g. <code>MapEntry - java.util.Map</code>
*/
public final static int T_POST_QUALIFIED= 1 << 15;
/**
* Declarations (import container / declarartion, package declarartion) are qualified.
* e.g. <code>java.util.Vector.class/import container</code>
*/
public final static int D_QUALIFIED= 1 << 16;
/**
* Declarations (import container / declarartion, package declarartion) are post qualified.
* e.g. <code>import container - java.util.Vector.class</code>
*/
public final static int D_POST_QUALIFIED= 1 << 17;
/**
* Class file names are fully qualified.
* e.g. <code>java.util.Vector.class</code>
*/
public final static int CF_QUALIFIED= 1 << 18;
/**
* Class file names are post qualified.
* e.g. <code>Vector.class - java.util</code>
*/
public final static int CF_POST_QUALIFIED= 1 << 19;
/**
* Compilation unit names are fully qualified.
* e.g. <code>java.util.Vector.java</code>
*/
public final static int CU_QUALIFIED= 1 << 20;
/**
* Compilation unit names are post qualified.
* e.g. <code>Vector.java - java.util</code>
*/
public final static int CU_POST_QUALIFIED= 1 << 21;
/**
* Package names are qualified.
* e.g. <code>MyProject/src/java.util</code>
*/
public final static int P_QUALIFIED= 1 << 22;
/**
* Package names are post qualified.
* e.g. <code>java.util - MyProject/src</code>
*/
public final static int P_POST_QUALIFIED= 1 << 23;
/**
* Package Fragment Roots contain variable name if from a variable.
* e.g. <code>JRE_LIB - c:\java\lib\rt.jar</code>
*/
public final static int ROOT_VARIABLE= 1 << 24;
/**
* Package Fragment Roots contain the project name if not an archive (prepended).
* e.g. <code>MyProject/src</code>
*/
public final static int ROOT_QUALIFIED= 1 << 25;
/**
* Package Fragment Roots contain the project name if not an archive (appended).
* e.g. <code>src - MyProject</code>
*/
public final static int ROOT_POST_QUALIFIED= 1 << 26;
/**
* Add root path to all elements except Package Fragment Roots and Java projects.
* e.g. <code>java.lang.Vector - c:\java\lib\rt.jar</code>
* Option only applies to getElementLabel
*/
public final static int APPEND_ROOT_PATH= 1 << 27;
/**
* Add root path to all elements except Package Fragment Roots and Java projects.
* e.g. <code>java.lang.Vector - c:\java\lib\rt.jar</code>
* Option only applies to getElementLabel
*/
public final static int PREPEND_ROOT_PATH= 1 << 28;
/**
* Package names are compressed.
* e.g. <code>o*.e*.search</code>
*/
public final static int P_COMPRESSED= 1 << 29;
/**
* Qualify all elements
*/
public final static int ALL_FULLY_QUALIFIED= F_FULLY_QUALIFIED | M_FULLY_QUALIFIED | I_FULLY_QUALIFIED | T_FULLY_QUALIFIED | D_QUALIFIED | CF_QUALIFIED | CU_QUALIFIED | P_QUALIFIED | ROOT_QUALIFIED;
/**
* Post qualify all elements
*/
public final static int ALL_POST_QUALIFIED= F_POST_QUALIFIED | M_POST_QUALIFIED | I_POST_QUALIFIED | T_POST_QUALIFIED | D_POST_QUALIFIED | CF_POST_QUALIFIED | CU_POST_QUALIFIED | P_POST_QUALIFIED | ROOT_POST_QUALIFIED;
/**
* Default options (M_PARAMETER_TYPES enabled)
*/
public final static int ALL_DEFAULT= M_PARAMETER_TYPES;
/**
* Default qualify options (All except Root and Package)
*/
public final static int DEFAULT_QUALIFIED= F_FULLY_QUALIFIED | M_FULLY_QUALIFIED | I_FULLY_QUALIFIED | T_FULLY_QUALIFIED | D_QUALIFIED | CF_QUALIFIED | CU_QUALIFIED;
/**
* Default post qualify options (All except Root and Package)
*/
public final static int DEFAULT_POST_QUALIFIED= F_POST_QUALIFIED | M_POST_QUALIFIED | I_POST_QUALIFIED | T_POST_QUALIFIED | D_POST_QUALIFIED | CF_POST_QUALIFIED | CU_POST_QUALIFIED;
public final static String CONCAT_STRING= JavaUIMessages.getString("JavaElementLabels.concat_string"); // " - "; //$NON-NLS-1$
public final static String COMMA_STRING= JavaUIMessages.getString("JavaElementLabels.comma_string"); // ", "; //$NON-NLS-1$
public final static String DECL_STRING= JavaUIMessages.getString("JavaElementLabels.declseparator_string"); // " "; // use for return type //$NON-NLS-1$
/*
* Package name compression
*/
private static String fgPkgNamePattern= ""; //$NON-NLS-1$
private static String fgPkgNamePrefix;
private static String fgPkgNamePostfix;
private static int fgPkgNameChars;
private static int fgPkgNameLength;
private JavaElementLabels() {
}
private static boolean getFlag(int flags, int flag) {
return (flags & flag) != 0;
}
public static String getTextLabel(Object obj, int flags) {
if (obj instanceof IJavaElement) {
return getElementLabel((IJavaElement) obj, flags);
} else if (obj instanceof IAdaptable) {
IWorkbenchAdapter wbadapter= (IWorkbenchAdapter) ((IAdaptable)obj).getAdapter(IWorkbenchAdapter.class);
if (wbadapter != null) {
return wbadapter.getLabel(obj);
}
}
return ""; //$NON-NLS-1$
}
/**
* Returns the label for a Java element. Flags as defined above.
*/
public static String getElementLabel(IJavaElement element, int flags) {
StringBuffer buf= new StringBuffer(60);
getElementLabel(element, flags, buf);
return buf.toString();
}
/**
* Returns the label for a Java element. Flags as defined above.
*/
public static void getElementLabel(IJavaElement element, int flags, StringBuffer buf) {
int type= element.getElementType();
IPackageFragmentRoot root= null;
if (type != IJavaElement.JAVA_MODEL && type != IJavaElement.JAVA_PROJECT && type != IJavaElement.PACKAGE_FRAGMENT_ROOT)
root= JavaModelUtil.getPackageFragmentRoot(element);
if (root != null && getFlag(flags, PREPEND_ROOT_PATH)) {
getPackageFragmentRootLabel(root, ROOT_QUALIFIED, buf);
buf.append(CONCAT_STRING);
}
switch (type) {
case IJavaElement.METHOD:
getMethodLabel((IMethod) element, flags, buf);
break;
case IJavaElement.FIELD:
getFieldLabel((IField) element, flags, buf);
break;
case IJavaElement.INITIALIZER:
getInitializerLabel((IInitializer) element, flags, buf);
break;
case IJavaElement.TYPE:
getTypeLabel((IType) element, flags, buf);
break;
case IJavaElement.CLASS_FILE:
getClassFileLabel((IClassFile) element, flags, buf);
break;
case IJavaElement.COMPILATION_UNIT:
getCompilationUnitLabel((ICompilationUnit) element, flags, buf);
break;
case IJavaElement.PACKAGE_FRAGMENT:
getPackageFragmentLabel((IPackageFragment) element, flags, buf);
break;
case IJavaElement.PACKAGE_FRAGMENT_ROOT:
getPackageFragmentRootLabel((IPackageFragmentRoot) element, flags, buf);
break;
case IJavaElement.IMPORT_CONTAINER:
case IJavaElement.IMPORT_DECLARATION:
case IJavaElement.PACKAGE_DECLARATION:
getDeclararionLabel(element, flags, buf);
break;
case IJavaElement.JAVA_PROJECT:
case IJavaElement.JAVA_MODEL:
buf.append(element.getElementName());
break;
default:
buf.append(element.getElementName());
}
if (root != null && getFlag(flags, APPEND_ROOT_PATH)) {
buf.append(CONCAT_STRING);
getPackageFragmentRootLabel(root, ROOT_QUALIFIED, buf);
}
}
/**
* Appends the label for a method to a StringBuffer. Considers the M_* flags.
*/
public static void getMethodLabel(IMethod method, int flags, StringBuffer buf) {
try {
// return type
if (getFlag(flags, M_PRE_RETURNTYPE) && method.exists() && !method.isConstructor()) {
buf.append(Signature.getSimpleName(Signature.toString(method.getReturnType())));
buf.append(' ');
}
// qualification
if (getFlag(flags, M_FULLY_QUALIFIED)) {
getTypeLabel(method.getDeclaringType(), T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf);
buf.append('.');
}
buf.append(method.getElementName());
// parameters
if (getFlag(flags, M_PARAMETER_TYPES | M_PARAMETER_NAMES)) {
buf.append('(');
String[] types= getFlag(flags, M_PARAMETER_TYPES) ? method.getParameterTypes() : null;
String[] names= (getFlag(flags, M_PARAMETER_NAMES) && method.exists()) ? method.getParameterNames() : null;
int nParams= types != null ? types.length : names.length;
for (int i= 0; i < nParams; i++) {
if (i > 0) {
buf.append(COMMA_STRING); //$NON-NLS-1$
}
if (types != null) {
buf.append(Signature.getSimpleName(Signature.toString(types[i])));
}
if (names != null) {
if (types != null) {
buf.append(' ');
}
buf.append(names[i]);
}
}
buf.append(')');
}
if (getFlag(flags, M_EXCEPTIONS) && method.exists()) {
String[] types= method.getExceptionTypes();
if (types.length > 0) {
buf.append(" throws "); //$NON-NLS-1$
for (int i= 0; i < types.length; i++) {
if (i > 0) {
buf.append(COMMA_STRING);
}
buf.append(Signature.getSimpleName(Signature.toString(types[i])));
}
}
}
if (getFlag(flags, M_APP_RETURNTYPE) && method.exists() && !method.isConstructor()) {
buf.append(DECL_STRING);
buf.append(Signature.getSimpleName(Signature.toString(method.getReturnType())));
}
// post qualification
if (getFlag(flags, M_POST_QUALIFIED)) {
buf.append(CONCAT_STRING);
getTypeLabel(method.getDeclaringType(), T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf);
}
} catch (JavaModelException e) {
JavaPlugin.log(e); // NotExistsException will not reach this point
}
}
/**
* Appends the label for a field to a StringBuffer. Considers the F_* flags.
*/
public static void getFieldLabel(IField field, int flags, StringBuffer buf) {
try {
if (getFlag(flags, F_PRE_TYPE_SIGNATURE) && field.exists()) {
buf.append(Signature.toString(field.getTypeSignature()));
buf.append(' ');
}
// qualification
if (getFlag(flags, F_FULLY_QUALIFIED)) {
getTypeLabel(field.getDeclaringType(), T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf);
buf.append('.');
}
buf.append(field.getElementName());
if (getFlag(flags, F_APP_TYPE_SIGNATURE) && field.exists()) {
buf.append(DECL_STRING);
buf.append(Signature.toString(field.getTypeSignature()));
}
// post qualification
if (getFlag(flags, F_POST_QUALIFIED)) {
buf.append(CONCAT_STRING);
getTypeLabel(field.getDeclaringType(), T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf);
}
} catch (JavaModelException e) {
JavaPlugin.log(e); // NotExistsException will not reach this point
}
}
/**
* Appends the label for a initializer to a StringBuffer. Considers the I_* flags.
*/
public static void getInitializerLabel(IInitializer initializer, int flags, StringBuffer buf) {
// qualification
if (getFlag(flags, I_FULLY_QUALIFIED)) {
getTypeLabel(initializer.getDeclaringType(), T_FULLY_QUALIFIED | (flags ^ P_COMPRESSED), buf);
buf.append('.');
}
buf.append(JavaUIMessages.getString("JavaElementLabels.initializer")); //$NON-NLS-1$
// post qualification
if (getFlag(flags, I_POST_QUALIFIED)) {
buf.append(CONCAT_STRING);
getTypeLabel(initializer.getDeclaringType(), T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf);
}
}
/**
* Appends the label for a type to a StringBuffer. Considers the T_* flags.
*/
public static void getTypeLabel(IType type, int flags, StringBuffer buf) {
if (getFlag(flags, T_FULLY_QUALIFIED)) {
IPackageFragment pack= type.getPackageFragment();
if (!pack.isDefaultPackage()) {
getPackageFragmentLabel(pack, (flags & P_COMPRESSED), buf);
buf.append('.');
}
buf.append(JavaModelUtil.getTypeQualifiedName(type));
} else if (getFlag(flags, T_CONTAINER_QUALIFIED)) {
buf.append(JavaModelUtil.getTypeQualifiedName(type));
} else {
buf.append(type.getElementName());
}
// post qualification
if (getFlag(flags, T_POST_QUALIFIED)) {
buf.append(CONCAT_STRING);
IType declaringType= type.getDeclaringType();
if (declaringType != null) {
getTypeLabel(declaringType, T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf);
} else {
getPackageFragmentLabel(type.getPackageFragment(), (flags & P_COMPRESSED), buf);
}
}
}
/**
* Appends the label for a declaration to a StringBuffer. Considers the D_* flags.
*/
public static void getDeclararionLabel(IJavaElement declaration, int flags, StringBuffer buf) {
if (getFlag(flags, D_QUALIFIED)) {
IJavaElement openable= (IJavaElement) declaration.getOpenable();
if (openable != null) {
buf.append(getElementLabel(openable, CF_QUALIFIED | CU_QUALIFIED));
buf.append('/');
}
}
if (declaration.getElementType() == IJavaElement.IMPORT_CONTAINER) {
buf.append(JavaUIMessages.getString("JavaElementLabels.import_container")); //$NON-NLS-1$
} else {
buf.append(declaration.getElementName());
}
// post qualification
if (getFlag(flags, D_POST_QUALIFIED)) {
IJavaElement openable= (IJavaElement) declaration.getOpenable();
if (openable != null) {
buf.append(CONCAT_STRING);
buf.append(getElementLabel(openable, CF_QUALIFIED | CU_QUALIFIED));
}
}
}
/**
* Appends the label for a class file to a StringBuffer. Considers the CF_* flags.
*/
public static void getClassFileLabel(IClassFile classFile, int flags, StringBuffer buf) {
if (getFlag(flags, CF_QUALIFIED)) {
IPackageFragment pack= (IPackageFragment) classFile.getParent();
if (!pack.isDefaultPackage()) {
buf.append(pack.getElementName());
buf.append('.');
}
}
buf.append(classFile.getElementName());
if (getFlag(flags, CF_POST_QUALIFIED)) {
buf.append(CONCAT_STRING);
getPackageFragmentLabel((IPackageFragment) classFile.getParent(), 0, buf);
}
}
/**
* Appends the label for a compilation unit to a StringBuffer. Considers the CU_* flags.
*/
public static void getCompilationUnitLabel(ICompilationUnit cu, int flags, StringBuffer buf) {
if (getFlag(flags, CU_QUALIFIED)) {
IPackageFragment pack= (IPackageFragment) cu.getParent();
if (!pack.isDefaultPackage()) {
buf.append(pack.getElementName());
buf.append('.');
}
}
buf.append(cu.getElementName());
if (getFlag(flags, CU_POST_QUALIFIED)) {
buf.append(CONCAT_STRING);
getPackageFragmentLabel((IPackageFragment) cu.getParent(), 0, buf);
}
}
/**
* Appends the label for a package fragment to a StringBuffer. Considers the P_* flags.
*/
public static void getPackageFragmentLabel(IPackageFragment pack, int flags, StringBuffer buf) {
if (getFlag(flags, P_QUALIFIED)) {
getPackageFragmentRootLabel((IPackageFragmentRoot) pack.getParent(), ROOT_QUALIFIED, buf);
buf.append('/');
}
refreshPackageNamePattern();
if (pack.isDefaultPackage()) {
buf.append(JavaUIMessages.getString("JavaElementLabels.default_package")); //$NON-NLS-1$
} else if (getFlag(flags, P_COMPRESSED) && fgPkgNameLength >= 0) {
String name= pack.getElementName();
int start= 0;
int dot= name.indexOf('.', start);
while (dot > 0) {
if (dot - start > fgPkgNameLength-1) {
buf.append(fgPkgNamePrefix);
if (fgPkgNameChars > 0)
buf.append(name.substring(start, Math.min(start+ fgPkgNameChars, dot)));
buf.append(fgPkgNamePostfix);
} else
buf.append(name.substring(start, dot + 1));
start= dot + 1;
dot= name.indexOf('.', start);
}
buf.append(name.substring(start));
} else {
buf.append(pack.getElementName());
}
if (getFlag(flags, P_POST_QUALIFIED)) {
buf.append(CONCAT_STRING);
getPackageFragmentRootLabel((IPackageFragmentRoot) pack.getParent(), ROOT_QUALIFIED, buf);
}
}
/**
* Appends the label for a package fragment root to a StringBuffer. Considers the ROOT_* flags.
*/
public static void getPackageFragmentRootLabel(IPackageFragmentRoot root, int flags, StringBuffer buf) {
boolean varNamePrepended= false;
if (root.isArchive() && getFlag(flags, ROOT_VARIABLE)) {
try {
IClasspathEntry rawEntry= root.getRawClasspathEntry();
if (rawEntry != null) {
if (rawEntry.getEntryKind() == IClasspathEntry.CPE_VARIABLE) {
buf.append(rawEntry.getPath().makeRelative());
buf.append(CONCAT_STRING);
varNamePrepended= true;
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e); // problems with class path
}
}
if (root.isExternal()) {
IPath path= root.getPath();
int segements= path.segmentCount();
if (segements > 0 && !varNamePrepended) {
buf.append(path.segment(segements - 1));
if (segements > 1 || path.getDevice() != null) {
buf.append(CONCAT_STRING);
buf.append(path.removeLastSegments(1).toOSString());
}
} else {
buf.append(path.toOSString());
}
} else {
if (getFlag(flags, ROOT_QUALIFIED)) {
buf.append(root.getPath().makeRelative().toString());
} else {
buf.append(root.getElementName());
}
if (getFlag(flags, ROOT_POST_QUALIFIED)) {
buf.append(CONCAT_STRING);
buf.append(root.getParent().getElementName());
}
}
}
private static void refreshPackageNamePattern() {
String pattern= getPkgNamePatternForPackagesView();
if (pattern.equals(fgPkgNamePattern))
return;
else if (pattern.equals("")) { //$NON-NLS-1$
fgPkgNamePattern= ""; //$NON-NLS-1$
fgPkgNameLength= -1;
return;
}
fgPkgNamePattern= pattern;
int i= 0;
fgPkgNameChars= 0;
fgPkgNamePrefix= ""; //$NON-NLS-1$
fgPkgNamePostfix= ""; //$NON-NLS-1$
while (i < pattern.length()) {
char ch= pattern.charAt(i);
if (Character.isDigit(ch)) {
fgPkgNameChars= ch-48;
if (i > 0)
fgPkgNamePrefix= pattern.substring(0, i);
if (i >= 0)
fgPkgNamePostfix= pattern.substring(i+1);
fgPkgNameLength= fgPkgNamePrefix.length() + fgPkgNameChars + fgPkgNamePostfix.length();
return;
}
i++;
}
fgPkgNamePrefix= pattern;
fgPkgNameLength= pattern.length();
}
private static String getPkgNamePatternForPackagesView() {
IPreferenceStore store= PreferenceConstants.getPreferenceStore();
if (!store.getBoolean(PreferenceConstants.APPEARANCE_COMPRESS_PACKAGE_NAMES))
return ""; //$NON-NLS-1$
return store.getString(PreferenceConstants.APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW);
}
}
|
29,170 |
Bug 29170 False error feedback from "Show in package explorer"
|
Build 20030107 1. Open a .java file in the Java editor. 2. Click "Collapse All" in the packages view to collapse the tree. 3. Right click on the top-level type in the Outline view and choose "Show in Package Explorer" 4. The packages view correctly expands to the selected type, but an error dialog pops up: Title: "Show in Package Explorer" Message: "Couldn't reveal the selected element in Package Explorer. May be the element is filtered out." This happens any time the tree needs to be expanded to reveal a type.
|
resolved fixed
|
75ceea6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-14T08:05:09Z | 2003-01-08T21:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/packageview/PackageExplorerPart.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial implementation
******************************************************************************/
package org.eclipse.jdt.internal.ui.packageview;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.runtime.IPath;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.DragSourceEvent;
import org.eclipse.swt.dnd.FileTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.ScrollBar;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.preference.IPreferenceStore;
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.ILabelDecorator;
import org.eclipse.jface.viewers.IOpenListener;
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.ITreeContentProvider;
import org.eclipse.jface.viewers.ITreeViewerListener;
import org.eclipse.jface.viewers.OpenEvent;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeExpansionEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchPartSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.part.ISetSelectionTarget;
import org.eclipse.ui.part.ResourceTransfer;
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.IJavaModel;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.IPackagesViewPart;
import org.eclipse.jdt.ui.JavaElementSorter;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.StandardJavaElementContentProvider;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.dnd.DelegatingDragAdapter;
import org.eclipse.jdt.internal.ui.dnd.DelegatingDropAdapter;
import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer;
import org.eclipse.jdt.internal.ui.dnd.ResourceTransferDragAdapter;
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.javaeditor.IClassFileEditorInput;
import org.eclipse.jdt.internal.ui.javaeditor.JarEntryEditorInput;
import org.eclipse.jdt.internal.ui.util.JavaUIHelp;
import org.eclipse.jdt.internal.ui.viewsupport.AppearanceAwareLabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.DecoratingJavaLabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
import org.eclipse.jdt.internal.ui.viewsupport.ProblemTreeViewer;
import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater;
/**
* The ViewPart for the ProjectExplorer. It listens to part activation events.
* When selection linking with the editor is enabled the view selection tracks
* the active editor page. Similarly when a resource is selected in the packages
* view the corresponding editor is activated.
*/
public class PackageExplorerPart extends ViewPart implements ISetSelectionTarget, IMenuListener, IPackagesViewPart, IPropertyChangeListener, IViewPartInputProvider {
private boolean fIsCurrentLayoutFlat; // true means flat, false means hierachical
private static final int HIERARCHICAL_LAYOUT= 0x1;
private static final int FLAT_LAYOUT= 0x2;
public final static String VIEW_ID= JavaUI.ID_PACKAGES;
// Persistance tags.
static final String TAG_SELECTION= "selection"; //$NON-NLS-1$
static final String TAG_EXPANDED= "expanded"; //$NON-NLS-1$
static final String TAG_ELEMENT= "element"; //$NON-NLS-1$
static final String TAG_PATH= "path"; //$NON-NLS-1$
static final String TAG_VERTICAL_POSITION= "verticalPosition"; //$NON-NLS-1$
static final String TAG_HORIZONTAL_POSITION= "horizontalPosition"; //$NON-NLS-1$
static final String TAG_FILTERS = "filters"; //$NON-NLS-1$
static final String TAG_FILTER = "filter"; //$NON-NLS-1$
static final String TAG_LAYOUT= "layout"; //$NON-NLS-1$
private PackageExplorerContentProvider fContentProvider;
private PackageExplorerActionGroup fActionSet;
private ProblemTreeViewer fViewer;
private Menu fContextMenu;
private IMemento fMemento;
private ISelectionChangedListener fSelectionListener;
private String fWorkingSetName;
private IPartListener fPartListener= new IPartListener() {
public void partActivated(IWorkbenchPart part) {
if (part instanceof IEditorPart)
editorActivated((IEditorPart) part);
}
public void partBroughtToTop(IWorkbenchPart part) {
}
public void partClosed(IWorkbenchPart part) {
}
public void partDeactivated(IWorkbenchPart part) {
}
public void partOpened(IWorkbenchPart part) {
}
};
private ITreeViewerListener fExpansionListener= new ITreeViewerListener() {
public void treeCollapsed(TreeExpansionEvent event) {
}
public void treeExpanded(TreeExpansionEvent event) {
Object element= event.getElement();
if (element instanceof ICompilationUnit ||
element instanceof IClassFile)
expandMainType(element);
}
};
private PackageExplorerLabelProvider fLabelProvider;
/* (non-Javadoc)
* Method declared on IViewPart.
*/
public void init(IViewSite site, IMemento memento) throws PartInitException {
super.init(site, memento);
fMemento= memento;
restoreLayoutState(memento);
}
private void restoreLayoutState(IMemento memento) {
Integer state= null;
if (memento != null)
state= memento.getInteger(TAG_LAYOUT);
// If no memento try an restore from preference store
if(state == null) {
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
state= new Integer(store.getInt(TAG_LAYOUT));
}
if (state.intValue() == FLAT_LAYOUT)
fIsCurrentLayoutFlat= true;
else if (state.intValue() == HIERARCHICAL_LAYOUT)
fIsCurrentLayoutFlat= false;
else
fIsCurrentLayoutFlat= true;
}
/**
* Returns the package explorer part of the active perspective. If
* there isn't any package explorer part <code>null</code> is returned.
*/
public static PackageExplorerPart getFromActivePerspective() {
IViewPart view= JavaPlugin.getActivePage().findView(VIEW_ID);
if (view instanceof PackageExplorerPart)
return (PackageExplorerPart)view;
return null;
}
/**
* Makes the package explorer part visible in the active perspective. If there
* isn't a package explorer part registered <code>null</code> is returned.
* Otherwise the opened view part is returned.
*/
public static PackageExplorerPart openInActivePerspective() {
try {
return (PackageExplorerPart)JavaPlugin.getActivePage().showView(VIEW_ID);
} catch(PartInitException pe) {
return null;
}
}
public void dispose() {
if (fContextMenu != null && !fContextMenu.isDisposed())
fContextMenu.dispose();
getSite().getPage().removePartListener(fPartListener);
JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(this);
if (fViewer != null)
fViewer.removeTreeListener(fExpansionListener);
if (fActionSet != null)
fActionSet.dispose();
super.dispose();
}
/**
* Implementation of IWorkbenchPart.createPartControl(Composite)
*/
public void createPartControl(Composite parent) {
fViewer= createViewer(parent);
fViewer.setUseHashlookup(true);
setProviders();
JavaPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(this);
MenuManager menuMgr= new MenuManager("#PopupMenu"); //$NON-NLS-1$
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(this);
fContextMenu= menuMgr.createContextMenu(fViewer.getTree());
fViewer.getTree().setMenu(fContextMenu);
// Register viewer with site. This must be done before making the actions.
IWorkbenchPartSite site= getSite();
site.registerContextMenu(menuMgr, fViewer);
site.setSelectionProvider(fViewer);
site.getPage().addPartListener(fPartListener);
makeActions(); // call before registering for selection changes
// Set input after filter and sorter has been set. This avoids resorting and refiltering.
restoreFilterAndSorter();
fViewer.setInput(findInputElement());
initDragAndDrop();
initKeyListener();
fSelectionListener= new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
handleSelectionChanged(event);
}
};
fViewer.addSelectionChangedListener(fSelectionListener);
fViewer.addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
fActionSet.handleDoubleClick(event);
}
});
fViewer.addOpenListener(new IOpenListener() {
public void open(OpenEvent event) {
fActionSet.handleOpen(event);
}
});
IStatusLineManager slManager= getViewSite().getActionBars().getStatusLineManager();
fViewer.addSelectionChangedListener(new StatusBarUpdater(slManager));
fViewer.addTreeListener(fExpansionListener);
if (fMemento != null)
restoreUIState(fMemento);
fMemento= null;
// Set help for the view
JavaUIHelp.setHelp(fViewer, IJavaHelpContextIds.PACKAGES_VIEW);
fillActionBars();
updateTitle();
}
/**
* This viewer ensures that non-leaves in the hierarchical
* layout are not removed by any filters.
*
* @since 2.1
*/
private ProblemTreeViewer createViewer(Composite parent) {
return new ProblemTreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL) {
/*
* @see org.eclipse.jface.viewers.StructuredViewer#filter(java.lang.Object)
*/
protected Object[] getFilteredChildren(Object parent) {
List list = new ArrayList();
ViewerFilter[] filters = fViewer.getFilters();
Object[] children = ((ITreeContentProvider) fViewer.getContentProvider()).getChildren(parent);
for (int i = 0; i < children.length; i++) {
Object object = children[i];
if (!isEssential(object)) {
object = filter(object, parent, filters);
if (object != null) {
list.add(object);
}
} else
list.add(object);
}
return list.toArray();
}
// Sends the object through the given filters
private Object filter(Object object, Object parent, ViewerFilter[] filters) {
for (int i = 0; i < filters.length; i++) {
ViewerFilter filter = filters[i];
if (!filter.select(fViewer, parent, object))
return null;
}
return object;
}
/* Checks if a filtered object in essential (ie. is a parent that
* should not be removed).
*/
private boolean isEssential(Object object) {
try {
if (!isFlatLayout() && object instanceof IPackageFragment) {
IPackageFragment fragment = (IPackageFragment) object;
return !fragment.isDefaultPackage() && fragment.hasSubpackages();
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
return false;
}
};
}
/**
* Answers whether this part shows the packages flat or hierarchical.
*
* @since 2.1
*/
boolean isFlatLayout() {
return fIsCurrentLayoutFlat;
}
private void setProviders() {
//content provider must be set before the label provider
fContentProvider= createContentProvider();
fContentProvider.setIsFlatLayout(fIsCurrentLayoutFlat);
fViewer.setContentProvider(fContentProvider);
fLabelProvider= createLabelProvider();
fLabelProvider.setIsFlatLayout(fIsCurrentLayoutFlat);
fViewer.setLabelProvider(new DecoratingJavaLabelProvider(fLabelProvider, false, false));
// problem decoration provided by PackageLabelProvider
}
void toggleLayout() {
// Update current state and inform content and label providers
fIsCurrentLayoutFlat= !fIsCurrentLayoutFlat;
saveLayoutState(null);
fContentProvider.setIsFlatLayout(isFlatLayout());
fLabelProvider.setIsFlatLayout(isFlatLayout());
fViewer.getControl().setRedraw(false);
fViewer.refresh();
fViewer.getControl().setRedraw(true);
}
/**
* This method should only be called inside this class
* and from test cases.
*/
public PackageExplorerContentProvider createContentProvider() {
IPreferenceStore store= PreferenceConstants.getPreferenceStore();
boolean showCUChildren= store.getBoolean(PreferenceConstants.SHOW_CU_CHILDREN);
boolean reconcile= PreferenceConstants.UPDATE_WHILE_EDITING.equals(store.getString(PreferenceConstants.UPDATE_JAVA_VIEWS));
return new PackageExplorerContentProvider(showCUChildren, reconcile);
}
private PackageExplorerLabelProvider createLabelProvider() {
return new PackageExplorerLabelProvider(AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS | JavaElementLabels.P_COMPRESSED,
AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS | JavaElementImageProvider.SMALL_ICONS,
fContentProvider);
}
private void fillActionBars() {
IActionBars actionBars= getViewSite().getActionBars();
fActionSet.fillActionBars(actionBars);
}
private Object findInputElement() {
Object input= getSite().getPage().getInput();
if (input instanceof IWorkspace) {
return JavaCore.create(((IWorkspace)input).getRoot());
} else if (input instanceof IContainer) {
return JavaCore.create((IContainer)input);
}
//1GERPRT: ITPJUI:ALL - Packages View is empty when shown in Type Hierarchy Perspective
// we can't handle the input
// fall back to show the workspace
return JavaCore.create(JavaPlugin.getWorkspace().getRoot());
}
/**
* Answer the property defined by key.
*/
public Object getAdapter(Class key) {
if (key.equals(ISelectionProvider.class))
return fViewer;
return super.getAdapter(key);
}
/**
* Returns the tool tip text for the given element.
*/
String getToolTipText(Object element) {
String result;
if (!(element instanceof IResource)) {
result= JavaElementLabels.getTextLabel(element, AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS);
} else {
IPath path= ((IResource) element).getFullPath();
if (path.isRoot()) {
result= PackagesMessages.getString("PackageExplorer.title"); //$NON-NLS-1$
} else {
result= path.makeRelative().toString();
}
}
if (fWorkingSetName == null)
return result;
String wsstr= PackagesMessages.getFormattedString("PackageExplorer.toolTip", new String[] { fWorkingSetName }); //$NON-NLS-1$
if (result.length() == 0)
return wsstr;
return PackagesMessages.getFormattedString("PackageExplorer.toolTip2", new String[] { result, fWorkingSetName }); //$NON-NLS-1$
}
public String getTitleToolTip() {
if (fViewer == null)
return super.getTitleToolTip();
return getToolTipText(fViewer.getInput());
}
/**
* @see IWorkbenchPart#setFocus()
*/
public void setFocus() {
fViewer.getTree().setFocus();
}
/**
* Returns the shell to use for opening dialogs.
* Used in this class, and in the actions.
*/
private Shell getShell() {
return fViewer.getTree().getShell();
}
/**
* Returns the selection provider.
*/
private ISelectionProvider getSelectionProvider() {
return fViewer;
}
/**
* Returns the current selection.
*/
private ISelection getSelection() {
return fViewer.getSelection();
}
//---- Action handling ----------------------------------------------------------
/**
* Called when the context menu is about to open. Override
* to add your own context dependent menu contributions.
*/
public void menuAboutToShow(IMenuManager menu) {
JavaPlugin.createStandardGroups(menu);
fActionSet.setContext(new ActionContext(getSelection()));
fActionSet.fillContextMenu(menu);
fActionSet.setContext(null);
}
private void makeActions() {
fActionSet= new PackageExplorerActionGroup(this);
}
private boolean isSelectionOfType(ISelection s, Class clazz, boolean considerUnderlyingResource) {
if (! (s instanceof IStructuredSelection) || s.isEmpty())
return false;
IStructuredSelection selection= (IStructuredSelection)s;
Iterator iter= selection.iterator();
while (iter.hasNext()) {
Object o= iter.next();
if (clazz.isInstance(o))
return true;
if (considerUnderlyingResource) {
if (! (o instanceof IJavaElement))
return false;
IJavaElement element= (IJavaElement)o;
Object resource= element.getAdapter(IResource.class);
if (! clazz.isInstance(resource))
return false;
}
}
return true;
}
//---- Event handling ----------------------------------------------------------
private void initDragAndDrop() {
int ops= DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK;
Transfer[] transfers= new Transfer[] {
LocalSelectionTransfer.getInstance(),
ResourceTransfer.getInstance(),
FileTransfer.getInstance()};
// Drop Adapter
TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] {
new SelectionTransferDropAdapter(fViewer),
new FileTransferDropAdapter(fViewer)
};
fViewer.addDropSupport(ops | DND.DROP_DEFAULT, transfers, new DelegatingDropAdapter(dropListeners));
// Drag Adapter
Control control= fViewer.getControl();
TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] {
new SelectionTransferDragAdapter(fViewer),
new ResourceTransferDragAdapter(fViewer),
new FileTransferDragAdapter(fViewer)
};
DragSource source= new DragSource(control, ops);
// Note, that the transfer agents are set by the delegating drag adapter itself.
source.addDragListener(new DelegatingDragAdapter(dragListeners) {
public void dragStart(DragSourceEvent event) {
IStructuredSelection selection= (IStructuredSelection)getSelection();
for (Iterator iter= selection.iterator(); iter.hasNext(); ) {
if (iter.next() instanceof IMember) {
setPossibleListeners(new TransferDragSourceListener[] {new SelectionTransferDragAdapter(fViewer)});
break;
}
}
super.dragStart(event);
}
});
}
/**
* Handles selection changed in viewer.
* Updates global actions.
* Links to editor (if option enabled)
*/
private void handleSelectionChanged(SelectionChangedEvent event) {
IStructuredSelection selection= (IStructuredSelection) event.getSelection();
fActionSet.handleSelectionChanged(event);
// if (OpenStrategy.getOpenMethod() != OpenStrategy.SINGLE_CLICK)
linkToEditor(selection);
}
public void selectReveal(final ISelection selection) {
// HACK: second async is required to ensure that
// viewer has processed the addition.
Display d= getSite().getShell().getDisplay();
Runnable r= new Runnable() {
public void run() {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
final ISelection javaSelection= convertSelection(selection);
fViewer.setSelection(javaSelection, true);
if (javaSelection != selection && !javaSelection.equals(fViewer.getSelection()))
fViewer.setSelection(selection);
}
}
};
d.asyncExec(r);
}
private ISelection convertSelection(ISelection s) {
if (!(s instanceof IStructuredSelection))
return s;
Object[] elements= ((StructuredSelection)s).toArray();
if (!containsResources(elements))
return s;
for (int i= 0; i < elements.length; i++) {
Object o= elements[i];
if (o instanceof IResource) {
IJavaElement jElement= JavaCore.create((IResource)o);
if (jElement != null)
elements[i]= jElement;
}
}
return new StructuredSelection(elements);
}
private boolean containsResources(Object[] elements) {
for (int i = 0; i < elements.length; i++) {
if (elements[i] instanceof IResource)
return true;
}
return false;
}
public void selectAndReveal(Object element) {
selectReveal(new StructuredSelection(element));
}
/**
* Returns whether the preference to link selection to active editor is enabled.
*/
boolean isLinkingEnabled() {
return PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.LINK_PACKAGES_TO_EDITOR);
}
/**
* Links to editor (if option enabled)
*/
private void linkToEditor(IStructuredSelection selection) {
// ignore selection changes if the package explorer is not the active part.
// In this case the selection change isn't triggered by a user.
if (!isActivePart())
return;
Object obj= selection.getFirstElement();
if (selection.size() == 1) {
IEditorPart part= EditorUtility.isOpenInEditor(obj);
if (part != null) {
IWorkbenchPage page= getSite().getPage();
page.bringToTop(part);
if (obj instanceof IJavaElement)
EditorUtility.revealInEditor(part, (IJavaElement) obj);
}
}
}
private boolean isActivePart() {
return this == getSite().getPage().getActivePart();
}
public void saveState(IMemento memento) {
if (fViewer == null) {
// part has not been created
if (fMemento != null) //Keep the old state;
memento.putMemento(fMemento);
return;
}
saveExpansionState(memento);
saveSelectionState(memento);
saveLayoutState(memento);
// commented out because of http://bugs.eclipse.org/bugs/show_bug.cgi?id=4676
//saveScrollState(memento, fViewer.getTree());
fActionSet.saveFilterAndSorterState(memento);
}
/**
* Saves the current layout state.
*
* @param memento the memento to save the state into or
* <code>null</code> to store the state in the preferences
* @since 2.1
*/
private void saveLayoutState(IMemento memento) {
if (memento != null) {
memento.putInteger(TAG_LAYOUT, getLayoutAsInt());
} else {
//if memento is null save in preference store
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
store.setValue(TAG_LAYOUT, getLayoutAsInt());
}
}
private int getLayoutAsInt() {
if (fIsCurrentLayoutFlat)
return FLAT_LAYOUT;
else
return HIERARCHICAL_LAYOUT;
}
protected void saveScrollState(IMemento memento, Tree tree) {
ScrollBar bar= tree.getVerticalBar();
int position= bar != null ? bar.getSelection() : 0;
memento.putString(TAG_VERTICAL_POSITION, String.valueOf(position));
//save horizontal position
bar= tree.getHorizontalBar();
position= bar != null ? bar.getSelection() : 0;
memento.putString(TAG_HORIZONTAL_POSITION, String.valueOf(position));
}
protected void saveSelectionState(IMemento memento) {
Object elements[]= ((IStructuredSelection) fViewer.getSelection()).toArray();
if (elements.length > 0) {
IMemento selectionMem= memento.createChild(TAG_SELECTION);
for (int i= 0; i < elements.length; i++) {
IMemento elementMem= selectionMem.createChild(TAG_ELEMENT);
// we can only persist JavaElements for now
Object o= elements[i];
if (o instanceof IJavaElement)
elementMem.putString(TAG_PATH, ((IJavaElement) elements[i]).getHandleIdentifier());
}
}
}
protected void saveExpansionState(IMemento memento) {
Object expandedElements[]= fViewer.getVisibleExpandedElements();
if (expandedElements.length > 0) {
IMemento expandedMem= memento.createChild(TAG_EXPANDED);
for (int i= 0; i < expandedElements.length; i++) {
IMemento elementMem= expandedMem.createChild(TAG_ELEMENT);
// we can only persist JavaElements for now
Object o= expandedElements[i];
if (o instanceof IJavaElement)
elementMem.putString(TAG_PATH, ((IJavaElement) expandedElements[i]).getHandleIdentifier());
}
}
}
private void restoreFilterAndSorter() {
fViewer.setSorter(new JavaElementSorter());
if (fMemento != null)
fActionSet.restoreFilterAndSorterState(fMemento);
}
private void restoreUIState(IMemento memento) {
restoreExpansionState(memento);
restoreSelectionState(memento);
// commented out because of http://bugs.eclipse.org/bugs/show_bug.cgi?id=4676
//restoreScrollState(memento, fViewer.getTree());
}
protected void restoreScrollState(IMemento memento, Tree tree) {
ScrollBar bar= tree.getVerticalBar();
if (bar != null) {
try {
String posStr= memento.getString(TAG_VERTICAL_POSITION);
int position;
position= new Integer(posStr).intValue();
bar.setSelection(position);
} catch (NumberFormatException e) {
// ignore, don't set scrollposition
}
}
bar= tree.getHorizontalBar();
if (bar != null) {
try {
String posStr= memento.getString(TAG_HORIZONTAL_POSITION);
int position;
position= new Integer(posStr).intValue();
bar.setSelection(position);
} catch (NumberFormatException e) {
// ignore don't set scroll position
}
}
}
protected void restoreSelectionState(IMemento memento) {
IMemento childMem;
childMem= memento.getChild(TAG_SELECTION);
if (childMem != null) {
ArrayList list= new ArrayList();
IMemento[] elementMem= childMem.getChildren(TAG_ELEMENT);
for (int i= 0; i < elementMem.length; i++) {
Object element= JavaCore.create(elementMem[i].getString(TAG_PATH));
if (element != null)
list.add(element);
}
fViewer.setSelection(new StructuredSelection(list));
}
}
protected void restoreExpansionState(IMemento memento) {
IMemento childMem= memento.getChild(TAG_EXPANDED);
if (childMem != null) {
ArrayList elements= new ArrayList();
IMemento[] elementMem= childMem.getChildren(TAG_ELEMENT);
for (int i= 0; i < elementMem.length; i++) {
Object element= JavaCore.create(elementMem[i].getString(TAG_PATH));
if (element != null)
elements.add(element);
}
fViewer.setExpandedElements(elements.toArray());
}
}
/**
* Create the KeyListener for doing the refresh on the viewer.
*/
private void initKeyListener() {
fViewer.getControl().addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent event) {
fActionSet.handleKeyEvent(event);
}
});
}
/**
* An editor has been activated. Set the selection in this Packages Viewer
* to be the editor's input, if linking is enabled.
*/
void editorActivated(IEditorPart editor) {
if (!isLinkingEnabled())
return;
Object input= getElementOfInput(editor.getEditorInput());
Object element= null;
if (input instanceof IFile)
element= JavaCore.create((IFile)input);
if (element == null) // try a non Java resource
element= input;
if (element != null) {
// if the current selection is a child of the new
// selection then ignore it.
IStructuredSelection oldSelection= (IStructuredSelection)getSelection();
if (oldSelection.size() == 1) {
Object o= oldSelection.getFirstElement();
if (o instanceof IJavaElement) {
ICompilationUnit cu= (ICompilationUnit)((IJavaElement)o).getAncestor(IJavaElement.COMPILATION_UNIT);
if (cu != null) {
if (cu.isWorkingCopy())
cu= (ICompilationUnit)cu.getOriginalElement();
if ( element.equals(cu))
return;
}
IClassFile cf= (IClassFile)((IJavaElement)o).getAncestor(IJavaElement.CLASS_FILE);
if (cf != null && element.equals(cf))
return;
}
}
ISelection newSelection= new StructuredSelection(element);
if (!fViewer.getSelection().equals(newSelection)) {
try {
fViewer.removeSelectionChangedListener(fSelectionListener);
fViewer.setSelection(newSelection);
while (element != null && fViewer.getSelection().isEmpty()) {
// Try to select parent in case element is filtered
element= getParent(element);
if (element != null) {
newSelection= new StructuredSelection(element);
fViewer.setSelection(newSelection);
}
}
} finally {
fViewer.addSelectionChangedListener(fSelectionListener);
}
}
}
}
/**
* Returns the element's parent.
*
* @return the parent or <code>null</code> if there's no parent
*/
private Object getParent(Object element) {
if (element instanceof IJavaElement)
return ((IJavaElement)element).getParent();
else if (element instanceof IResource)
return ((IResource)element).getParent();
// else if (element instanceof IStorage) {
// can't get parent - see bug 22376
// }
return null;
}
/**
* A compilation unit or class was expanded, expand
* the main type.
*/
void expandMainType(Object element) {
try {
IType type= null;
if (element instanceof ICompilationUnit) {
ICompilationUnit cu= (ICompilationUnit)element;
IType[] types= cu.getTypes();
if (types.length > 0)
type= types[0];
}
else if (element instanceof IClassFile) {
IClassFile cf= (IClassFile)element;
type= cf.getType();
}
if (type != null) {
final IType type2= type;
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
ctrl.getDisplay().asyncExec(new Runnable() {
public void run() {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed())
fViewer.expandToLevel(type2, 1);
}
});
}
}
} catch(JavaModelException e) {
// no reveal
}
}
/**
* Returns the element contained in the EditorInput
*/
Object getElementOfInput(IEditorInput input) {
if (input instanceof IClassFileEditorInput)
return ((IClassFileEditorInput)input).getClassFile();
else if (input instanceof IFileEditorInput)
return ((IFileEditorInput)input).getFile();
else if (input instanceof JarEntryEditorInput)
return ((JarEntryEditorInput)input).getStorage();
return null;
}
/**
* Returns the Viewer.
*/
TreeViewer getViewer() {
return fViewer;
}
/**
* Returns the TreeViewer.
*/
public TreeViewer getTreeViewer() {
return fViewer;
}
boolean isExpandable(Object element) {
if (fViewer == null)
return false;
return fViewer.isExpandable(element);
}
void setWorkingSetName(String workingSetName) {
fWorkingSetName= workingSetName;
}
/**
* Updates the title text and title tool tip.
* Called whenever the input of the viewer changes.
*/
void updateTitle() {
Object input= fViewer.getInput();
String viewName= getConfigurationElement().getAttribute("name"); //$NON-NLS-1$
if (input == null
|| (input instanceof IJavaModel)) {
setTitle(viewName);
setTitleToolTip(""); //$NON-NLS-1$
} else {
String inputText= JavaElementLabels.getTextLabel(input, AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS);
String title= PackagesMessages.getFormattedString("PackageExplorer.argTitle", new String[] { viewName, inputText }); //$NON-NLS-1$
setTitle(title);
setTitleToolTip(getToolTipText(input));
}
}
/**
* Sets the decorator for the package explorer.
*
* @param decorator a label decorator or <code>null</code> for no decorations.
* @deprecated To be removed
*/
public void setLabelDecorator(ILabelDecorator decorator) {
}
/*
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
if (fViewer == null)
return;
boolean refreshViewer= false;
if (PreferenceConstants.SHOW_CU_CHILDREN.equals(event.getProperty())) {
IActionBars actionBars= getViewSite().getActionBars();
fActionSet.fillToolBar(actionBars.getToolBarManager());
actionBars.updateActionBars();
boolean showCUChildren= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.SHOW_CU_CHILDREN);
((StandardJavaElementContentProvider)fViewer.getContentProvider()).setProvideMembers(showCUChildren);
refreshViewer= true;
} else if (PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER.equals(event.getProperty())) {
refreshViewer= true;
}
if (refreshViewer)
fViewer.refresh();
}
/* (non-Javadoc)
* @see IViewPartInputProvider#getViewPartInput()
*/
public Object getViewPartInput() {
if (fViewer != null) {
return fViewer.getInput();
}
return null;
}
public void collapseAll() {
fViewer.getControl().setRedraw(false);
fViewer.collapseToLevel(getViewPartInput(), TreeViewer.ALL_LEVELS);
fViewer.getControl().setRedraw(true);
}
public PackageExplorerPart() {
}
}
|
29,405 |
Bug 29405 NPE in SearchUtil.isBinaryPrimitive [search]
|
20030107 Sorry, unsure of steps to reproduce but thought may be interesting none the less. java.lang.NullPointerException at org.eclipse.jdt.internal.ui.search.SearchUtil.isBinaryPrimitveConstantOrString (SearchUtil.java:429) at org.eclipse.jdt.internal.ui.search.SearchUtil.warnIfBinaryConstant (SearchUtil.java:416) at org.eclipse.jdt.ui.actions.FindReferencesAction.run (FindReferencesAction.java:78) at org.eclipse.jdt.ui.actions.FindAction.run(FindAction.java:237) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:193) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:169) at org.eclipse.jface.action.Action.runWithEvent(Action.java:769) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:411) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java:365) at org.eclipse.jface.action.ActionContributionItem.access$0 (ActionContributionItem.java:356) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java:48) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:825) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1692) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1410) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1467) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1450) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:845) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:462) 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:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539)
|
resolved fixed
|
0771670
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-14T08:17:45Z | 2003-01-13T17:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/SearchUtil.java
|
/*
* (c) Copyright IBM Corp. 2000, 2002.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.search;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Platform;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.ui.IWorkingSet;
import org.eclipse.ui.PlatformUI;
import org.eclipse.search.ui.ISearchResultViewEntry;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.IWorkingCopy;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.browsing.JavaElementTypeComparator;
import org.eclipse.jdt.internal.ui.dialogs.OptionalMessageDialog;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
/**
* This class contains some utility methods for J Search.
*/
public class SearchUtil extends JavaModelUtil {
// LRU working sets
public static int LRU_WORKINGSET_LIST_SIZE= 3;
private static LRUWorkingSetsList fgLRUWorkingSets;
// Settings store
private static final String DIALOG_SETTINGS_KEY= "JavaElementSearchActions"; //$NON-NLS-1$
private static final String STORE_LRU_WORKING_SET_NAMES= "lastUsedWorkingSetNames"; //$NON-NLS-1$
private static final JavaElementTypeComparator fgJavaElementTypeComparator= new JavaElementTypeComparator();
private static IDialogSettings fgSettingsStore;
private static final String BIN_PRIM_CONST_WARN_DIALOG_ID= "BinaryPrimitiveConstantWarningDialog"; //$NON-NLS-1$
public static IJavaElement getJavaElement(IMarker marker) {
if (marker == null || !marker.exists())
return null;
try {
String handleId= (String)marker.getAttribute(IJavaSearchUIConstants.ATT_JE_HANDLE_ID);
IJavaElement je= JavaCore.create(handleId);
if (je == null)
return null;
if (!marker.getAttribute(IJavaSearchUIConstants.ATT_IS_WORKING_COPY, false)) {
if (je != null && je.exists())
return je;
}
if (isBinary(je) || fgJavaElementTypeComparator.compare(je, IJavaElement.COMPILATION_UNIT) > 0)
return je;
ICompilationUnit cu= findCompilationUnit(je);
if (cu == null || !cu.exists()) {
cu= (ICompilationUnit)JavaCore.create(marker.getResource());
}
// Find working copy element
IWorkingCopy[] workingCopies= JavaUI.getSharedWorkingCopies();
int i= 0;
while (i < workingCopies.length) {
if (workingCopies[i].getOriginalElement().equals(cu)) {
je= findInWorkingCopy(workingCopies[i], je, true);
break;
}
i++;
}
if (je != null && !je.exists()) {
IJavaElement[] jElements= cu.findElements(je);
if (jElements == null || jElements.length == 0)
je= cu.getElementAt(marker.getAttribute(IMarker.CHAR_START, 0));
else
je= jElements[0];
}
return je;
} catch (CoreException ex) {
ExceptionHandler.handle(ex, SearchMessages.getString("Search.Error.createJavaElement.title"), SearchMessages.getString("Search.Error.createJavaElement.message")); //$NON-NLS-2$ //$NON-NLS-1$
return null;
}
}
public static IJavaElement getJavaElement(Object entry) {
if (entry != null && isISearchResultViewEntry(entry))
return getJavaElement((ISearchResultViewEntry)entry);
return null;
}
public static IResource getResource(Object entry) {
if (entry != null && isISearchResultViewEntry(entry))
return ((ISearchResultViewEntry)entry).getResource();
return null;
}
public static IJavaElement getJavaElement(ISearchResultViewEntry entry) {
if (entry != null)
return getJavaElement(entry.getSelectedMarker());
return null;
}
public static boolean isSearchPlugInActivated() {
return Platform.getPluginRegistry().getPluginDescriptor("org.eclipse.search").isPluginActivated(); //$NON-NLS-1$
}
public static boolean isISearchResultViewEntry(Object object) {
return object != null && isSearchPlugInActivated() && (object instanceof ISearchResultViewEntry);
}
private static boolean isBinary(IJavaElement jElement) {
if (jElement instanceof IMember)
return ((IMember)jElement).isBinary();
IPackageFragmentRoot pkgRoot= (IPackageFragmentRoot)jElement.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
if (pkgRoot != null && pkgRoot.isArchive())
return true;
return false;
}
private static IJavaElement fixCUName(IMarker marker, String handle) {
// FIXME: This is a dirty fix for 1GCE1EI: ITPJUI:WINNT - Can't handle rename of resource
if (handle != null) {
String resourceName= ""; //$NON-NLS-1$
if (marker.getResource() != null)
resourceName= marker.getResource().getName();
if (!handleContainsWrongCU(handle, resourceName)) {
handle= computeFixedHandle(handle, resourceName);
IJavaElement je= JavaCore.create(handle);
if (je != null && je.exists()) {
try {
marker.setAttribute(IJavaSearchUIConstants.ATT_JE_HANDLE_ID, handle);
} catch (CoreException ex) {
// leave old attribute
} finally {
return je;
}
}
}
}
return null;
}
private static boolean handleContainsWrongCU(String handle, String resourceName) {
int start= handle.indexOf('{');
int end= handle.indexOf(".java"); //$NON-NLS-1$
if (start >= end)
return false;
String name= handle.substring(start + 1, end + 5);
return name.equals(resourceName);
}
private static String computeFixedHandle(String handle, String resourceName) {
int start= handle.indexOf('{');
int end= handle.indexOf(".java"); //$NON-NLS-1$
handle= handle.substring(0, start + 1) + resourceName + handle.substring(end + 5);
return handle;
}
/**
* 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
*/
private static IJavaElement findInWorkingCopy(IWorkingCopy workingCopy, IJavaElement element, boolean reconcile) throws JavaModelException {
if (workingCopy != null) {
if (reconcile) {
synchronized (workingCopy) {
workingCopy.reconcile();
return SearchUtil.findInCompilationUnit((ICompilationUnit)workingCopy, element);
}
} else {
return SearchUtil.findInCompilationUnit((ICompilationUnit)workingCopy, element);
}
}
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
*/
static ICompilationUnit findCompilationUnit(IJavaElement element) {
if (element == null)
return null;
if (element.getElementType() == IJavaElement.COMPILATION_UNIT)
return (ICompilationUnit)element;
if (element instanceof IMember)
return ((IMember)element).getCompilationUnit();
return findCompilationUnit(element.getParent());
}
/*
* Copied from JavaModelUtil and patched to allow members which do not exist.
* The only case where this is a problem is for methods which have same name and
* paramters as a constructor. The constructor will win in such a situation.
*
* @see JavaModelUtil#findMemberInCompilationUnit(ICompilationUnit, IMember)
*/
public static IMember findInCompilationUnit(ICompilationUnit cu, IMember member) throws JavaModelException {
if (member.getElementType() == IJavaElement.TYPE) {
return findTypeInCompilationUnit(cu, getTypeQualifiedName((IType)member));
} else {
IType declaringType= findTypeInCompilationUnit(cu, getTypeQualifiedName(member.getDeclaringType()));
if (declaringType != null) {
IMember result= null;
switch (member.getElementType()) {
case IJavaElement.FIELD:
result= declaringType.getField(member.getElementName());
break;
case IJavaElement.METHOD:
IMethod meth= (IMethod) member;
// XXX: Begin patch ---------------------
boolean isConstructor;
if (meth.exists())
isConstructor= meth.isConstructor();
else
isConstructor= declaringType.getElementName().equals(meth.getElementName());
// XXX: End patch -----------------------
result= findMethod(meth.getElementName(), meth.getParameterTypes(), isConstructor, declaringType);
break;
case IJavaElement.INITIALIZER:
result= declaringType.getInitializer(1);
break;
}
if (result != null && result.exists()) {
return result;
}
}
}
return null;
}
/*
* XXX: Unchanged copy from JavaModelUtil
*/
public static IJavaElement findInCompilationUnit(ICompilationUnit cu, IJavaElement element) throws JavaModelException {
if (element instanceof IMember)
return findInCompilationUnit(cu, (IMember)element);
int type= element.getElementType();
switch (type) {
case IJavaElement.IMPORT_CONTAINER:
return cu.getImportContainer();
case IJavaElement.PACKAGE_DECLARATION:
return find(cu.getPackageDeclarations(), element.getElementName());
case IJavaElement.IMPORT_DECLARATION:
return find(cu.getImports(), element.getElementName());
case IJavaElement.COMPILATION_UNIT:
return cu;
}
return null;
}
/*
* XXX: Unchanged copy from JavaModelUtil
*/
private static IJavaElement find(IJavaElement[] elements, String name) {
if (elements == null || name == null)
return null;
for (int i= 0; i < elements.length; i++) {
if (name.equals(elements[i].getElementName()))
return elements[i];
}
return null;
}
public static String toString(IWorkingSet[] workingSets) {
Arrays.sort(workingSets, new WorkingSetComparator());
String result= ""; //$NON-NLS-1$
if (workingSets != null && workingSets.length > 0) {
boolean firstFound= false;
for (int i= 0; i < workingSets.length; i++) {
String workingSetName= workingSets[i].getName();
if (firstFound)
result= SearchMessages.getFormattedString("SearchUtil.workingSetConcatenation", new String[] {result, workingSetName}); //$NON-NLS-1$
else {
result= workingSetName;
firstFound= true;
}
}
}
return result;
}
// ---------- LRU working set handling ----------
/**
* Updates the LRU list of working sets.
*
* @param workingSets the workings sets to be added to the LRU list
*/
public static void updateLRUWorkingSets(IWorkingSet[] workingSets) {
if (workingSets == null || workingSets.length < 1)
return;
getLRUWorkingSets().add(workingSets);
saveState();
}
private static void saveState() {
IWorkingSet[] workingSets;
Iterator iter= fgLRUWorkingSets.iterator();
int i= 0;
while (iter.hasNext()) {
workingSets= (IWorkingSet[])iter.next();
String[] names= new String[workingSets.length];
for (int j= 0; j < workingSets.length; j++)
names[j]= workingSets[j].getName();
fgSettingsStore.put(STORE_LRU_WORKING_SET_NAMES + i, names);
i++;
}
}
public static LRUWorkingSetsList getLRUWorkingSets() {
if (fgLRUWorkingSets == null) {
restoreState();
}
return fgLRUWorkingSets;
}
static void restoreState() {
fgLRUWorkingSets= new LRUWorkingSetsList(LRU_WORKINGSET_LIST_SIZE);
fgSettingsStore= JavaPlugin.getDefault().getDialogSettings().getSection(DIALOG_SETTINGS_KEY);
if (fgSettingsStore == null)
fgSettingsStore= JavaPlugin.getDefault().getDialogSettings().addNewSection(DIALOG_SETTINGS_KEY);
boolean foundLRU= false;
for (int i= LRU_WORKINGSET_LIST_SIZE - 1; i >= 0; i--) {
String[] lruWorkingSetNames= fgSettingsStore.getArray(STORE_LRU_WORKING_SET_NAMES + i);
if (lruWorkingSetNames != null) {
Set workingSets= new HashSet(2);
for (int j= 0; j < lruWorkingSetNames.length; j++) {
IWorkingSet workingSet= PlatformUI.getWorkbench().getWorkingSetManager().getWorkingSet(lruWorkingSetNames[j]);
if (workingSet != null) {
workingSets.add(workingSet);
}
}
foundLRU= true;
if (!workingSets.isEmpty())
fgLRUWorkingSets.add((IWorkingSet[])workingSets.toArray(new IWorkingSet[workingSets.size()]));
}
}
if (!foundLRU)
// try old preference format
restoreFromOldFormat();
}
private static void restoreFromOldFormat() {
fgLRUWorkingSets= new LRUWorkingSetsList(LRU_WORKINGSET_LIST_SIZE);
fgSettingsStore= JavaPlugin.getDefault().getDialogSettings().getSection(DIALOG_SETTINGS_KEY);
if (fgSettingsStore == null)
fgSettingsStore= JavaPlugin.getDefault().getDialogSettings().addNewSection(DIALOG_SETTINGS_KEY);
boolean foundLRU= false;
String[] lruWorkingSetNames= fgSettingsStore.getArray(STORE_LRU_WORKING_SET_NAMES);
if (lruWorkingSetNames != null) {
for (int i= lruWorkingSetNames.length - 1; i >= 0; i--) {
IWorkingSet workingSet= PlatformUI.getWorkbench().getWorkingSetManager().getWorkingSet(lruWorkingSetNames[i]);
if (workingSet != null) {
foundLRU= true;
fgLRUWorkingSets.add(new IWorkingSet[]{workingSet});
}
}
}
if (foundLRU)
// save in new format
saveState();
}
public static void warnIfBinaryConstant(IJavaElement element, Shell shell) {
if (isBinaryPrimitveConstantOrString(element))
OptionalMessageDialog.open(
BIN_PRIM_CONST_WARN_DIALOG_ID,
shell,
SearchMessages.getString("Search.FindReferencesAction.BinPrimConstWarnDialog.title"), //$NON-NLS-1$
null,
SearchMessages.getString("Search.FindReferencesAction.BinPrimConstWarnDialog.message"), //$NON-NLS-1$
OptionalMessageDialog.INFORMATION,
new String[] { IDialogConstants.OK_LABEL },
0);
}
private static boolean isBinaryPrimitveConstantOrString(IJavaElement element) {
if (element.getElementType() == IJavaElement.FIELD) {
IField field= (IField)element;
int flags;
try {
flags= field.getFlags();
} catch (JavaModelException ex) {
return false;
}
return field.isBinary() && Flags.isStatic(flags) && Flags.isFinal(flags) && isPrimitiveOrString(field);
}
return false;
}
private static boolean isPrimitiveOrString(IField field) {
String fieldType;
try {
fieldType= field.getTypeSignature();
} catch (JavaModelException ex) {
return false;
}
char first= fieldType.charAt(0);
return (first != Signature.C_RESOLVED && first != Signature.C_UNRESOLVED && first != Signature.C_ARRAY)
|| (first == Signature.C_RESOLVED && fieldType.substring(1, fieldType.length() - 1).equals(String.class.getName()));
}
}
|
29,416 |
Bug 29416 Cannot create Type if typecomment Template doesn't exist
|
Actual: Click on File/New/Interface (or Class). Type a name, and click Finish. Error dialog appears telling me to look in the log (stack trace below). Interface/Class file is created, but is completely empty. If I go to Preferences and create the "typecomment" template, this problem goes away Expected: Class/Interface should be created and the file populated properly, despite the absence of the typecomment template. Looks easy to fix, I just don't have the code handy, nor thetime to do it (sorry). The relevant portion of the stack trace: Caused by: java.lang.NullPointerException at org.eclipse.jdt.ui.wizards.NewTypeWizardPage.isValidComment(NewTypeWizardPage.java:1543) at org.eclipse.jdt.ui.wizards.NewTypeWizardPage.getTypeComment(NewTypeWizardPage.java:1566) at org.eclipse.jdt.ui.wizards.NewTypeWizardPage.constructTypeStub(NewTypeWizardPage.java:1462) at org.eclipse.jdt.ui.wizards.NewTypeWizardPage.createType(NewTypeWizardPage.java:1345) at org.eclipse.jdt.internal.ui.wizards.NewInterfaceCreationWizard.finishPage(NewInterfaceCreationWizard.java:45) at org.eclipse.jdt.internal.ui.wizards.NewElementWizard$2.run(NewElementWizard.java:79) at org.eclipse.jdt.internal.core.BatchOperation.executeOperation(BatchOperation.java:34) at org.eclipse.jdt.internal.core.JavaModelOperation.execute(JavaModelOperation.java:326) at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:626) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1564) at org.eclipse.jdt.core.JavaCore.run(JavaCore.java:2571) at org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter.run(WorkbenchRunnableAdapter.java:32) at org.eclipse.jface.operation.ModalContext.runInCurrentThread(ModalContext.java:296)
|
resolved fixed
|
3b9ae18
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-14T09:16:55Z | 2003-01-13T23:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/wizards/NewTypeWizardPage.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. 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.wizards;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.ui.dialogs.ElementListSelectionDialog;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IBuffer;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.JavaConventions;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.core.ToolFactory;
import org.eclipse.jdt.core.compiler.IScanner;
import org.eclipse.jdt.core.compiler.ITerminalSymbols;
import org.eclipse.jdt.core.compiler.InvalidInputException;
import org.eclipse.jdt.core.search.IJavaSearchConstants;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.codemanipulation.IImportsStructure;
import org.eclipse.jdt.internal.corext.codemanipulation.ImportsStructure;
import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility;
import org.eclipse.jdt.internal.corext.template.Template;
import org.eclipse.jdt.internal.corext.template.Templates;
import org.eclipse.jdt.internal.corext.template.java.JavaContext;
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.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.dialogs.TypeSelectionDialog;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.util.SWTUtil;
import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages;
import org.eclipse.jdt.internal.ui.wizards.SuperInterfaceSelectionDialog;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogFieldGroup;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.Separator;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonStatusDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField;
/**
* The class <code>NewTypeWizardPage</code> contains controls and validation routines
* for a 'New Type WizardPage'. Implementors decide which components to add and to enable.
* Implementors can also customize the validation code. <code>NewTypeWizardPage</code>
* is intended to serve as base class of all wizards that create types like applets, servlets, classes,
* interfaces, etc.
* <p>
* See <code>NewClassWizardPage</code> or <code>NewInterfaceWizardPage</code> for an
* example usage of <code>NewTypeWizardPage</code>.
* </p>
*
* @see org.eclipse.jdt.ui.wizards.NewClassWizardPage
* @see org.eclipse.jdt.ui.wizards.NewInterfaceWizardPage
*
* @since 2.0
*/
public abstract class NewTypeWizardPage extends NewContainerWizardPage {
/**
* Class used in stub creation routines to add needed imports to a
* compilation unit.
*/
public static class ImportsManager {
private IImportsStructure fImportsStructure;
/* package */ ImportsManager(IImportsStructure structure) {
fImportsStructure= structure;
}
/* package */ IImportsStructure getImportsStructure() {
return fImportsStructure;
}
/**
* Adds a new import declaration that is sorted in the existing imports.
* If an import already exists or the import would conflict with another import
* of an other type with the same simple name the import is not added.
*
* @param qualifiedTypeName The fully qualified name of the type to import
* (dot separated)
* @return Returns the simple type name that can be used in the code or the
* fully qualified type name if an import conflict prevented the import
*/
public String addImport(String qualifiedTypeName) {
return fImportsStructure.addImport(qualifiedTypeName);
}
}
/** Public access flag. See The Java Virtual Machine Specification for more details. */
public int F_PUBLIC = Flags.AccPublic;
/** Private access flag. See The Java Virtual Machine Specification for more details. */
public int F_PRIVATE = Flags.AccPrivate;
/** Protected access flag. See The Java Virtual Machine Specification for more details. */
public int F_PROTECTED = Flags.AccProtected;
/** Static access flag. See The Java Virtual Machine Specification for more details. */
public int F_STATIC = Flags.AccStatic;
/** Final access flag. See The Java Virtual Machine Specification for more details. */
public int F_FINAL = Flags.AccFinal;
/** Abstract property flag. See The Java Virtual Machine Specification for more details. */
public int F_ABSTRACT = Flags.AccAbstract;
private final static String PAGE_NAME= "NewTypeWizardPage"; //$NON-NLS-1$
/** Field ID of the package input field */
protected final static String PACKAGE= PAGE_NAME + ".package"; //$NON-NLS-1$
/** Field ID of the eclosing type input field */
protected final static String ENCLOSING= PAGE_NAME + ".enclosing"; //$NON-NLS-1$
/** Field ID of the enclosing type checkbox */
protected final static String ENCLOSINGSELECTION= ENCLOSING + ".selection"; //$NON-NLS-1$
/** Field ID of the type name input field */
protected final static String TYPENAME= PAGE_NAME + ".typename"; //$NON-NLS-1$
/** Field ID of the super type input field */
protected final static String SUPER= PAGE_NAME + ".superclass"; //$NON-NLS-1$
/** Field ID of the super interfaces input field */
protected final static String INTERFACES= PAGE_NAME + ".interfaces"; //$NON-NLS-1$
/** Field ID of the modifier checkboxes */
protected final static String MODIFIERS= PAGE_NAME + ".modifiers"; //$NON-NLS-1$
/** Field ID of the method stubs checkboxes */
protected final static String METHODS= PAGE_NAME + ".methods"; //$NON-NLS-1$
private class InterfacesListLabelProvider extends LabelProvider {
private Image fInterfaceImage;
public InterfacesListLabelProvider() {
super();
fInterfaceImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_INTERFACE);
}
public Image getImage(Object element) {
return fInterfaceImage;
}
}
private StringButtonStatusDialogField fPackageDialogField;
private SelectionButtonDialogField fEnclosingTypeSelection;
private StringButtonDialogField fEnclosingTypeDialogField;
private boolean fCanModifyPackage;
private boolean fCanModifyEnclosingType;
private IPackageFragment fCurrPackage;
private IType fCurrEnclosingType;
private StringDialogField fTypeNameDialogField;
private StringButtonDialogField fSuperClassDialogField;
private ListDialogField fSuperInterfacesDialogField;
private IType fSuperClass;
private SelectionButtonDialogFieldGroup fAccMdfButtons;
private SelectionButtonDialogFieldGroup fOtherMdfButtons;
private IType fCreatedType;
protected IStatus fEnclosingTypeStatus;
protected IStatus fPackageStatus;
protected IStatus fTypeNameStatus;
protected IStatus fSuperClassStatus;
protected IStatus fModifierStatus;
protected IStatus fSuperInterfacesStatus;
private boolean fIsClass;
private int fStaticMdfIndex;
private final int PUBLIC_INDEX= 0, DEFAULT_INDEX= 1, PRIVATE_INDEX= 2, PROTECTED_INDEX= 3;
private final int ABSTRACT_INDEX= 0, FINAL_INDEX= 1;
/**
* Creates a new <code>NewTypeWizardPage</code>
*
* @param isClass <code>true</code> if a new class is to be created; otherwise
* an interface is to be created
* @param pageName the wizard page's name
*/
public NewTypeWizardPage(boolean isClass, String pageName) {
super(pageName);
fCreatedType= null;
fIsClass= isClass;
TypeFieldsAdapter adapter= new TypeFieldsAdapter();
fPackageDialogField= new StringButtonStatusDialogField(adapter);
fPackageDialogField.setDialogFieldListener(adapter);
fPackageDialogField.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.package.label")); //$NON-NLS-1$
fPackageDialogField.setButtonLabel(NewWizardMessages.getString("NewTypeWizardPage.package.button")); //$NON-NLS-1$
fPackageDialogField.setStatusWidthHint(NewWizardMessages.getString("NewTypeWizardPage.default")); //$NON-NLS-1$
fEnclosingTypeSelection= new SelectionButtonDialogField(SWT.CHECK);
fEnclosingTypeSelection.setDialogFieldListener(adapter);
fEnclosingTypeSelection.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.enclosing.selection.label")); //$NON-NLS-1$
fEnclosingTypeDialogField= new StringButtonDialogField(adapter);
fEnclosingTypeDialogField.setDialogFieldListener(adapter);
fEnclosingTypeDialogField.setButtonLabel(NewWizardMessages.getString("NewTypeWizardPage.enclosing.button")); //$NON-NLS-1$
fTypeNameDialogField= new StringDialogField();
fTypeNameDialogField.setDialogFieldListener(adapter);
fTypeNameDialogField.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.typename.label")); //$NON-NLS-1$
fSuperClassDialogField= new StringButtonDialogField(adapter);
fSuperClassDialogField.setDialogFieldListener(adapter);
fSuperClassDialogField.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.superclass.label")); //$NON-NLS-1$
fSuperClassDialogField.setButtonLabel(NewWizardMessages.getString("NewTypeWizardPage.superclass.button")); //$NON-NLS-1$
String[] addButtons= new String[] {
/* 0 */ NewWizardMessages.getString("NewTypeWizardPage.interfaces.add"), //$NON-NLS-1$
/* 1 */ null,
/* 2 */ NewWizardMessages.getString("NewTypeWizardPage.interfaces.remove") //$NON-NLS-1$
};
fSuperInterfacesDialogField= new ListDialogField(adapter, addButtons, new InterfacesListLabelProvider());
fSuperInterfacesDialogField.setDialogFieldListener(adapter);
String interfaceLabel= fIsClass ? NewWizardMessages.getString("NewTypeWizardPage.interfaces.class.label") : NewWizardMessages.getString("NewTypeWizardPage.interfaces.ifc.label"); //$NON-NLS-1$ //$NON-NLS-2$
fSuperInterfacesDialogField.setLabelText(interfaceLabel);
fSuperInterfacesDialogField.setRemoveButtonIndex(2);
String[] buttonNames1= new String[] {
/* 0 == PUBLIC_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.public"), //$NON-NLS-1$
/* 1 == DEFAULT_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.default"), //$NON-NLS-1$
/* 2 == PRIVATE_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.private"), //$NON-NLS-1$
/* 3 == PROTECTED_INDEX*/ NewWizardMessages.getString("NewTypeWizardPage.modifiers.protected") //$NON-NLS-1$
};
fAccMdfButtons= new SelectionButtonDialogFieldGroup(SWT.RADIO, buttonNames1, 4);
fAccMdfButtons.setDialogFieldListener(adapter);
fAccMdfButtons.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.modifiers.acc.label")); //$NON-NLS-1$
fAccMdfButtons.setSelection(0, true);
String[] buttonNames2;
if (fIsClass) {
buttonNames2= new String[] {
/* 0 == ABSTRACT_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.abstract"), //$NON-NLS-1$
/* 1 == FINAL_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.final"), //$NON-NLS-1$
/* 2 */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.static") //$NON-NLS-1$
};
fStaticMdfIndex= 2; // index of the static checkbox is 2
} else {
buttonNames2= new String[] {
NewWizardMessages.getString("NewTypeWizardPage.modifiers.static") //$NON-NLS-1$
};
fStaticMdfIndex= 0; // index of the static checkbox is 0
}
fOtherMdfButtons= new SelectionButtonDialogFieldGroup(SWT.CHECK, buttonNames2, 4);
fOtherMdfButtons.setDialogFieldListener(adapter);
fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, false);
fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, false);
fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, false);
fPackageStatus= new StatusInfo();
fEnclosingTypeStatus= new StatusInfo();
fCanModifyPackage= true;
fCanModifyEnclosingType= true;
updateEnableState();
fTypeNameStatus= new StatusInfo();
fSuperClassStatus= new StatusInfo();
fSuperInterfacesStatus= new StatusInfo();
fModifierStatus= new StatusInfo();
}
/**
* Initializes all fields provided by the page with a given selection.
*
* @param elem the selection used to intialize this page or <code>
* null</code> if no selection was available
*/
protected void initTypePage(IJavaElement elem) {
String initSuperclass= "java.lang.Object"; //$NON-NLS-1$
ArrayList initSuperinterfaces= new ArrayList(5);
IPackageFragment pack= null;
IType enclosingType= null;
if (elem != null) {
// evaluate the enclosing type
pack= (IPackageFragment) elem.getAncestor(IJavaElement.PACKAGE_FRAGMENT);
IType typeInCU= (IType) elem.getAncestor(IJavaElement.TYPE);
if (typeInCU != null) {
if (typeInCU.getCompilationUnit() != null) {
enclosingType= typeInCU;
}
} else {
ICompilationUnit cu= (ICompilationUnit) elem.getAncestor(IJavaElement.COMPILATION_UNIT);
if (cu != null) {
enclosingType= cu.findPrimaryType();
}
}
try {
IType type= null;
if (elem.getElementType() == IJavaElement.TYPE) {
type= (IType)elem;
if (type.exists()) {
String superName= JavaModelUtil.getFullyQualifiedName(type);
if (type.isInterface()) {
initSuperinterfaces.add(superName);
} else {
initSuperclass= superName;
}
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
// ignore this exception now
}
}
setPackageFragment(pack, true);
setEnclosingType(enclosingType, true);
setEnclosingTypeSelection(false, true);
setTypeName("", true); //$NON-NLS-1$
setSuperClass(initSuperclass, true);
setSuperInterfaces(initSuperinterfaces, true);
}
// -------- UI Creation ---------
/**
* Creates a separator line. Expects a <code>GridLayout</code> with at least 1 column.
*
* @param composite the parent composite
* @param nColumns number of columns to span
*/
protected void createSeparator(Composite composite, int nColumns) {
(new Separator(SWT.SEPARATOR | SWT.HORIZONTAL)).doFillIntoGrid(composite, nColumns, convertHeightInCharsToPixels(1));
}
/**
* Creates the controls for the package name field. Expects a <code>GridLayout</code> with at
* least 4 columns.
*
* @param composite the parent composite
* @param nColumns number of columns to span
*/
protected void createPackageControls(Composite composite, int nColumns) {
fPackageDialogField.doFillIntoGrid(composite, nColumns);
LayoutUtil.setWidthHint(fPackageDialogField.getTextControl(null), getMaxFieldWidth());
LayoutUtil.setHorizontalGrabbing(fPackageDialogField.getTextControl(null));
}
/**
* Creates the controls for the enclosing type name field. Expects a <code>GridLayout</code> with at
* least 4 columns.
*
* @param composite the parent composite
* @param nColumns number of columns to span
*/
protected void createEnclosingTypeControls(Composite composite, int nColumns) {
// #6891
Composite tabGroup= new Composite(composite, SWT.NONE);
GridLayout layout= new GridLayout();
layout.marginWidth= 0;
layout.marginHeight= 0;
tabGroup.setLayout(layout);
fEnclosingTypeSelection.doFillIntoGrid(tabGroup, 1);
Control c= fEnclosingTypeDialogField.getTextControl(composite);
GridData gd= new GridData(GridData.FILL_HORIZONTAL);
gd.widthHint= getMaxFieldWidth();
gd.horizontalSpan= 2;
c.setLayoutData(gd);
Button button= fEnclosingTypeDialogField.getChangeControl(composite);
gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.heightHint = SWTUtil.getButtonHeigthHint(button);
gd.widthHint = SWTUtil.getButtonWidthHint(button);
button.setLayoutData(gd);
}
/**
* Creates the controls for the type name field. Expects a <code>GridLayout</code> with at
* least 2 columns.
*
* @param composite the parent composite
* @param nColumns number of columns to span
*/
protected void createTypeNameControls(Composite composite, int nColumns) {
fTypeNameDialogField.doFillIntoGrid(composite, nColumns - 1);
DialogField.createEmptySpace(composite);
LayoutUtil.setWidthHint(fTypeNameDialogField.getTextControl(null), getMaxFieldWidth());
}
/**
* Creates the controls for the modifiers radio/ceckbox buttons. Expects a
* <code>GridLayout</code> with at least 3 columns.
*
* @param composite the parent composite
* @param nColumns number of columns to span
*/
protected void createModifierControls(Composite composite, int nColumns) {
LayoutUtil.setHorizontalSpan(fAccMdfButtons.getLabelControl(composite), 1);
Control control= fAccMdfButtons.getSelectionButtonsGroup(composite);
GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= nColumns - 2;
control.setLayoutData(gd);
DialogField.createEmptySpace(composite);
DialogField.createEmptySpace(composite);
control= fOtherMdfButtons.getSelectionButtonsGroup(composite);
gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= nColumns - 2;
control.setLayoutData(gd);
DialogField.createEmptySpace(composite);
}
/**
* Creates the controls for the superclass name field. Expects a <code>GridLayout</code>
* with at least 3 columns.
*
* @param composite the parent composite
* @param nColumns number of columns to span
*/
protected void createSuperClassControls(Composite composite, int nColumns) {
fSuperClassDialogField.doFillIntoGrid(composite, nColumns);
LayoutUtil.setWidthHint(fSuperClassDialogField.getTextControl(null), getMaxFieldWidth());
}
/**
* Creates the controls for the superclass name field. Expects a <code>GridLayout</code> with
* at least 3 columns.
*
* @param composite the parent composite
* @param nColumns number of columns to span
*/
protected void createSuperInterfacesControls(Composite composite, int nColumns) {
fSuperInterfacesDialogField.doFillIntoGrid(composite, nColumns);
GridData gd= (GridData)fSuperInterfacesDialogField.getListControl(null).getLayoutData();
if (fIsClass) {
gd.heightHint= convertHeightInCharsToPixels(3);
} else {
gd.heightHint= convertHeightInCharsToPixels(6);
}
gd.grabExcessVerticalSpace= false;
gd.widthHint= getMaxFieldWidth();
}
/**
* Sets the focus on the type name input field.
*/
protected void setFocus() {
fTypeNameDialogField.setFocus();
}
// -------- TypeFieldsAdapter --------
private class TypeFieldsAdapter implements IStringButtonAdapter, IDialogFieldListener, IListAdapter {
// -------- IStringButtonAdapter
public void changeControlPressed(DialogField field) {
typePageChangeControlPressed(field);
}
// -------- IListAdapter
public void customButtonPressed(ListDialogField field, int index) {
typePageCustomButtonPressed(field, index);
}
public void selectionChanged(ListDialogField field) {}
// -------- IDialogFieldListener
public void dialogFieldChanged(DialogField field) {
typePageDialogFieldChanged(field);
}
public void doubleClicked(ListDialogField field) {
}
}
private void typePageChangeControlPressed(DialogField field) {
if (field == fPackageDialogField) {
IPackageFragment pack= choosePackage();
if (pack != null) {
fPackageDialogField.setText(pack.getElementName());
}
} else if (field == fEnclosingTypeDialogField) {
IType type= chooseEnclosingType();
if (type != null) {
fEnclosingTypeDialogField.setText(JavaModelUtil.getFullyQualifiedName(type));
}
} else if (field == fSuperClassDialogField) {
IType type= chooseSuperType();
if (type != null) {
fSuperClassDialogField.setText(JavaModelUtil.getFullyQualifiedName(type));
}
}
}
private void typePageCustomButtonPressed(DialogField field, int index) {
if (field == fSuperInterfacesDialogField) {
chooseSuperInterfaces();
}
}
/*
* A field on the type has changed. The fields' status and all dependend
* status are updated.
*/
private void typePageDialogFieldChanged(DialogField field) {
String fieldName= null;
if (field == fPackageDialogField) {
fPackageStatus= packageChanged();
updatePackageStatusLabel();
fTypeNameStatus= typeNameChanged();
fSuperClassStatus= superClassChanged();
fieldName= PACKAGE;
} else if (field == fEnclosingTypeDialogField) {
fEnclosingTypeStatus= enclosingTypeChanged();
fTypeNameStatus= typeNameChanged();
fSuperClassStatus= superClassChanged();
fieldName= ENCLOSING;
} else if (field == fEnclosingTypeSelection) {
updateEnableState();
boolean isEnclosedType= isEnclosingTypeSelected();
if (!isEnclosedType) {
if (fAccMdfButtons.isSelected(PRIVATE_INDEX) || fAccMdfButtons.isSelected(PROTECTED_INDEX)) {
fAccMdfButtons.setSelection(PRIVATE_INDEX, false);
fAccMdfButtons.setSelection(PROTECTED_INDEX, false);
fAccMdfButtons.setSelection(PUBLIC_INDEX, true);
}
if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) {
fOtherMdfButtons.setSelection(fStaticMdfIndex, false);
}
}
fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, isEnclosedType && fIsClass);
fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, isEnclosedType && fIsClass);
fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, isEnclosedType);
fTypeNameStatus= typeNameChanged();
fSuperClassStatus= superClassChanged();
fieldName= ENCLOSINGSELECTION;
} else if (field == fTypeNameDialogField) {
fTypeNameStatus= typeNameChanged();
fieldName= TYPENAME;
} else if (field == fSuperClassDialogField) {
fSuperClassStatus= superClassChanged();
fieldName= SUPER;
} else if (field == fSuperInterfacesDialogField) {
fSuperInterfacesStatus= superInterfacesChanged();
fieldName= INTERFACES;
} else if (field == fOtherMdfButtons) {
fModifierStatus= modifiersChanged();
fieldName= MODIFIERS;
} else {
fieldName= METHODS;
}
// tell all others
handleFieldChanged(fieldName);
}
// -------- update message ----------------
/*
* @see org.eclipse.jdt.ui.wizards.NewContainerWizardPage#handleFieldChanged(String)
*/
protected void handleFieldChanged(String fieldName) {
super.handleFieldChanged(fieldName);
if (fieldName == CONTAINER) {
fPackageStatus= packageChanged();
fEnclosingTypeStatus= enclosingTypeChanged();
fTypeNameStatus= typeNameChanged();
fSuperClassStatus= superClassChanged();
fSuperInterfacesStatus= superInterfacesChanged();
}
}
// ---- set / get ----------------
/**
* Returns the text of the package input field.
*
* @return the text of the package input field
*/
public String getPackageText() {
return fPackageDialogField.getText();
}
/**
* Returns the text of the enclosing type input field.
*
* @return the text of the enclosing type input field
*/
public String getEnclosingTypeText() {
return fEnclosingTypeDialogField.getText();
}
/**
* Returns the package fragment corresponding to the current input.
*
* @return a package fragement or <code>null</code> if the input
* could not be resolved.
*/
public IPackageFragment getPackageFragment() {
if (!isEnclosingTypeSelected()) {
return fCurrPackage;
} else {
if (fCurrEnclosingType != null) {
return fCurrEnclosingType.getPackageFragment();
}
}
return null;
}
/**
* Sets the package fragment to the given value. The method updates the model
* and the text of the control.
*
* @param pack the package fragement to be set
* @param canBeModified if <code>true</code> the package fragment is
* editable; otherwise it is read-only.
*/
public void setPackageFragment(IPackageFragment pack, boolean canBeModified) {
fCurrPackage= pack;
fCanModifyPackage= canBeModified;
String str= (pack == null) ? "" : pack.getElementName(); //$NON-NLS-1$
fPackageDialogField.setText(str);
updateEnableState();
}
/**
* Returns the enclosing type corresponding to the current input.
*
* @return the enclosing type or <code>null</code> if the enclosing type is
* not selected or the input could not be resolved
*/
public IType getEnclosingType() {
if (isEnclosingTypeSelected()) {
return fCurrEnclosingType;
}
return null;
}
/**
* Sets the enclosing type. The method updates the underlying model
* and the text of the control.
*
* @param type the enclosing type
* @param canBeModified if <code>true</code> the enclosing type field is
* editable; otherwise it is read-only.
*/
public void setEnclosingType(IType type, boolean canBeModified) {
fCurrEnclosingType= type;
fCanModifyEnclosingType= canBeModified;
String str= (type == null) ? "" : JavaModelUtil.getFullyQualifiedName(type); //$NON-NLS-1$
fEnclosingTypeDialogField.setText(str);
updateEnableState();
}
/**
* Returns the selection state of the enclosing type checkbox.
*
* @return the seleciton state of the enclosing type checkbox
*/
public boolean isEnclosingTypeSelected() {
return fEnclosingTypeSelection.isSelected();
}
/**
* Sets the enclosing type checkbox's selection state.
*
* @param isSelected the checkbox's selection state
* @param canBeModified if <code>true</code> the enclosing type checkbox is
* modifiable; otherwise it is read-only.
*/
public void setEnclosingTypeSelection(boolean isSelected, boolean canBeModified) {
fEnclosingTypeSelection.setSelection(isSelected);
fEnclosingTypeSelection.setEnabled(canBeModified);
updateEnableState();
}
/**
* Returns the type name entered into the type input field.
*
* @return the type name
*/
public String getTypeName() {
return fTypeNameDialogField.getText();
}
/**
* Sets the type name input field's text to the given value. Method doesn't update
* the model.
*
* @param name the new type name
* @param canBeModified if <code>true</code> the enclosing type name field is
* editable; otherwise it is read-only.
*/
public void setTypeName(String name, boolean canBeModified) {
fTypeNameDialogField.setText(name);
fTypeNameDialogField.setEnabled(canBeModified);
}
/**
* Returns the selected modifiers.
*
* @return the selected modifiers
* @see Flags
*/
public int getModifiers() {
int mdf= 0;
if (fAccMdfButtons.isSelected(PUBLIC_INDEX)) {
mdf+= F_PUBLIC;
} else if (fAccMdfButtons.isSelected(PRIVATE_INDEX)) {
mdf+= F_PRIVATE;
} else if (fAccMdfButtons.isSelected(PROTECTED_INDEX)) {
mdf+= F_PROTECTED;
}
if (fOtherMdfButtons.isSelected(ABSTRACT_INDEX) && (fStaticMdfIndex != 0)) {
mdf+= F_ABSTRACT;
}
if (fOtherMdfButtons.isSelected(FINAL_INDEX)) {
mdf+= F_FINAL;
}
if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) {
mdf+= F_STATIC;
}
return mdf;
}
/**
* Sets the modifiers.
*
* @param modifiers <code>F_PUBLIC</code>, <code>F_PRIVATE</code>,
* <code>F_PROTECTED</code>, <code>F_ABSTRACT, F_FINAL</code>
* or <code>F_STATIC</code> or, a valid combination.
* @param canBeModified if <code>true</code> the modifier fields are
* editable; otherwise they are read-only
* @see Flags
*/
public void setModifiers(int modifiers, boolean canBeModified) {
if (Flags.isPublic(modifiers)) {
fAccMdfButtons.setSelection(PUBLIC_INDEX, true);
} else if (Flags.isPrivate(modifiers)) {
fAccMdfButtons.setSelection(PRIVATE_INDEX, true);
} else if (Flags.isProtected(modifiers)) {
fAccMdfButtons.setSelection(PROTECTED_INDEX, true);
} else {
fAccMdfButtons.setSelection(DEFAULT_INDEX, true);
}
if (Flags.isAbstract(modifiers)) {
fOtherMdfButtons.setSelection(ABSTRACT_INDEX, true);
}
if (Flags.isFinal(modifiers)) {
fOtherMdfButtons.setSelection(FINAL_INDEX, true);
}
if (Flags.isStatic(modifiers)) {
fOtherMdfButtons.setSelection(fStaticMdfIndex, true);
}
fAccMdfButtons.setEnabled(canBeModified);
fOtherMdfButtons.setEnabled(canBeModified);
}
/**
* Returns the content of the superclass input field.
*
* @return the superclass name
*/
public String getSuperClass() {
return fSuperClassDialogField.getText();
}
/**
* Sets the super class name.
*
* @param name the new superclass name
* @param canBeModified if <code>true</code> the superclass name field is
* editable; otherwise it is read-only.
*/
public void setSuperClass(String name, boolean canBeModified) {
fSuperClassDialogField.setText(name);
fSuperClassDialogField.setEnabled(canBeModified);
}
/**
* Returns the chosen super interfaces.
*
* @return a list of chosen super interfaces. The list's elements
* are of type <code>String</code>
*/
public List getSuperInterfaces() {
return fSuperInterfacesDialogField.getElements();
}
/**
* Sets the super interfaces.
*
* @param interfacesNames a list of super interface. The method requires that
* the list's elements are of type <code>String</code>
* @param canBeModified if <code>true</code> the super interface field is
* editable; otherwise it is read-only.
*/
public void setSuperInterfaces(List interfacesNames, boolean canBeModified) {
fSuperInterfacesDialogField.setElements(interfacesNames);
fSuperInterfacesDialogField.setEnabled(canBeModified);
}
// ----------- validation ----------
/**
* A hook method that gets called when the package field has changed. The method
* validates the package name and returns the status of the validation. The validation
* also updates the package fragment model.
* <p>
* Subclasses may extend this method to perform their own validation.
* </p>
*
* @return the status of the validation
*/
protected IStatus packageChanged() {
StatusInfo status= new StatusInfo();
fPackageDialogField.enableButton(getPackageFragmentRoot() != null);
String packName= getPackageText();
if (packName.length() > 0) {
IStatus val= JavaConventions.validatePackageName(packName);
if (val.getSeverity() == IStatus.ERROR) {
status.setError(NewWizardMessages.getFormattedString("NewTypeWizardPage.error.InvalidPackageName", val.getMessage())); //$NON-NLS-1$
return status;
} else if (val.getSeverity() == IStatus.WARNING) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.DiscouragedPackageName", val.getMessage())); //$NON-NLS-1$
// continue
}
}
IPackageFragmentRoot root= getPackageFragmentRoot();
if (root != null) {
if (root.getJavaProject().exists() && packName.length() > 0) {
try {
IPath rootPath= root.getPath();
IPath outputPath= root.getJavaProject().getOutputLocation();
if (rootPath.isPrefixOf(outputPath) && !rootPath.equals(outputPath)) {
// if the bin folder is inside of our root, dont allow to name a package
// like the bin folder
IPath packagePath= rootPath.append(packName.replace('.', '/'));
if (outputPath.isPrefixOf(packagePath)) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.ClashOutputLocation")); //$NON-NLS-1$
return status;
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
// let pass
}
}
fCurrPackage= root.getPackageFragment(packName);
} else {
status.setError(""); //$NON-NLS-1$
}
return status;
}
/*
* Updates the 'default' label next to the package field.
*/
private void updatePackageStatusLabel() {
String packName= getPackageText();
if (packName.length() == 0) {
fPackageDialogField.setStatus(NewWizardMessages.getString("NewTypeWizardPage.default")); //$NON-NLS-1$
} else {
fPackageDialogField.setStatus(""); //$NON-NLS-1$
}
}
/*
* Updates the enable state of buttons related to the enclosing type selection checkbox.
*/
private void updateEnableState() {
boolean enclosing= isEnclosingTypeSelected();
fPackageDialogField.setEnabled(fCanModifyPackage && !enclosing);
fEnclosingTypeDialogField.setEnabled(fCanModifyEnclosingType && enclosing);
}
/**
* Hook method that gets called when the enclosing type name has changed. The method
* validates the enclosing type and returns the status of the validation. It also updates the
* enclosing type model.
* <p>
* Subclasses may extend this method to perform their own validation.
* </p>
*
* @return the status of the validation
*/
protected IStatus enclosingTypeChanged() {
StatusInfo status= new StatusInfo();
fCurrEnclosingType= null;
IPackageFragmentRoot root= getPackageFragmentRoot();
fEnclosingTypeDialogField.enableButton(root != null);
if (root == null) {
status.setError(""); //$NON-NLS-1$
return status;
}
String enclName= getEnclosingTypeText();
if (enclName.length() == 0) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeEnterName")); //$NON-NLS-1$
return status;
}
try {
IType type= root.getJavaProject().findType(enclName);
if (type == null) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeNotExists")); //$NON-NLS-1$
return status;
}
if (type.getCompilationUnit() == null) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingNotInCU")); //$NON-NLS-1$
return status;
}
if (!JavaModelUtil.isEditable(type.getCompilationUnit())) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingNotEditable")); //$NON-NLS-1$
return status;
}
fCurrEnclosingType= type;
IPackageFragmentRoot enclosingRoot= JavaModelUtil.getPackageFragmentRoot(type);
if (!enclosingRoot.equals(root)) {
status.setWarning(NewWizardMessages.getString("NewTypeWizardPage.warning.EnclosingNotInSourceFolder")); //$NON-NLS-1$
}
return status;
} catch (JavaModelException e) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeNotExists")); //$NON-NLS-1$
JavaPlugin.log(e);
return status;
}
}
/**
* Hook method that gets called when the type name has changed. The method validates the
* type name and returns the status of the validation.
* <p>
* Subclasses may extend this method to perform their own validation.
* </p>
*
* @return the status of the validation
*/
protected IStatus typeNameChanged() {
StatusInfo status= new StatusInfo();
String typeName= getTypeName();
// must not be empty
if (typeName.length() == 0) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnterTypeName")); //$NON-NLS-1$
return status;
}
if (typeName.indexOf('.') != -1) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.QualifiedName")); //$NON-NLS-1$
return status;
}
IStatus val= JavaConventions.validateJavaTypeName(typeName);
if (val.getSeverity() == IStatus.ERROR) {
status.setError(NewWizardMessages.getFormattedString("NewTypeWizardPage.error.InvalidTypeName", val.getMessage())); //$NON-NLS-1$
return status;
} else if (val.getSeverity() == IStatus.WARNING) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.TypeNameDiscouraged", val.getMessage())); //$NON-NLS-1$
// continue checking
}
// must not exist
if (!isEnclosingTypeSelected()) {
IPackageFragment pack= getPackageFragment();
if (pack != null) {
ICompilationUnit cu= pack.getCompilationUnit(typeName + ".java"); //$NON-NLS-1$
if (cu.exists()) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.TypeNameExists")); //$NON-NLS-1$
return status;
}
}
} else {
IType type= getEnclosingType();
if (type != null) {
IType member= type.getType(typeName);
if (member.exists()) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.TypeNameExists")); //$NON-NLS-1$
return status;
}
}
}
return status;
}
/**
* Hook method that gets called when the superclass name has changed. The method
* validates the superclass name and returns the status of the validation.
* <p>
* Subclasses may extend this method to perform their own validation.
* </p>
*
* @return the status of the validation
*/
protected IStatus superClassChanged() {
StatusInfo status= new StatusInfo();
IPackageFragmentRoot root= getPackageFragmentRoot();
fSuperClassDialogField.enableButton(root != null);
fSuperClass= null;
String sclassName= getSuperClass();
if (sclassName.length() == 0) {
// accept the empty field (stands for java.lang.Object)
return status;
}
IStatus val= JavaConventions.validateJavaTypeName(sclassName);
if (val.getSeverity() == IStatus.ERROR) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.InvalidSuperClassName")); //$NON-NLS-1$
return status;
}
if (root != null) {
try {
IType type= resolveSuperTypeName(root.getJavaProject(), sclassName);
if (type == null) {
status.setWarning(NewWizardMessages.getString("NewTypeWizardPage.warning.SuperClassNotExists")); //$NON-NLS-1$
return status;
} else {
if (type.isInterface()) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsNotClass", sclassName)); //$NON-NLS-1$
return status;
}
int flags= type.getFlags();
if (Flags.isFinal(flags)) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsFinal", sclassName)); //$NON-NLS-1$
return status;
} else if (!JavaModelUtil.isVisible(type, getPackageFragment())) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsNotVisible", sclassName)); //$NON-NLS-1$
return status;
}
}
fSuperClass= type;
} catch (JavaModelException e) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.InvalidSuperClassName")); //$NON-NLS-1$
JavaPlugin.log(e);
}
} else {
status.setError(""); //$NON-NLS-1$
}
return status;
}
private IType resolveSuperTypeName(IJavaProject jproject, String sclassName) throws JavaModelException {
IType type= null;
if (isEnclosingTypeSelected()) {
// search in the context of the enclosing type
IType enclosingType= getEnclosingType();
if (enclosingType != null) {
String[][] res= enclosingType.resolveType(sclassName);
if (res != null && res.length > 0) {
type= jproject.findType(res[0][0], res[0][1]);
}
}
} else {
IPackageFragment currPack= getPackageFragment();
if (type == null && currPack != null) {
String packName= currPack.getElementName();
// search in own package
if (!currPack.isDefaultPackage()) {
type= jproject.findType(packName, sclassName);
}
// search in java.lang
if (type == null && !"java.lang".equals(packName)) { //$NON-NLS-1$
type= jproject.findType("java.lang", sclassName); //$NON-NLS-1$
}
}
// search fully qualified
if (type == null) {
type= jproject.findType(sclassName);
}
}
return type;
}
/**
* Hook method that gets called when the list of super interface has changed. The method
* validates the superinterfaces and returns the status of the validation.
* <p>
* Subclasses may extend this method to perform their own validation.
* </p>
*
* @return the status of the validation
*/
protected IStatus superInterfacesChanged() {
StatusInfo status= new StatusInfo();
IPackageFragmentRoot root= getPackageFragmentRoot();
fSuperInterfacesDialogField.enableButton(0, root != null);
if (root != null) {
List elements= fSuperInterfacesDialogField.getElements();
int nElements= elements.size();
for (int i= 0; i < nElements; i++) {
String intfname= (String)elements.get(i);
try {
IType type= root.getJavaProject().findType(intfname);
if (type == null) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceNotExists", intfname)); //$NON-NLS-1$
return status;
} else {
if (type.isClass()) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceIsNotInterface", intfname)); //$NON-NLS-1$
return status;
}
if (!JavaModelUtil.isVisible(type, getPackageFragment())) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceIsNotVisible", intfname)); //$NON-NLS-1$
return status;
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
// let pass, checking is an extra
}
}
}
return status;
}
/**
* Hook method that gets called when the modifiers have changed. The method validates
* the modifiers and returns the status of the validation.
* <p>
* Subclasses may extend this method to perform their own validation.
* </p>
*
* @return the status of the validation
*/
protected IStatus modifiersChanged() {
StatusInfo status= new StatusInfo();
int modifiers= getModifiers();
if (Flags.isFinal(modifiers) && Flags.isAbstract(modifiers)) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.ModifiersFinalAndAbstract")); //$NON-NLS-1$
}
return status;
}
// selection dialogs
private IPackageFragment choosePackage() {
IPackageFragmentRoot froot= getPackageFragmentRoot();
IJavaElement[] packages= null;
try {
if (froot != null && froot.exists()) {
packages= froot.getChildren();
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
if (packages == null) {
packages= new IJavaElement[0];
}
ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT));
dialog.setIgnoreCase(false);
dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.title")); //$NON-NLS-1$
dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.description")); //$NON-NLS-1$
dialog.setEmptyListMessage(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.empty")); //$NON-NLS-1$
dialog.setElements(packages);
IPackageFragment pack= getPackageFragment();
if (pack != null) {
dialog.setInitialSelections(new Object[] { pack });
}
if (dialog.open() == ElementListSelectionDialog.OK) {
return (IPackageFragment) dialog.getFirstResult();
}
return null;
}
private IType chooseEnclosingType() {
IPackageFragmentRoot root= getPackageFragmentRoot();
if (root == null) {
return null;
}
IJavaSearchScope scope= SearchEngine.createJavaSearchScope(new IJavaElement[] { root });
TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(), getWizard().getContainer(), IJavaSearchConstants.TYPE, scope);
dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.ChooseEnclosingTypeDialog.title")); //$NON-NLS-1$
dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.ChooseEnclosingTypeDialog.description")); //$NON-NLS-1$
dialog.setFilter(Signature.getSimpleName(getEnclosingTypeText()));
if (dialog.open() == TypeSelectionDialog.OK) {
return (IType) dialog.getFirstResult();
}
return null;
}
private IType chooseSuperType() {
IPackageFragmentRoot root= getPackageFragmentRoot();
if (root == null) {
return null;
}
IJavaElement[] elements= new IJavaElement[] { root.getJavaProject() };
IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements);
TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(), getWizard().getContainer(), IJavaSearchConstants.CLASS, scope);
dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.SuperClassDialog.title")); //$NON-NLS-1$
dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.SuperClassDialog.message")); //$NON-NLS-1$
dialog.setFilter(getSuperClass());
if (dialog.open() == TypeSelectionDialog.OK) {
return (IType) dialog.getFirstResult();
}
return null;
}
private void chooseSuperInterfaces() {
IPackageFragmentRoot root= getPackageFragmentRoot();
if (root == null) {
return;
}
IJavaProject project= root.getJavaProject();
SuperInterfaceSelectionDialog dialog= new SuperInterfaceSelectionDialog(getShell(), getWizard().getContainer(), fSuperInterfacesDialogField, project);
dialog.setTitle(fIsClass ? NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.class.title") : NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.interface.title")); //$NON-NLS-1$ //$NON-NLS-2$
dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.message")); //$NON-NLS-1$
dialog.open();
return;
}
// ---- creation ----------------
/**
* Creates the new type using the entered field values.
*
* @param monitor a progress monitor to report progress.
*/
public void createType(IProgressMonitor monitor) throws CoreException, InterruptedException {
if (monitor == null) {
monitor= new NullProgressMonitor();
}
monitor.beginTask(NewWizardMessages.getString("NewTypeWizardPage.operationdesc"), 10); //$NON-NLS-1$
ICompilationUnit createdWorkingCopy= null;
try {
IPackageFragmentRoot root= getPackageFragmentRoot();
IPackageFragment pack= getPackageFragment();
if (pack == null) {
pack= root.getPackageFragment(""); //$NON-NLS-1$
}
if (!pack.exists()) {
String packName= pack.getElementName();
pack= root.createPackageFragment(packName, true, null);
}
monitor.worked(1);
String clName= getTypeName();
boolean isInnerClass= isEnclosingTypeSelected();
IType createdType;
ImportsStructure imports;
int indent= 0;
IPreferenceStore store= PreferenceConstants.getPreferenceStore();
String[] prefOrder= JavaPreferencesSettings.getImportOrderPreference(store);
int threshold= JavaPreferencesSettings.getImportNumberThreshold(store);
String lineDelimiter= null;
if (!isInnerClass) {
lineDelimiter= System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
String packStatement= pack.isDefaultPackage() ? "" : "package " + pack.getElementName() + ";" + lineDelimiter + lineDelimiter; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
ICompilationUnit parentCU= pack.createCompilationUnit(clName + ".java", "", false, new SubProgressMonitor(monitor, 2)); //$NON-NLS-1$
createdWorkingCopy= (ICompilationUnit) parentCU.getSharedWorkingCopy(null, JavaUI.getBufferFactory(), null);
createdWorkingCopy.getBuffer().setContents(packStatement);
imports= new ImportsStructure(createdWorkingCopy, prefOrder, threshold, false);
// add an import that will be removed again. Having this import solves 14661
imports.addImport(pack.getElementName(), getTypeName());
String content= constructTypeStub(new ImportsManager(imports), lineDelimiter, createdWorkingCopy);
createdType= createdWorkingCopy.createType(content, null, false, new SubProgressMonitor(monitor, 3));
} else {
IType enclosingType= getEnclosingType();
// if we are working on a enclosed type that is open in an editor,
// then replace the enclosing type with its working copy
IType workingCopy= (IType) EditorUtility.getWorkingCopy(enclosingType);
if (workingCopy != null) {
enclosingType= workingCopy;
}
ICompilationUnit parentCU= enclosingType.getCompilationUnit();
imports= new ImportsStructure(parentCU, prefOrder, threshold, true);
// add imports that will be removed again. Having the imports solves 14661
IType[] topLevelTypes= parentCU.getTypes();
for (int i= 0; i < topLevelTypes.length; i++) {
imports.addImport(topLevelTypes[i].getFullyQualifiedName('.'));
}
lineDelimiter= StubUtility.getLineDelimiterUsed(enclosingType);
String content= constructTypeStub(new ImportsManager(imports), lineDelimiter, parentCU);
IJavaElement[] elems= enclosingType.getChildren();
IJavaElement sibling= elems.length > 0 ? elems[0] : null;
createdType= enclosingType.createType(content, sibling, false, new SubProgressMonitor(monitor, 1));
indent= StubUtility.getIndentUsed(enclosingType) + 1;
}
// add imports for superclass/interfaces, so types can be resolved correctly
imports.create(false, new SubProgressMonitor(monitor, 1));
ICompilationUnit cu= createdType.getCompilationUnit();
synchronized(cu) {
cu.reconcile();
}
createTypeMembers(createdType, new ImportsManager(imports), new SubProgressMonitor(monitor, 1));
// add imports
imports.create(false, new SubProgressMonitor(monitor, 1));
synchronized(cu) {
cu.reconcile();
}
ISourceRange range= createdType.getSourceRange();
IBuffer buf= cu.getBuffer();
String originalContent= buf.getText(range.getOffset(), range.getLength());
String formattedContent= StubUtility.codeFormat(originalContent, indent, lineDelimiter);
buf.replace(range.getOffset(), range.getLength(), formattedContent);
if (!isInnerClass) {
String fileComment= getFileComment(cu);
if (fileComment != null && fileComment.length() > 0) {
buf.replace(0, 0, fileComment + lineDelimiter);
}
cu.commit(false, new SubProgressMonitor(monitor, 1));
} else {
monitor.worked(1);
}
fCreatedType= createdType;
} finally {
if (createdWorkingCopy != null) {
createdWorkingCopy.destroy();
}
monitor.done();
}
}
/**
* Returns the created type. The method only returns a valid type
* after <code>createType</code> has been called.
*
* @return the created type
* @see #createType(IProgressMonitor)
*/
public IType getCreatedType() {
return fCreatedType;
}
// ---- construct cu body----------------
private void writeSuperClass(StringBuffer buf, ImportsManager imports) {
String typename= getSuperClass();
if (fIsClass && typename.length() > 0 && !"java.lang.Object".equals(typename)) { //$NON-NLS-1$
buf.append(" extends "); //$NON-NLS-1$
String qualifiedName= fSuperClass != null ? JavaModelUtil.getFullyQualifiedName(fSuperClass) : typename;
buf.append(imports.addImport(qualifiedName));
}
}
private void writeSuperInterfaces(StringBuffer buf, ImportsManager imports) {
List interfaces= getSuperInterfaces();
int last= interfaces.size() - 1;
if (last >= 0) {
if (fIsClass) {
buf.append(" implements "); //$NON-NLS-1$
} else {
buf.append(" extends "); //$NON-NLS-1$
}
for (int i= 0; i <= last; i++) {
String typename= (String) interfaces.get(i);
buf.append(imports.addImport(typename));
if (i < last) {
buf.append(',');
}
}
}
}
/*
* Called from createType to construct the source for this type
*/
private String constructTypeStub(ImportsManager imports, String lineDelimiter, ICompilationUnit parentCU) {
StringBuffer buf= new StringBuffer();
String typeComment= getTypeComment(parentCU);
if (typeComment != null && typeComment.length() > 0) {
buf.append(typeComment);
buf.append(lineDelimiter);
}
int modifiers= getModifiers();
buf.append(Flags.toString(modifiers));
if (modifiers != 0) {
buf.append(' ');
}
buf.append(fIsClass ? "class " : "interface "); //$NON-NLS-2$ //$NON-NLS-1$
buf.append(getTypeName());
writeSuperClass(buf, imports);
writeSuperInterfaces(buf, imports);
buf.append('{');
buf.append(lineDelimiter);
buf.append(lineDelimiter);
buf.append('}');
buf.append(lineDelimiter);
return buf.toString();
}
/**
* @deprecated Overwrite createTypeMembers(IType, IImportsManager, IProgressMonitor) instead
*/
protected void createTypeMembers(IType newType, IImportsStructure imports, IProgressMonitor monitor) throws CoreException {
//deprecated
}
/**
* Hook method that gets called from <code>createType</code> to support adding of
* unanticipated methods, fields, and inner types to the created type.
* <p>
* Implementers can use any methods defined on <code>IType</code> to manipulate the
* new type.
* </p>
* <p>
* The source code of the new type will be formtted using the platform's formatter. Needed
* imports are added by the wizard at the end of the type creation process using the given
* import manager.
* </p>
*
* @param newType the new type created via <code>createType</code>
* @param imports an import manager which can be used to add new imports
* @param monitor a progress monitor to report progress. Must not be <code>null</code>
*
* @see #createType(IProgressMonitor)
*/
protected void createTypeMembers(IType newType, ImportsManager imports, IProgressMonitor monitor) throws CoreException {
// call for compatibility
createTypeMembers(newType, ((ImportsManager)imports).getImportsStructure(), monitor);
// default implementation does nothing
// example would be
// String mainMathod= "public void foo(Vector vec) {}"
// createdType.createMethod(main, null, false, null);
// imports.addImport("java.lang.Vector");
}
/**
* Hook mathod that gets called from <code>createType</code> to retrieve
* a file comment. This default implementation returns the content of the
* 'filecomment' template.
*
* @return the file comment or <code>null</code> if a file comment
* is not desired
*/
protected String getFileComment(ICompilationUnit parentCU) {
if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.CODEGEN__FILE_COMMENTS)) {
String template= getTemplate("filecomment", parentCU, 0); //$NON-NLS-1$
if (isValidComment(template)) {
return template;
}
}
return null;
}
private boolean isValidComment(String template) {
IScanner scanner= ToolFactory.createScanner(true, false, false, false);
scanner.setSource(template.toCharArray());
try {
int next= scanner.getNextToken();
while (next == ITerminalSymbols.TokenNameCOMMENT_LINE || next == ITerminalSymbols.TokenNameCOMMENT_JAVADOC || next == ITerminalSymbols.TokenNameCOMMENT_BLOCK) {
next= scanner.getNextToken();
}
return next == ITerminalSymbols.TokenNameEOF;
} catch (InvalidInputException e) {
}
return false;
}
/**
* Hook method that gets called from <code>createType</code> to retrieve
* a type comment. This default implementation returns the content of the
* 'typecomment' template.
*
* @return the type comment or <code>null</code> if a type comment
* is not desired
*/
protected String getTypeComment(ICompilationUnit parentCU) {
if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.CODEGEN__JAVADOC_STUBS)) {
String template= getTemplate("typecomment", parentCU, 0); //$NON-NLS-1$
if (isValidComment(template)) {
return template;
}
}
return null;
}
/**
* @deprecated Use getTemplate(String,ICompilationUnit,int)
*/
protected String getTemplate(String name, ICompilationUnit parentCU) {
return getTemplate(name, parentCU, 0);
}
/**
* Returns the string resulting from evaluation the given template in
* the context of the given compilation unit.
*
* @param name the template to be evaluated
* @param parentCU the templates evaluation context
* @param pos a source offset into the parent compilation unit. The
* template is evalutated at the given source offset
*/
protected String getTemplate(String name, ICompilationUnit parentCU, int pos) {
try {
Template[] templates= Templates.getInstance().getTemplates(name);
if (templates.length > 0) {
return JavaContext.evaluateTemplate(templates[0], parentCU, pos);
}
} catch (CoreException e) {
JavaPlugin.log(e);
}
return null;
}
/**
* @deprecated Use createInheritedMethods(IType,boolean,boolean,IImportsManager,IProgressMonitor)
*/
protected IMethod[] createInheritedMethods(IType type, boolean doConstructors, boolean doUnimplementedMethods, IImportsStructure imports, IProgressMonitor monitor) throws CoreException {
return createInheritedMethods(type, doConstructors, doUnimplementedMethods, new ImportsManager(imports), monitor);
}
/**
* Creates the bodies of all unimplemented methods and constructors and adds them to the type.
* Method is typically called by implementers of <code>NewTypeWizardPage</code> to add
* needed method and constructors.
*
* @param type the type for which the new methods and constructor are to be created
* @param doConstructors if <code>true</code> unimplemented constructors are created
* @param doUnimplementedMethods if <code>true</code> unimplemented methods are created
* @param imports an import manager to add all neded import statements
* @param monitor a progress monitor to report progress
*/
protected IMethod[] createInheritedMethods(IType type, boolean doConstructors, boolean doUnimplementedMethods, ImportsManager imports, IProgressMonitor monitor) throws CoreException {
ArrayList newMethods= new ArrayList();
ITypeHierarchy hierarchy= type.newSupertypeHierarchy(monitor);
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
if (doConstructors) {
IType superclass= hierarchy.getSuperclass(type);
if (superclass != null) {
String[] constructors= StubUtility.evalConstructors(type, superclass, settings, imports.getImportsStructure());
if (constructors != null) {
for (int i= 0; i < constructors.length; i++) {
newMethods.add(constructors[i]);
}
}
}
}
if (doUnimplementedMethods) {
String[] unimplemented= StubUtility.evalUnimplementedMethods(type, hierarchy, false, settings, null, imports.getImportsStructure());
if (unimplemented != null) {
for (int i= 0; i < unimplemented.length; i++) {
newMethods.add(unimplemented[i]);
}
}
}
IMethod[] createdMethods= new IMethod[newMethods.size()];
for (int i= 0; i < newMethods.size(); i++) {
String content= (String) newMethods.get(i) + '\n'; // content will be formatted, ok to use \n
createdMethods[i]= type.createMethod(content, null, false, null);
}
return createdMethods;
}
// ---- creation ----------------
/**
* Returns the runnable that creates the type using the current settings.
* The returned runnable must be executed in the UI thread.
*
* @return the runnable to create the new type
*/
public IRunnableWithProgress getRunnable() {
return new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
try {
if (monitor == null) {
monitor= new NullProgressMonitor();
}
createType(monitor);
} catch (CoreException e) {
throw new InvocationTargetException(e);
}
}
};
}
}
|
29,500 |
Bug 29500 Cannot cancel organize imports
|
After selecting organize imports on my project (to reduce the 4175 warnings about unused imports I got when I upgraded to 2.1 M4), I decided that maybe this was going to take longer than I thought, so I tried to cancel the action. The cancel button on the dialog didn't to do anything. I can repeat this at will with my project. I'm using Sun's JDK 1.4.1_01 on Debian GNU/Linux, SWT/Motif.
|
resolved fixed
|
b3d6599
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-15T11:09:58Z | 2003-01-15T05:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/OrganizeImportsAction.java
|
/*******************************************************************************
* Copyright (c) 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.ui.actions;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.ui.IEditorActionBarContributor;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.EditorActionBarContributor;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.internal.corext.ValidateEditException;
import org.eclipse.jdt.internal.corext.codemanipulation.OrganizeImportsOperation;
import org.eclipse.jdt.internal.corext.codemanipulation.OrganizeImportsOperation.IChooseImportQuery;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.corext.util.TypeInfo;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.ActionMessages;
import org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter;
import org.eclipse.jdt.internal.ui.dialogs.MultiElementListSelectionDialog;
import org.eclipse.jdt.internal.ui.dialogs.ProblemDialog;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext;
import org.eclipse.jdt.internal.ui.util.ElementValidator;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.util.TypeInfoLabelProvider;
import org.eclipse.jdt.ui.IWorkingCopyManager;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
/**
* Organizes the imports of a compilation unit.
* <p>
* The action is applicable to selections containing elements of
* type <code>ICompilationUnit</code> or <code>IPackage
* </code>.
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 2.0
*/
public class OrganizeImportsAction extends SelectionDispatchAction {
private JavaEditor fEditor;
/* (non-Javadoc)
* Class implements IObjectActionDelegate
*/
public static class ObjectDelegate implements IObjectActionDelegate {
private OrganizeImportsAction fAction;
public void setActivePart(IAction action, IWorkbenchPart targetPart) {
fAction= new OrganizeImportsAction(targetPart.getSite());
}
public void run(IAction action) {
fAction.run();
}
public void selectionChanged(IAction action, ISelection selection) {
if (fAction == null)
action.setEnabled(false);
}
}
/**
* Creates a new <code>OrganizeImportsAction</code>. The action requires
* that the selection provided by the site's selection provider is of type <code>
* org.eclipse.jface.viewers.IStructuredSelection</code>.
*
* @param site the site providing context information for this action
*/
public OrganizeImportsAction(IWorkbenchSite site) {
super(site);
setText(ActionMessages.getString("OrganizeImportsAction.label")); //$NON-NLS-1$
setToolTipText(ActionMessages.getString("OrganizeImportsAction.tooltip")); //$NON-NLS-1$
setDescription(ActionMessages.getString("OrganizeImportsAction.description")); //$NON-NLS-1$
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.ORGANIZE_IMPORTS_ACTION);
}
/**
* Note: This constructor is for internal use only. Clients should not call this constructor.
*/
public OrganizeImportsAction(JavaEditor editor) {
this(editor.getEditorSite());
fEditor= editor;
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
protected void selectionChanged(ITextSelection selection) {
// do nothing
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
protected void selectionChanged(IStructuredSelection selection) {
setEnabled(isEnabled(selection));
}
private ICompilationUnit[] getCompilationUnits(IStructuredSelection selection) {
HashSet result= new HashSet();
Object[] selected= selection.toArray();
for (int i= 0; i < selected.length; i++) {
try {
if (selected[i] instanceof IJavaElement) {
IJavaElement elem= (IJavaElement) selected[i];
switch (elem.getElementType()) {
case IJavaElement.COMPILATION_UNIT:
result.add(elem);
break;
case IJavaElement.IMPORT_CONTAINER:
result.add(elem.getParent());
break;
case IJavaElement.PACKAGE_FRAGMENT:
collectCompilationUnits((IPackageFragment) elem, result);
break;
case IJavaElement.PACKAGE_FRAGMENT_ROOT:
collectCompilationUnits((IPackageFragmentRoot) elem, result);
break;
case IJavaElement.JAVA_PROJECT:
IPackageFragmentRoot[] roots= ((IJavaProject) elem).getPackageFragmentRoots();
for (int k= 0; k < roots.length; k++) {
collectCompilationUnits(roots[i], result);
}
break;
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
return (ICompilationUnit[]) result.toArray(new ICompilationUnit[result.size()]);
}
private void collectCompilationUnits(IPackageFragment pack, Collection result) throws JavaModelException {
result.addAll(Arrays.asList(pack.getCompilationUnits()));
}
private void collectCompilationUnits(IPackageFragmentRoot root, Collection result) throws JavaModelException {
if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
IJavaElement[] children= root.getChildren();
for (int i= 0; i < children.length; i++) {
collectCompilationUnits((IPackageFragment) children[i], result);
}
}
}
private boolean isEnabled(IStructuredSelection selection) {
Object[] selected= selection.toArray();
for (int i= 0; i < selected.length; i++) {
try {
if (selected[i] instanceof IJavaElement) {
IJavaElement elem= (IJavaElement) selected[i];
switch (elem.getElementType()) {
case IJavaElement.COMPILATION_UNIT:
return true;
case IJavaElement.IMPORT_CONTAINER:
return true;
case IJavaElement.PACKAGE_FRAGMENT:
case IJavaElement.PACKAGE_FRAGMENT_ROOT:
IPackageFragmentRoot root= (IPackageFragmentRoot) elem.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
return (root.getKind() == IPackageFragmentRoot.K_SOURCE);
case IJavaElement.JAVA_PROJECT:
return hasSourceFolders((IJavaProject) elem);
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
return false;
}
private boolean hasSourceFolders(IJavaProject project) throws JavaModelException {
IPackageFragmentRoot[] roots= project.getPackageFragmentRoots();
for (int i= 0; i < roots.length; i++) {
IPackageFragmentRoot root= roots[i];
if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
return true;
}
}
return false;
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
protected void run(ITextSelection selection) {
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
ICompilationUnit cu= manager.getWorkingCopy(fEditor.getEditorInput());
runOnSingle(cu, true, true);
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
protected void run(IStructuredSelection selection) {
ICompilationUnit[] cus= getCompilationUnits(selection);
if (cus.length == 1) {
runOnSingle(cus[0], true, false);
} else {
runOnMultiple(cus, true);
}
}
private void runOnMultiple(final ICompilationUnit[] cus, final boolean doResolve) {
try {
String message= ActionMessages.getString("OrganizeImportsAction.multi.status.description"); //$NON-NLS-1$
final MultiStatus status= new MultiStatus(JavaUI.ID_PLUGIN, Status.OK, message, null);
ProgressMonitorDialog dialog= new ProgressMonitorDialog(getShell());
dialog.run(false, true, new WorkbenchRunnableAdapter(new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) {
doRunOnMultiple(cus, status, doResolve, monitor);
}
}));
if (!status.isOK()) {
String title= ActionMessages.getString("OrganizeImportsAction.multi.status.title"); //$NON-NLS-1$
ProblemDialog.open(getShell(), title, null, status);
}
} catch (InvocationTargetException e) {
ExceptionHandler.handle(e, getShell(), ActionMessages.getString("OrganizeImportsAction.error.title"), ActionMessages.getString("OrganizeImportsAction.error.message")); //$NON-NLS-1$ //$NON-NLS-2$
} catch (InterruptedException e) {
// cancelled by user
}
}
private void doRunOnMultiple(ICompilationUnit[] cus, MultiStatus status, boolean doResolve, IProgressMonitor monitor) throws OperationCanceledException {
final class OrganizeImportError extends Error {
}
if (monitor == null) {
monitor= new NullProgressMonitor();
}
monitor.beginTask(ActionMessages.getString("OrganizeImportsAction.multi.op.description"), cus.length); //$NON-NLS-1$
try {
IPreferenceStore store= PreferenceConstants.getPreferenceStore();
String[] prefOrder= JavaPreferencesSettings.getImportOrderPreference(store);
int threshold= JavaPreferencesSettings.getImportNumberThreshold(store);
boolean ignoreLowerCaseNames= store.getBoolean(PreferenceConstants.ORGIMPORTS_IGNORELOWERCASE);
IChooseImportQuery query= new IChooseImportQuery() {
public TypeInfo[] chooseImports(TypeInfo[][] openChoices, ISourceRange[] ranges) {
throw new OrganizeImportError();
}
};
for (int i= 0; i < cus.length; i++) {
ICompilationUnit cu= cus[i];
String cuLocation= cu.getPath().makeRelative().toString();
try {
cu= JavaModelUtil.toWorkingCopy(cu);
monitor.subTask(cuLocation);
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, prefOrder, threshold, ignoreLowerCaseNames, !cu.isWorkingCopy(), doResolve, query);
op.run(new SubProgressMonitor(monitor, 1));
if (monitor.isCanceled()) {
throw new OperationCanceledException();
}
IProblem parseError= op.getParseError();
if (parseError != null) {
String message= ActionMessages.getFormattedString("OrganizeImportsAction.multi.error.parse", cuLocation); //$NON-NLS-1$
status.add(new Status(Status.INFO, JavaUI.ID_PLUGIN, Status.ERROR, message, null));
}
} catch (OrganizeImportError e) {
String message= ActionMessages.getFormattedString("OrganizeImportsAction.multi.error.unresolvable", cuLocation); //$NON-NLS-1$
status.add(new Status(Status.INFO, JavaUI.ID_PLUGIN, Status.ERROR, message, null));
} catch (ValidateEditException e) {
status.add(e.getStatus());
} catch (CoreException e) {
JavaPlugin.log(e);
String message= ActionMessages.getFormattedString("OrganizeImportsAction.multi.error.unexpected", e.getStatus().getMessage()); //$NON-NLS-1$
status.add(new Status(Status.ERROR, JavaUI.ID_PLUGIN, Status.ERROR, message, null));
}
}
} finally {
monitor.done();
}
}
private void runOnSingle(ICompilationUnit cu, boolean doResolve, boolean inEditor) {
if (!ElementValidator.check(cu, getShell(), ActionMessages.getString("OrganizeImportsAction.error.title"), inEditor)) //$NON-NLS-1$
return;
try {
IPreferenceStore store= PreferenceConstants.getPreferenceStore();
String[] prefOrder= JavaPreferencesSettings.getImportOrderPreference(store);
int threshold= JavaPreferencesSettings.getImportNumberThreshold(store);
boolean ignoreLowerCaseNames= store.getBoolean(PreferenceConstants.ORGIMPORTS_IGNORELOWERCASE);
if (!cu.isWorkingCopy()) {
IEditorPart editor= EditorUtility.openInEditor(cu);
if (editor instanceof JavaEditor) {
fEditor= (JavaEditor) editor;
}
cu= JavaModelUtil.toWorkingCopy(cu);
}
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, prefOrder, threshold, ignoreLowerCaseNames, !cu.isWorkingCopy(), doResolve, createChooseImportQuery());
BusyIndicatorRunnableContext context= new BusyIndicatorRunnableContext();
context.run(false, true, new WorkbenchRunnableAdapter(op));
IProblem parseError= op.getParseError();
if (parseError != null) {
String message= ActionMessages.getFormattedString("OrganizeImportsAction.single.error.parse", parseError.getMessage()); //$NON-NLS-1$
MessageDialog.openInformation(getShell(), ActionMessages.getString("OrganizeImportsAction.error.title"), message); //$NON-NLS-1$
if (fEditor != null && parseError.getSourceStart() != -1) {
fEditor.selectAndReveal(parseError.getSourceStart(), parseError.getSourceEnd() - parseError.getSourceStart() + 1);
}
} else {
if (fEditor != null) {
setStatusBarMessage(getOrganizeInfo(op));
}
}
} catch (CoreException e) {
ExceptionHandler.handle(e, getShell(), ActionMessages.getString("OrganizeImportsAction.error.title"), ActionMessages.getString("OrganizeImportsAction.error.message")); //$NON-NLS-1$ //$NON-NLS-2$
} catch (InvocationTargetException e) {
ExceptionHandler.handle(e, getShell(), ActionMessages.getString("OrganizeImportsAction.error.title"), ActionMessages.getString("OrganizeImportsAction.error.message")); //$NON-NLS-1$ //$NON-NLS-2$
} catch (InterruptedException e) {
}
}
private String getOrganizeInfo(OrganizeImportsOperation op) {
int nImportsAdded= op.getNumberOfImportsAdded();
if (nImportsAdded >= 0) {
return ActionMessages.getFormattedString("OrganizeImportsAction.summary_added", String.valueOf(nImportsAdded)); //$NON-NLS-1$
} else {
return ActionMessages.getFormattedString("OrganizeImportsAction.summary_removed", String.valueOf(-nImportsAdded)); //$NON-NLS-1$
}
}
private IChooseImportQuery createChooseImportQuery() {
return new IChooseImportQuery() {
public TypeInfo[] chooseImports(TypeInfo[][] openChoices, ISourceRange[] ranges) {
return doChooseImports(openChoices, ranges);
}
};
}
private TypeInfo[] doChooseImports(TypeInfo[][] openChoices, final ISourceRange[] ranges) {
// remember selection
ISelection sel= fEditor.getSelectionProvider().getSelection();
TypeInfo[] result= null;;
ILabelProvider labelProvider= new TypeInfoLabelProvider(TypeInfoLabelProvider.SHOW_FULLYQUALIFIED);
MultiElementListSelectionDialog dialog= new MultiElementListSelectionDialog(getShell(), labelProvider) {
protected void handleSelectionChanged() {
super.handleSelectionChanged();
// show choices in editor
doListSelectionChanged(getCurrentPage(), ranges);
}
};
dialog.setTitle(ActionMessages.getString("OrganizeImportsAction.selectiondialog.title")); //$NON-NLS-1$
dialog.setMessage(ActionMessages.getString("OrganizeImportsAction.selectiondialog.message")); //$NON-NLS-1$
dialog.setElements(openChoices);
if (dialog.open() == Window.OK) {
Object[] res= dialog.getResult();
result= new TypeInfo[res.length];
for (int i= 0; i < res.length; i++) {
Object[] array= (Object[]) res[i];
if (array.length > 0)
result[i]= (TypeInfo) array[0];
}
}
// restore selection
if (sel instanceof ITextSelection) {
ITextSelection textSelection= (ITextSelection) sel;
fEditor.selectAndReveal(textSelection.getOffset(), textSelection.getLength());
}
return result;
}
private void doListSelectionChanged(int page, ISourceRange[] ranges) {
if (page >= 0 && page < ranges.length) {
ISourceRange range= ranges[page];
fEditor.selectAndReveal(range.getOffset(), range.getLength());
}
}
private void setStatusBarMessage(String message) {
IEditorActionBarContributor contributor= fEditor.getEditorSite().getActionBarContributor();
if (contributor instanceof EditorActionBarContributor) {
IStatusLineManager manager= ((EditorActionBarContributor) contributor).getActionBars().getStatusLineManager();
manager.setMessage(message);
}
}
}
|
28,443 |
Bug 28443 organize imports sometimes added to logical packages, sometimes not
|
20021216 select a logical package - 'organize imports' is not in the context menu select the logical package and another package - organize imports is in the menu
|
resolved fixed
|
5cd6316
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-15T16:24:56Z | 2002-12-17T10:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/OrganizeImportsAction.java
|
/*******************************************************************************
* Copyright (c) 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.ui.actions;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.ui.IEditorActionBarContributor;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.EditorActionBarContributor;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.ui.IWorkingCopyManager;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.corext.ValidateEditException;
import org.eclipse.jdt.internal.corext.codemanipulation.OrganizeImportsOperation;
import org.eclipse.jdt.internal.corext.codemanipulation.OrganizeImportsOperation.IChooseImportQuery;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.corext.util.TypeInfo;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.ActionMessages;
import org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter;
import org.eclipse.jdt.internal.ui.dialogs.MultiElementListSelectionDialog;
import org.eclipse.jdt.internal.ui.dialogs.ProblemDialog;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext;
import org.eclipse.jdt.internal.ui.util.ElementValidator;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.util.TypeInfoLabelProvider;
/**
* Organizes the imports of a compilation unit.
* <p>
* The action is applicable to selections containing elements of
* type <code>ICompilationUnit</code> or <code>IPackage
* </code>.
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 2.0
*/
public class OrganizeImportsAction extends SelectionDispatchAction {
private JavaEditor fEditor;
/* (non-Javadoc)
* Class implements IObjectActionDelegate
*/
public static class ObjectDelegate implements IObjectActionDelegate {
private OrganizeImportsAction fAction;
public void setActivePart(IAction action, IWorkbenchPart targetPart) {
fAction= new OrganizeImportsAction(targetPart.getSite());
}
public void run(IAction action) {
fAction.run();
}
public void selectionChanged(IAction action, ISelection selection) {
if (fAction == null)
action.setEnabled(false);
}
}
/**
* Creates a new <code>OrganizeImportsAction</code>. The action requires
* that the selection provided by the site's selection provider is of type <code>
* org.eclipse.jface.viewers.IStructuredSelection</code>.
*
* @param site the site providing context information for this action
*/
public OrganizeImportsAction(IWorkbenchSite site) {
super(site);
setText(ActionMessages.getString("OrganizeImportsAction.label")); //$NON-NLS-1$
setToolTipText(ActionMessages.getString("OrganizeImportsAction.tooltip")); //$NON-NLS-1$
setDescription(ActionMessages.getString("OrganizeImportsAction.description")); //$NON-NLS-1$
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.ORGANIZE_IMPORTS_ACTION);
}
/**
* Note: This constructor is for internal use only. Clients should not call this constructor.
*/
public OrganizeImportsAction(JavaEditor editor) {
this(editor.getEditorSite());
fEditor= editor;
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
protected void selectionChanged(ITextSelection selection) {
// do nothing
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
protected void selectionChanged(IStructuredSelection selection) {
setEnabled(isEnabled(selection));
}
private ICompilationUnit[] getCompilationUnits(IStructuredSelection selection) {
HashSet result= new HashSet();
Object[] selected= selection.toArray();
for (int i= 0; i < selected.length; i++) {
try {
if (selected[i] instanceof IJavaElement) {
IJavaElement elem= (IJavaElement) selected[i];
switch (elem.getElementType()) {
case IJavaElement.COMPILATION_UNIT:
result.add(elem);
break;
case IJavaElement.IMPORT_CONTAINER:
result.add(elem.getParent());
break;
case IJavaElement.PACKAGE_FRAGMENT:
collectCompilationUnits((IPackageFragment) elem, result);
break;
case IJavaElement.PACKAGE_FRAGMENT_ROOT:
collectCompilationUnits((IPackageFragmentRoot) elem, result);
break;
case IJavaElement.JAVA_PROJECT:
IPackageFragmentRoot[] roots= ((IJavaProject) elem).getPackageFragmentRoots();
for (int k= 0; k < roots.length; k++) {
collectCompilationUnits(roots[i], result);
}
break;
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
return (ICompilationUnit[]) result.toArray(new ICompilationUnit[result.size()]);
}
private void collectCompilationUnits(IPackageFragment pack, Collection result) throws JavaModelException {
result.addAll(Arrays.asList(pack.getCompilationUnits()));
}
private void collectCompilationUnits(IPackageFragmentRoot root, Collection result) throws JavaModelException {
if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
IJavaElement[] children= root.getChildren();
for (int i= 0; i < children.length; i++) {
collectCompilationUnits((IPackageFragment) children[i], result);
}
}
}
private boolean isEnabled(IStructuredSelection selection) {
Object[] selected= selection.toArray();
for (int i= 0; i < selected.length; i++) {
try {
if (selected[i] instanceof IJavaElement) {
IJavaElement elem= (IJavaElement) selected[i];
switch (elem.getElementType()) {
case IJavaElement.COMPILATION_UNIT:
return true;
case IJavaElement.IMPORT_CONTAINER:
return true;
case IJavaElement.PACKAGE_FRAGMENT:
case IJavaElement.PACKAGE_FRAGMENT_ROOT:
IPackageFragmentRoot root= (IPackageFragmentRoot) elem.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
return (root.getKind() == IPackageFragmentRoot.K_SOURCE);
case IJavaElement.JAVA_PROJECT:
return hasSourceFolders((IJavaProject) elem);
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
return false;
}
private boolean hasSourceFolders(IJavaProject project) throws JavaModelException {
IPackageFragmentRoot[] roots= project.getPackageFragmentRoots();
for (int i= 0; i < roots.length; i++) {
IPackageFragmentRoot root= roots[i];
if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
return true;
}
}
return false;
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
protected void run(ITextSelection selection) {
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
ICompilationUnit cu= manager.getWorkingCopy(fEditor.getEditorInput());
runOnSingle(cu, true, true);
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
protected void run(IStructuredSelection selection) {
ICompilationUnit[] cus= getCompilationUnits(selection);
if (cus.length == 1) {
runOnSingle(cus[0], true, false);
} else {
runOnMultiple(cus, true);
}
}
private void runOnMultiple(final ICompilationUnit[] cus, final boolean doResolve) {
try {
String message= ActionMessages.getString("OrganizeImportsAction.multi.status.description"); //$NON-NLS-1$
final MultiStatus status= new MultiStatus(JavaUI.ID_PLUGIN, Status.OK, message, null);
ProgressMonitorDialog dialog= new ProgressMonitorDialog(getShell());
dialog.run(true, true, new WorkbenchRunnableAdapter(new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) {
doRunOnMultiple(cus, status, doResolve, monitor);
}
}));
if (!status.isOK()) {
String title= ActionMessages.getString("OrganizeImportsAction.multi.status.title"); //$NON-NLS-1$
ProblemDialog.open(getShell(), title, null, status);
}
} catch (InvocationTargetException e) {
ExceptionHandler.handle(e, getShell(), ActionMessages.getString("OrganizeImportsAction.error.title"), ActionMessages.getString("OrganizeImportsAction.error.message")); //$NON-NLS-1$ //$NON-NLS-2$
} catch (InterruptedException e) {
// cancelled by user
}
}
static final class OrganizeImportError extends Error {
}
private void doRunOnMultiple(ICompilationUnit[] cus, MultiStatus status, boolean doResolve, IProgressMonitor monitor) throws OperationCanceledException {
if (monitor == null) {
monitor= new NullProgressMonitor();
}
monitor.beginTask(ActionMessages.getString("OrganizeImportsAction.multi.op.description"), cus.length); //$NON-NLS-1$
try {
IPreferenceStore store= PreferenceConstants.getPreferenceStore();
String[] prefOrder= JavaPreferencesSettings.getImportOrderPreference(store);
int threshold= JavaPreferencesSettings.getImportNumberThreshold(store);
boolean ignoreLowerCaseNames= store.getBoolean(PreferenceConstants.ORGIMPORTS_IGNORELOWERCASE);
IChooseImportQuery query= new IChooseImportQuery() {
public TypeInfo[] chooseImports(TypeInfo[][] openChoices, ISourceRange[] ranges) {
throw new OrganizeImportError();
}
};
for (int i= 0; i < cus.length; i++) {
ICompilationUnit cu= cus[i];
String cuLocation= cu.getPath().makeRelative().toString();
cu= JavaModelUtil.toWorkingCopy(cu);
monitor.subTask(cuLocation);
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, prefOrder, threshold, ignoreLowerCaseNames, !cu.isWorkingCopy(), doResolve, query);
runInSync(op, cuLocation, status, monitor);
if (monitor.isCanceled()) {
throw new OperationCanceledException();
}
IProblem parseError= op.getParseError();
if (parseError != null) {
String message= ActionMessages.getFormattedString("OrganizeImportsAction.multi.error.parse", cuLocation); //$NON-NLS-1$
status.add(new Status(Status.INFO, JavaUI.ID_PLUGIN, Status.ERROR, message, null));
}
}
} finally {
monitor.done();
}
}
private void runInSync(final OrganizeImportsOperation op, final String cuLocation, final MultiStatus status, final IProgressMonitor monitor) {
Runnable runnable= new Runnable() {
public void run() {
try {
op.run(new SubProgressMonitor(monitor, 1));
} catch (ValidateEditException e) {
status.add(e.getStatus());
} catch (CoreException e) {
JavaPlugin.log(e);
String message= ActionMessages.getFormattedString("OrganizeImportsAction.multi.error.unexpected", e.getStatus().getMessage()); //$NON-NLS-1$
status.add(new Status(Status.ERROR, JavaUI.ID_PLUGIN, Status.ERROR, message, null));
} catch (OrganizeImportError e) {
String message= ActionMessages.getFormattedString("OrganizeImportsAction.multi.error.unresolvable", cuLocation); //$NON-NLS-1$
status.add(new Status(Status.INFO, JavaUI.ID_PLUGIN, Status.ERROR, message, null));
}
}
};
getShell().getDisplay().syncExec(runnable);
}
private void runOnSingle(ICompilationUnit cu, boolean doResolve, boolean inEditor) {
if (!ElementValidator.check(cu, getShell(), ActionMessages.getString("OrganizeImportsAction.error.title"), inEditor)) //$NON-NLS-1$
return;
try {
IPreferenceStore store= PreferenceConstants.getPreferenceStore();
String[] prefOrder= JavaPreferencesSettings.getImportOrderPreference(store);
int threshold= JavaPreferencesSettings.getImportNumberThreshold(store);
boolean ignoreLowerCaseNames= store.getBoolean(PreferenceConstants.ORGIMPORTS_IGNORELOWERCASE);
if (!cu.isWorkingCopy()) {
IEditorPart editor= EditorUtility.openInEditor(cu);
if (editor instanceof JavaEditor) {
fEditor= (JavaEditor) editor;
}
cu= JavaModelUtil.toWorkingCopy(cu);
}
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, prefOrder, threshold, ignoreLowerCaseNames, !cu.isWorkingCopy(), doResolve, createChooseImportQuery());
BusyIndicatorRunnableContext context= new BusyIndicatorRunnableContext();
context.run(false, true, new WorkbenchRunnableAdapter(op));
IProblem parseError= op.getParseError();
if (parseError != null) {
String message= ActionMessages.getFormattedString("OrganizeImportsAction.single.error.parse", parseError.getMessage()); //$NON-NLS-1$
MessageDialog.openInformation(getShell(), ActionMessages.getString("OrganizeImportsAction.error.title"), message); //$NON-NLS-1$
if (fEditor != null && parseError.getSourceStart() != -1) {
fEditor.selectAndReveal(parseError.getSourceStart(), parseError.getSourceEnd() - parseError.getSourceStart() + 1);
}
} else {
if (fEditor != null) {
setStatusBarMessage(getOrganizeInfo(op));
}
}
} catch (CoreException e) {
ExceptionHandler.handle(e, getShell(), ActionMessages.getString("OrganizeImportsAction.error.title"), ActionMessages.getString("OrganizeImportsAction.error.message")); //$NON-NLS-1$ //$NON-NLS-2$
} catch (InvocationTargetException e) {
ExceptionHandler.handle(e, getShell(), ActionMessages.getString("OrganizeImportsAction.error.title"), ActionMessages.getString("OrganizeImportsAction.error.message")); //$NON-NLS-1$ //$NON-NLS-2$
} catch (InterruptedException e) {
}
}
private String getOrganizeInfo(OrganizeImportsOperation op) {
int nImportsAdded= op.getNumberOfImportsAdded();
if (nImportsAdded >= 0) {
return ActionMessages.getFormattedString("OrganizeImportsAction.summary_added", String.valueOf(nImportsAdded)); //$NON-NLS-1$
} else {
return ActionMessages.getFormattedString("OrganizeImportsAction.summary_removed", String.valueOf(-nImportsAdded)); //$NON-NLS-1$
}
}
private IChooseImportQuery createChooseImportQuery() {
return new IChooseImportQuery() {
public TypeInfo[] chooseImports(TypeInfo[][] openChoices, ISourceRange[] ranges) {
return doChooseImports(openChoices, ranges);
}
};
}
private TypeInfo[] doChooseImports(TypeInfo[][] openChoices, final ISourceRange[] ranges) {
// remember selection
ISelection sel= fEditor.getSelectionProvider().getSelection();
TypeInfo[] result= null;;
ILabelProvider labelProvider= new TypeInfoLabelProvider(TypeInfoLabelProvider.SHOW_FULLYQUALIFIED);
MultiElementListSelectionDialog dialog= new MultiElementListSelectionDialog(getShell(), labelProvider) {
protected void handleSelectionChanged() {
super.handleSelectionChanged();
// show choices in editor
doListSelectionChanged(getCurrentPage(), ranges);
}
};
dialog.setTitle(ActionMessages.getString("OrganizeImportsAction.selectiondialog.title")); //$NON-NLS-1$
dialog.setMessage(ActionMessages.getString("OrganizeImportsAction.selectiondialog.message")); //$NON-NLS-1$
dialog.setElements(openChoices);
if (dialog.open() == Window.OK) {
Object[] res= dialog.getResult();
result= new TypeInfo[res.length];
for (int i= 0; i < res.length; i++) {
Object[] array= (Object[]) res[i];
if (array.length > 0)
result[i]= (TypeInfo) array[0];
}
}
// restore selection
if (sel instanceof ITextSelection) {
ITextSelection textSelection= (ITextSelection) sel;
fEditor.selectAndReveal(textSelection.getOffset(), textSelection.getLength());
}
return result;
}
private void doListSelectionChanged(int page, ISourceRange[] ranges) {
if (page >= 0 && page < ranges.length) {
ISourceRange range= ranges[page];
fEditor.selectAndReveal(range.getOffset(), range.getLength());
}
}
private void setStatusBarMessage(String message) {
IEditorActionBarContributor contributor= fEditor.getEditorSite().getActionBarContributor();
if (contributor instanceof EditorActionBarContributor) {
IStatusLineManager manager= ((EditorActionBarContributor) contributor).getActionBars().getStatusLineManager();
manager.setMessage(message);
}
}
}
|
28,269 |
Bug 28269 type hierarchy makes work much slower even though it's invisible
|
20021210 i had a big type hierarchy open but put in the background - behind the package explorer i added 1 type to the workspace boom - tyhe whole thing froze for 2 minutes because the type hierarchy was doing a lot of work that i did not ask for and no busy cursor it makes it quite impossible to work if you have a type hierarchy open anywhere
|
resolved fixed
|
9a4499d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-17T11:02:54Z | 2002-12-13T14:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/TypeHierarchyViewPart.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.typehierarchy;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
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.DragSource;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.Transfer;
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.IPartListener;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.actions.OpenWithMenu;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.PageBook;
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.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.ui.actions.ShowActionGroup;
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.DelegatingDragAdapter;
import org.eclipse.jdt.internal.ui.dnd.DelegatingDropAdapter;
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.util.BusyIndicatorRunnableContext;
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;
/**
* 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 inut elements. No duplicates
private ArrayList fInputHistory;
private IMemento fMemento;
private TypeHierarchyLifeCycle fHierarchyLifeCycle;
private ITypeHierarchyLifeCycleListener fTypeHierarchyLifeCycleListener;
private IPropertyChangeListener fPropertyChangeListener;
private MethodsViewer fMethodsViewer;
private int fCurrentViewerIndex;
private TypeHierarchyViewer[] fAllViewers;
private SelectionProviderMediator fSelectionProviderMediator;
private ISelectionChangedListener fSelectionChangedListener;
private boolean fIsEnableMemberFilter;
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 IDialogSettings fDialogSettings;
private ToggleViewAction[] fViewActions;
private HistoryDropDownAction fHistoryDropDownAction;
private ToggleOrientationAction[] fToggleOrientationActions;
private int fCurrentOrientation;
private EnableMemberFilterAction fEnableMemberFilterAction;
private ShowQualifiedTypeNamesAction fShowQualifiedTypeNamesAction;
private AddMethodStubAction fAddStubAction;
private FocusOnTypeAction fFocusOnTypeAction;
private FocusOnSelectionAction fFocusOnSelectionAction;
private IPartListener fPartListener;
private CompositeActionGroup fActionGroups;
private CCPActionGroup fCCPActionGroup;
private SelectAllAction fSelectAllAction;
public TypeHierarchyViewPart() {
fSelectedType= null;
fInputElement= null;
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);
}
};
JavaPlugin.getDefault().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 IPartListener() {
public void partActivated(IWorkbenchPart part) {
if (part instanceof IEditorPart)
editorActivated((IEditorPart) part);
}
public void partBroughtToTop(IWorkbenchPart part) {}
public void partClosed(IWorkbenchPart part) {}
public void partDeactivated(IWorkbenchPart part) {}
public void partOpened(IWorkbenchPart part) {}
};
fSelectionChangedListener= new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
doSelectionChanged(event);
}
};
}
/**
* Method doPropertyChange.
* @param event
*/
private void doPropertyChange(PropertyChangeEvent event) {
if (fMethodsViewer != null) {
if (PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER.equals(event.getProperty())) {
fMethodsViewer.refresh();
}
}
}
/**
* 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) {
ICompilationUnit cu= member.getCompilationUnit();
if (cu != null && cu.isWorkingCopy()) {
member= (IMember) cu.getOriginal(member);
if (member == null) {
return;
}
}
if (member.getElementType() != IJavaElement.TYPE) {
if (fHierarchyLifeCycle.isReconciled() && cu != null) {
try {
member= (IMember) EditorUtility.getWorkingCopy(member);
if (member == null) {
return;
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
return;
}
}
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();
}
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();
}
ICompilationUnit cu= ((IMember) element).getCompilationUnit();
if (cu != null && cu.isWorkingCopy()) {
element= cu.getOriginal(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;
fInputElement= inputElement;
if (fInputElement == null) {
clearInput();
} else {
try {
fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(fInputElement, new BusyIndicatorRunnableContext());
} catch (JavaModelException e) {
JavaPlugin.log(e);
clearInput();
return;
}
fPagebook.showPage(fTypeMethodsSplitter);
if (inputElement.getElementType() != IJavaElement.TYPE) {
setView(VIEW_ID_TYPE);
}
// turn off member filtering
setMemberFilter(null);
fIsEnableMemberFilter= false;
if (!fInputElement.equals(prevInput)) {
updateHierarchyViewer();
}
IType root= getSelectableType(fInputElement);
internalSelectType(root, true);
updateMethodViewer(root);
updateToolbarButtons();
updateTitle();
enableMemberFilter(false);
}
}
private void clearInput() {
fInputElement= null;
fHierarchyLifeCycle.freeHierarchy();
updateHierarchyViewer();
updateToolbarButtons();
}
/*
* @see IWorbenchPart#setFocus
*/
public void setFocus() {
fPagebook.setFocus();
}
/*
* @see IWorkbenchPart#dispose
*/
public void dispose() {
fHierarchyLifeCycle.freeHierarchy();
fHierarchyLifeCycle.removeChangedListener(fTypeHierarchyLifeCycleListener);
fPaneLabelProvider.dispose();
fMethodsViewer.dispose();
if (fPropertyChangeListener != null) {
JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(fPropertyChangeListener);
fPropertyChangeListener= null;
}
getSite().getPage().removePartListener(fPartListener);
if (fActionGroups != null)
fActionGroups.dispose();
super.dispose();
}
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) {
updateHierarchyViewer();
return;
} else if (event.character == SWT.DEL){
if (fCCPActionGroup.getDeleteAction().isEnabled())
fCCPActionGroup.getDeleteAction().run();
return;
}
}
viewPartKeyShortcuts(event);
}
};
}
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.addSelectionChangedListener(fSelectionChangedListener);
typesViewer.setQualifiedTypeName(isShowQualifiedTypeNames());
}
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.addSelectionChangedListener(fSelectionChangedListener);
Control control= fMethodsViewer.getTable();
control.addKeyListener(createKeyListener());
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){
Control control= viewer.getControl();
TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] {
new SelectionTransferDragAdapter(viewer)
};
DragSource source= new DragSource(control, ops);
// Note, that the transfer agents are set by the delegating drag adapter itself.
source.addDragListener(new DelegatingDragAdapter(dragListeners));
}
private void viewPartKeyShortcuts(KeyEvent event) {
if (event.stateMask == SWT.CTRL) {
if (event.character == '1') {
setView(VIEW_ID_TYPE);
} else if (event.character == '2') {
setView(VIEW_ID_SUPER);
} else if (event.character == '3') {
setView(VIEW_ID_SUB);
}
}
}
/**
* Returns the inner component in a workbench part.
* @see IWorkbenchPart#createPartControl
*/
public void createPartControl(Composite container) {
fPagebook= new PageBook(container, SWT.NONE);
// 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$
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);
// set the filter menu items
IActionBars actionBars= getViewSite().getActionBars();
IMenuManager viewMenu= actionBars.getMenuManager();
for (int i= 0; i < fToggleOrientationActions.length; i++) {
viewMenu.add(fToggleOrientationActions[i]);
}
viewMenu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
viewMenu.add(fShowQualifiedTypeNamesAction);
// 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);
IJavaElement input= 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),
new ShowActionGroup(this),
fCCPActionGroup= new CCPActionGroup(this),
new RefactorActionGroup(this),
new GenerateActionGroup(this),
new JavaSearchActionGroup(this)});
fActionGroups.fillActionBars(actionBars);
fSelectAllAction= new SelectAllAction(fMethodsViewer);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.SELECT_ALL, fSelectAllAction);
initDragAndDrop();
}
/**
* 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);
// //menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, new JavaReplaceWithEditionAction(fMethodsViewer));
// addOpenWithMenu(menu, (IStructuredSelection)fMethodsViewer.getSelection());
// ContextMenuGroup.add(menu, new ContextMenuGroup[] { new BuildGroup(this, false)}, fMethodsViewer);
//
// // XXX workaround until we have fully converted the code to use the new action groups
// fActionGroups.get(2).fillContextMenu(menu);
// fActionGroups.get(3).fillContextMenu(menu);
// fActionGroups.get(4).fillContextMenu(menu);
}
private void addOpenWithMenu(IMenuManager menu, IStructuredSelection selection) {
// If one file is selected get it.
// Otherwise, do not show the "open with" menu.
if (selection.size() != 1)
return;
Object element= selection.getFirstElement();
if (!(element instanceof IJavaElement))
return;
IJavaElement openable= (IJavaElement) ((IJavaElement) element).getOpenable();
IResource resource= openable.getResource();
if (!(resource instanceof IFile))
return;
// Create a menu flyout.
MenuManager submenu= new MenuManager(TypeHierarchyMessages.getString("TypeHierarchyViewPart.menu.open")); //$NON-NLS-1$
submenu.add(new OpenWithMenu(getSite().getPage(), (IFile) resource));
// Add the submenu.
menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, submenu);
}
/**
* 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.removeSelectionChangedListener(fSelectionChangedListener);
viewer.setSelection(elem != null ? new StructuredSelection(elem) : StructuredSelection.EMPTY, reveal);
viewer.addSelectionChangedListener(fSelectionChangedListener);
}
private void internalSelectMember(IMember member) {
fMethodsViewer.removeSelectionChangedListener(fSelectionChangedListener);
fMethodsViewer.setSelection(member != null ? new StructuredSelection(member) : StructuredSelection.EMPTY);
fMethodsViewer.addSelectionChangedListener(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() {
if (fInputElement == null) {
fPagebook.showPage(fNoHierarchyShownLabel);
} else {
if (getCurrentViewer().containsElements() != null) {
Runnable runnable= new Runnable() {
public void run() {
getCurrentViewer().updateContent(); // 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);
}
}
}
private void doSelectionChanged(SelectionChangedEvent e) {
if (e.getSelectionProvider() == fMethodsViewer) {
methodSelectionChanged(e.getSelection());
fSelectAllAction.setEnabled(true);
} else {
typeSelectionChanged(e.getSelection());
fSelectAllAction.setEnabled(false);
}
}
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();
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)) {
try {
getSite().getPage().removePartListener(fPartListener);
EditorUtility.openInEditor(elem, false);
EditorUtility.revealInEditor(editorPart, (IJavaElement) elem);
getSite().getPage().addPartListener(fPartListener);
} catch (CoreException e) {
JavaPlugin.log(e);
}
}
}
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();
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();
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
*/
private void doTypeHierarchyChanged(final TypeHierarchyLifeCycle typeHierarchy, final IType[] changedTypes) {
Display display= getDisplay();
if (display != null) {
display.asyncExec(new Runnable() {
public void run() {
if (fPagebook != null && !fPagebook.isDisposed()) {
doTypeHierarchyChangedOnViewers(changedTypes);
}
}
});
}
}
private void doTypeHierarchyChangedOnViewers(IType[] changedTypes) {
if (fHierarchyLifeCycle.getHierarchy() == null || !fHierarchyLifeCycle.getHierarchy().exists()) {
clearInput();
} else {
if (changedTypes == null) {
// hierarchy change
try {
fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(fInputElement, new BusyIndicatorRunnableContext());
} catch (JavaModelException e) {
JavaPlugin.log(e.getStatus());
clearInput();
return;
}
fMethodsViewer.refresh();
updateHierarchyViewer();
} else {
// elements in hierarchy modified
fMethodsViewer.refresh();
if (getCurrentViewer().isMethodFiltering()) {
if (changedTypes.length == 1) {
getCurrentViewer().refresh(changedTypes[0]);
} else {
updateHierarchyViewer();
}
} else {
getCurrentViewer().update(changedTypes, new String[] { IBasicPropertyConstants.P_TEXT, IBasicPropertyConstants.P_IMAGE } );
}
}
}
}
/**
* Determines the input element to be used initially .
*/
private IJavaElement determineInputElement() {
Object input= getSite().getPage().getInput();
if (input instanceof IJavaElement) {
IJavaElement elem= (IJavaElement) input;
if (elem instanceof IMember) {
return elem;
} else {
int kind= elem.getElementType();
if (kind == IJavaElement.JAVA_PROJECT || kind == IJavaElement.PACKAGE_FRAGMENT_ROOT || kind == IJavaElement.PACKAGE_FRAGMENT) {
return elem;
}
}
}
return null;
}
/*
* @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());
}
fMethodsViewer.saveState(memento);
}
/**
* Restores the type hierarchy settings from a memento.
*/
private void restoreState(IMemento memento, IJavaElement defaultInput) {
IJavaElement input= defaultInput;
String elementId= memento.getString(TAG_INPUT);
if (elementId != null) {
input= JavaCore.create(elementId);
if (input != null && !input.exists()) {
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);
}
/**
* Link selection to active editor.
*/
private void editorActivated(IEditorPart editor) {
if (!PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.LINK_TYPEHIERARCHY_TO_EDITOR)) {
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.getStatus());
}
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput()
*/
public Object getViewPartInput() {
return fInputElement;
}
}
|
28,575 |
Bug 28575 Hierarchy view updates items twice [type hierarchy]
| null |
resolved fixed
|
2098c30
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-17T13:53:22Z | 2002-12-17T21:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/TypeHierarchyViewPart.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.typehierarchy;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
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.DragSource;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.Transfer;
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.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.PartInitException;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.actions.OpenWithMenu;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.PageBook;
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.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.ui.actions.ShowActionGroup;
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.DelegatingDragAdapter;
import org.eclipse.jdt.internal.ui.dnd.DelegatingDropAdapter;
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.util.BusyIndicatorRunnableContext;
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;
/**
* 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 fIsVisible;
private boolean fNeedRefresh;
private boolean fIsEnableMemberFilter;
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 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;
public TypeHierarchyViewPart() {
fSelectedType= null;
fInputElement= null;
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 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);
}
};
}
/**
* Method doPropertyChange.
* @param event
*/
protected void doPropertyChange(PropertyChangeEvent event) {
if (fMethodsViewer != null) {
if (PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER.equals(event.getProperty())) {
fMethodsViewer.refresh();
}
}
}
/**
* 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) {
ICompilationUnit cu= member.getCompilationUnit();
if (cu != null && cu.isWorkingCopy()) {
member= (IMember) cu.getOriginal(member);
if (member == null) {
return;
}
}
if (member.getElementType() != IJavaElement.TYPE) {
if (fHierarchyLifeCycle.isReconciled() && cu != null) {
try {
member= (IMember) EditorUtility.getWorkingCopy(member);
if (member == null) {
return;
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
return;
}
}
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();
}
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();
}
ICompilationUnit cu= ((IMember) element).getCompilationUnit();
if (cu != null && cu.isWorkingCopy()) {
element= cu.getOriginal(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;
fInputElement= inputElement;
if (fInputElement == null) {
clearInput();
} else {
try {
fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(fInputElement, new BusyIndicatorRunnableContext());
} catch (JavaModelException e) {
JavaPlugin.log(e);
clearInput();
return;
}
fPagebook.showPage(fTypeMethodsSplitter);
if (inputElement.getElementType() != IJavaElement.TYPE) {
setView(VIEW_ID_TYPE);
}
// turn off member filtering
setMemberFilter(null);
fIsEnableMemberFilter= false;
if (!fInputElement.equals(prevInput)) {
updateHierarchyViewer();
}
IType root= getSelectableType(fInputElement);
internalSelectType(root, true);
updateMethodViewer(root);
updateToolbarButtons();
updateTitle();
enableMemberFilter(false);
}
}
private void clearInput() {
fInputElement= null;
fHierarchyLifeCycle.freeHierarchy();
updateHierarchyViewer();
updateToolbarButtons();
}
/*
* @see IWorbenchPart#setFocus
*/
public void setFocus() {
fPagebook.setFocus();
}
/*
* @see IWorkbenchPart#dispose
*/
public void dispose() {
fHierarchyLifeCycle.freeHierarchy();
fHierarchyLifeCycle.removeChangedListener(fTypeHierarchyLifeCycleListener);
fPaneLabelProvider.dispose();
fMethodsViewer.dispose();
if (fPropertyChangeListener != null) {
JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(fPropertyChangeListener);
fPropertyChangeListener= null;
}
getSite().getPage().removePartListener(fPartListener);
if (fActionGroups != null)
fActionGroups.dispose();
super.dispose();
}
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) {
updateHierarchyViewer();
return;
} else if (event.character == SWT.DEL){
if (fCCPActionGroup.getDeleteAction().isEnabled())
fCCPActionGroup.getDeleteAction().run();
return;
}
}
viewPartKeyShortcuts(event);
}
};
}
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.addSelectionChangedListener(fSelectionChangedListener);
typesViewer.setQualifiedTypeName(isShowQualifiedTypeNames());
}
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.addSelectionChangedListener(fSelectionChangedListener);
Control control= fMethodsViewer.getTable();
control.addKeyListener(createKeyListener());
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){
Control control= viewer.getControl();
TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] {
new SelectionTransferDragAdapter(viewer)
};
DragSource source= new DragSource(control, ops);
// Note, that the transfer agents are set by the delegating drag adapter itself.
source.addDragListener(new DelegatingDragAdapter(dragListeners));
}
private void viewPartKeyShortcuts(KeyEvent event) {
if (event.stateMask == SWT.CTRL) {
if (event.character == '1') {
setView(VIEW_ID_TYPE);
} else if (event.character == '2') {
setView(VIEW_ID_SUPER);
} else if (event.character == '3') {
setView(VIEW_ID_SUB);
}
}
}
/**
* Returns the inner component in a workbench part.
* @see IWorkbenchPart#createPartControl
*/
public void createPartControl(Composite container) {
fPagebook= new PageBook(container, SWT.NONE);
// 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$
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);
// set the filter menu items
IActionBars actionBars= getViewSite().getActionBars();
IMenuManager viewMenu= actionBars.getMenuManager();
for (int i= 0; i < fToggleOrientationActions.length; i++) {
viewMenu.add(fToggleOrientationActions[i]);
}
viewMenu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
viewMenu.add(fShowQualifiedTypeNamesAction);
// 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);
IJavaElement input= 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),
new ShowActionGroup(this),
fCCPActionGroup= new CCPActionGroup(this),
new RefactorActionGroup(this),
new GenerateActionGroup(this),
new JavaSearchActionGroup(this)});
fActionGroups.fillActionBars(actionBars);
fSelectAllAction= new SelectAllAction(fMethodsViewer);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.SELECT_ALL, fSelectAllAction);
initDragAndDrop();
}
/**
* 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);
}
private void addOpenWithMenu(IMenuManager menu, IStructuredSelection selection) {
// If one file is selected get it.
// Otherwise, do not show the "open with" menu.
if (selection.size() != 1)
return;
Object element= selection.getFirstElement();
if (!(element instanceof IJavaElement))
return;
IJavaElement openable= (IJavaElement) ((IJavaElement) element).getOpenable();
IResource resource= openable.getResource();
if (!(resource instanceof IFile))
return;
// Create a menu flyout.
MenuManager submenu= new MenuManager(TypeHierarchyMessages.getString("TypeHierarchyViewPart.menu.open")); //$NON-NLS-1$
submenu.add(new OpenWithMenu(getSite().getPage(), (IFile) resource));
// Add the submenu.
menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, submenu);
}
/**
* 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.removeSelectionChangedListener(fSelectionChangedListener);
viewer.setSelection(elem != null ? new StructuredSelection(elem) : StructuredSelection.EMPTY, reveal);
viewer.addSelectionChangedListener(fSelectionChangedListener);
}
private void internalSelectMember(IMember member) {
fMethodsViewer.removeSelectionChangedListener(fSelectionChangedListener);
fMethodsViewer.setSelection(member != null ? new StructuredSelection(member) : StructuredSelection.EMPTY);
fMethodsViewer.addSelectionChangedListener(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() {
if (fInputElement == null) {
fPagebook.showPage(fNoHierarchyShownLabel);
} else {
if (getCurrentViewer().containsElements() != null) {
Runnable runnable= new Runnable() {
public void run() {
getCurrentViewer().updateContent(); // 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());
fSelectAllAction.setEnabled(true);
} else {
typeSelectionChanged(e.getSelection());
fSelectAllAction.setEnabled(false);
}
}
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();
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)) {
try {
getSite().getPage().removePartListener(fPartListener);
EditorUtility.openInEditor(elem, false);
EditorUtility.revealInEditor(editorPart, (IJavaElement) elem);
getSite().getPage().addPartListener(fPartListener);
} catch (CoreException e) {
JavaPlugin.log(e);
}
}
}
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();
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();
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;
}
Display display= getDisplay();
if (display != null) {
display.asyncExec(new Runnable() {
public void run() {
if (fPagebook != null && !fPagebook.isDisposed()) {
doTypeHierarchyChangedOnViewers(changedTypes);
}
}
});
}
}
protected void doTypeHierarchyChangedOnViewers(IType[] changedTypes) {
if (fHierarchyLifeCycle.getHierarchy() == null || !fHierarchyLifeCycle.getHierarchy().exists()) {
clearInput();
} else {
if (changedTypes == null) {
// hierarchy change
try {
fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(fInputElement, new BusyIndicatorRunnableContext());
} catch (JavaModelException e) {
JavaPlugin.log(e.getStatus());
clearInput();
return;
}
fMethodsViewer.refresh();
updateHierarchyViewer();
} else {
// elements in hierarchy modified
fMethodsViewer.refresh();
if (getCurrentViewer().isMethodFiltering()) {
if (changedTypes.length == 1) {
getCurrentViewer().refresh(changedTypes[0]);
} else {
updateHierarchyViewer();
}
} else {
getCurrentViewer().update(changedTypes, new String[] { IBasicPropertyConstants.P_TEXT, IBasicPropertyConstants.P_IMAGE } );
}
}
}
}
/**
* Determines the input element to be used initially .
*/
private IJavaElement determineInputElement() {
Object input= getSite().getPage().getInput();
if (input instanceof IJavaElement) {
IJavaElement elem= (IJavaElement) input;
if (elem instanceof IMember) {
return elem;
} else {
int kind= elem.getElementType();
if (kind == IJavaElement.JAVA_PROJECT || kind == IJavaElement.PACKAGE_FRAGMENT_ROOT || kind == IJavaElement.PACKAGE_FRAGMENT) {
return elem;
}
}
}
return null;
}
/*
* @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());
}
fMethodsViewer.saveState(memento);
}
/**
* Restores the type hierarchy settings from a memento.
*/
private void restoreState(IMemento memento, IJavaElement defaultInput) {
IJavaElement input= defaultInput;
String elementId= memento.getString(TAG_INPUT);
if (elementId != null) {
input= JavaCore.create(elementId);
if (input != null && !input.exists()) {
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);
}
/**
* view part becomes visible
*/
protected void visibilityChanged(boolean isVisible) {
fIsVisible= isVisible;
if (isVisible && fNeedRefresh) {
doTypeHierarchyChanged(fHierarchyLifeCycle, null);
}
fNeedRefresh= false;
}
/**
* Link selection to active editor.
*/
protected void editorActivated(IEditorPart editor) {
if (!PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.LINK_TYPEHIERARCHY_TO_EDITOR)) {
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.getStatus());
}
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput()
*/
public Object getViewPartInput() {
return fInputElement;
}
}
|
29,698 |
Bug 29698 drag and drop of java files between packages in package explorer doesn't work
|
the <preview> <ok> <cancel> dialog shows up, but <ok> has the same effect as <cancel> and <preview> would only show movements of files and no changes in imports of other java files. on <ok> in the preview it only moves the file(s) (as indicated ) without changing referencing imports.
|
resolved fixed
|
386c5c6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-17T14:02:05Z | 2003-01-17T10:40:00Z |
org.eclipse.jdt.ui/core
| |
29,698 |
Bug 29698 drag and drop of java files between packages in package explorer doesn't work
|
the <preview> <ok> <cancel> dialog shows up, but <ok> has the same effect as <cancel> and <preview> would only show movements of files and no changes in imports of other java files. on <ok> in the preview it only moves the file(s) (as indicated ) without changing referencing imports.
|
resolved fixed
|
386c5c6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-17T14:02:05Z | 2003-01-17T10:40:00Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/rename/RenameTypeRefactoring.java
| |
29,698 |
Bug 29698 drag and drop of java files between packages in package explorer doesn't work
|
the <preview> <ok> <cancel> dialog shows up, but <ok> has the same effect as <cancel> and <preview> would only show movements of files and no changes in imports of other java files. on <ok> in the preview it only moves the file(s) (as indicated ) without changing referencing imports.
|
resolved fixed
|
386c5c6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-17T14:02:05Z | 2003-01-17T10:40:00Z |
org.eclipse.jdt.ui/core
| |
29,698 |
Bug 29698 drag and drop of java files between packages in package explorer doesn't work
|
the <preview> <ok> <cancel> dialog shows up, but <ok> has the same effect as <cancel> and <preview> would only show movements of files and no changes in imports of other java files. on <ok> in the preview it only moves the file(s) (as indicated ) without changing referencing imports.
|
resolved fixed
|
386c5c6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-17T14:02:05Z | 2003-01-17T10:40:00Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/reorg/MoveRefactoring.java
| |
29,698 |
Bug 29698 drag and drop of java files between packages in package explorer doesn't work
|
the <preview> <ok> <cancel> dialog shows up, but <ok> has the same effect as <cancel> and <preview> would only show movements of files and no changes in imports of other java files. on <ok> in the preview it only moves the file(s) (as indicated ) without changing referencing imports.
|
resolved fixed
|
386c5c6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-17T14:02:05Z | 2003-01-17T10:40:00Z |
org.eclipse.jdt.ui/core
| |
29,698 |
Bug 29698 drag and drop of java files between packages in package explorer doesn't work
|
the <preview> <ok> <cancel> dialog shows up, but <ok> has the same effect as <cancel> and <preview> would only show movements of files and no changes in imports of other java files. on <ok> in the preview it only moves the file(s) (as indicated ) without changing referencing imports.
|
resolved fixed
|
386c5c6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-17T14:02:05Z | 2003-01-17T10:40:00Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/MoveStaticMembersRefactoring.java
| |
29,698 |
Bug 29698 drag and drop of java files between packages in package explorer doesn't work
|
the <preview> <ok> <cancel> dialog shows up, but <ok> has the same effect as <cancel> and <preview> would only show movements of files and no changes in imports of other java files. on <ok> in the preview it only moves the file(s) (as indicated ) without changing referencing imports.
|
resolved fixed
|
386c5c6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-17T14:02:05Z | 2003-01-17T10:40:00Z |
org.eclipse.jdt.ui/core
| |
29,698 |
Bug 29698 drag and drop of java files between packages in package explorer doesn't work
|
the <preview> <ok> <cancel> dialog shows up, but <ok> has the same effect as <cancel> and <preview> would only show movements of files and no changes in imports of other java files. on <ok> in the preview it only moves the file(s) (as indicated ) without changing referencing imports.
|
resolved fixed
|
386c5c6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-17T14:02:05Z | 2003-01-17T10:40:00Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/util/QualifiedNameFinder.java
| |
29,698 |
Bug 29698 drag and drop of java files between packages in package explorer doesn't work
|
the <preview> <ok> <cancel> dialog shows up, but <ok> has the same effect as <cancel> and <preview> would only show movements of files and no changes in imports of other java files. on <ok> in the preview it only moves the file(s) (as indicated ) without changing referencing imports.
|
resolved fixed
|
386c5c6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-17T14:02:05Z | 2003-01-17T10:40:00Z |
org.eclipse.jdt.ui/ui
| |
29,698 |
Bug 29698 drag and drop of java files between packages in package explorer doesn't work
|
the <preview> <ok> <cancel> dialog shows up, but <ok> has the same effect as <cancel> and <preview> would only show movements of files and no changes in imports of other java files. on <ok> in the preview it only moves the file(s) (as indicated ) without changing referencing imports.
|
resolved fixed
|
386c5c6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-17T14:02:05Z | 2003-01-17T10:40:00Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/MoveMembersWizard.java
| |
29,698 |
Bug 29698 drag and drop of java files between packages in package explorer doesn't work
|
the <preview> <ok> <cancel> dialog shows up, but <ok> has the same effect as <cancel> and <preview> would only show movements of files and no changes in imports of other java files. on <ok> in the preview it only moves the file(s) (as indicated ) without changing referencing imports.
|
resolved fixed
|
386c5c6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-17T14:02:05Z | 2003-01-17T10:40:00Z |
org.eclipse.jdt.ui/ui
| |
29,698 |
Bug 29698 drag and drop of java files between packages in package explorer doesn't work
|
the <preview> <ok> <cancel> dialog shows up, but <ok> has the same effect as <cancel> and <preview> would only show movements of files and no changes in imports of other java files. on <ok> in the preview it only moves the file(s) (as indicated ) without changing referencing imports.
|
resolved fixed
|
386c5c6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-17T14:02:05Z | 2003-01-17T10:40:00Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/actions/RenameJavaElementAction.java
| |
29,698 |
Bug 29698 drag and drop of java files between packages in package explorer doesn't work
|
the <preview> <ok> <cancel> dialog shows up, but <ok> has the same effect as <cancel> and <preview> would only show movements of files and no changes in imports of other java files. on <ok> in the preview it only moves the file(s) (as indicated ) without changing referencing imports.
|
resolved fixed
|
386c5c6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-17T14:02:05Z | 2003-01-17T10:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/packageview/SelectionTransferDropAdapter.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.packageview;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.Transfer;
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.Shell;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.DialogSettings;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.ISourceReference;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.corext.Assert;
import org.eclipse.jdt.internal.corext.refactoring.reorg.CopyRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.reorg.MoveRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.reorg.SourceReferenceUtil;
import org.eclipse.jdt.internal.corext.refactoring.util.ResourceUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.AddMethodStubAction;
import org.eclipse.jdt.internal.ui.dnd.JdtViewerDropAdapter;
import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer;
import org.eclipse.jdt.internal.ui.dnd.TransferDropTargetListener;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.refactoring.QualifiedNameComponent;
import org.eclipse.jdt.internal.ui.refactoring.RefactoringMessages;
import org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardPage;
import org.eclipse.jdt.internal.ui.reorg.CopyQueries;
import org.eclipse.jdt.internal.ui.reorg.DeleteSourceReferencesAction;
import org.eclipse.jdt.internal.ui.reorg.JdtMoveAction;
import org.eclipse.jdt.internal.ui.reorg.MockWorkbenchSite;
import org.eclipse.jdt.internal.ui.reorg.ReorgActionFactory;
import org.eclipse.jdt.internal.ui.reorg.ReorgMessages;
import org.eclipse.jdt.internal.ui.reorg.SimpleSelectionProvider;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.ui.actions.SelectionDispatchAction;
public class SelectionTransferDropAdapter extends JdtViewerDropAdapter implements TransferDropTargetListener {
private List fElements;
private MoveRefactoring fMoveRefactoring;
private int fCanMoveElements;
private CopyRefactoring fCopyRefactoring;
private int fCanCopyElements;
private ISelection fSelection;
private AddMethodStubAction fAddMethodStubAction;
private static final int DROP_TIME_DIFF_TRESHOLD= 150;
public SelectionTransferDropAdapter(StructuredViewer viewer) {
super(viewer, DND.FEEDBACK_SCROLL | DND.FEEDBACK_EXPAND);
fAddMethodStubAction= new AddMethodStubAction();
}
//---- TransferDropTargetListener interface ---------------------------------------
public Transfer getTransfer() {
return LocalSelectionTransfer.getInstance();
}
//---- Actual DND -----------------------------------------------------------------
public void dragEnter(DropTargetEvent event) {
clear();
super.dragEnter(event);
}
public void dragLeave(DropTargetEvent event) {
clear();
super.dragLeave(event);
}
private void clear() {
fElements= null;
fSelection= null;
fMoveRefactoring= null;
fCanMoveElements= 0;
fCopyRefactoring= null;
fCanCopyElements= 0;
}
public void validateDrop(Object target, DropTargetEvent event, int operation) {
event.detail= DND.DROP_NONE;
if (tooFast(event))
return;
initializeSelection();
try {
if (operation == DND.DROP_DEFAULT) {
event.detail= handleValidateDefault(target, event);
} else if (operation == DND.DROP_COPY) {
event.detail= handleValidateCopy(target, event);
} else if (operation == DND.DROP_MOVE) {
event.detail= handleValidateMove(target, event);
} else if (operation == DND.DROP_LINK) {
event.detail= handleValidateLink(target, event);
}
} catch (JavaModelException e){
ExceptionHandler.handle(e, PackagesMessages.getString("SelectionTransferDropAdapter.error.title"), PackagesMessages.getString("SelectionTransferDropAdapter.error.message")); //$NON-NLS-1$ //$NON-NLS-2$
event.detail= DND.DROP_NONE;
}
}
protected void initializeSelection(){
if (fElements != null)
return;
ISelection s= LocalSelectionTransfer.getInstance().getSelection();
if (!(s instanceof IStructuredSelection))
return;
fSelection= s;
fElements= ((IStructuredSelection)s).toList();
}
protected ISelection getSelection(){
return fSelection;
}
private boolean tooFast(DropTargetEvent event) {
return Math.abs(LocalSelectionTransfer.getInstance().getSelectionSetTime() - event.time) < DROP_TIME_DIFF_TRESHOLD;
}
public void drop(Object target, DropTargetEvent event) {
try{
if (event.detail == DND.DROP_MOVE) {
handleDropMove(target, event);
if (! canPasteSourceReferences(target))
return;
DeleteSourceReferencesAction delete= ReorgActionFactory.createDeleteSourceReferencesAction(getDragableSourceReferences());
delete.setAskForDeleteConfirmation(true);
delete.setCanDeleteGetterSetter(false);
delete.update(delete.getSelection());
if (delete.isEnabled())
delete.run();
} else if (event.detail == DND.DROP_COPY) {
handleDropCopy(target, event);
} else if (event.detail == DND.DROP_LINK) {
handleDropLink(target, event);
}
} catch (JavaModelException e){
ExceptionHandler.handle(e, PackagesMessages.getString("SelectionTransferDropAdapter.error.title"), PackagesMessages.getString("SelectionTransferDropAdapter.error.message")); //$NON-NLS-1$ //$NON-NLS-2$
} finally{
// The drag source listener must not perform any operation
// since this drop adapter did the remove of the source even
// if we moved something.
event.detail= DND.DROP_NONE;
}
}
private int handleValidateDefault(Object target, DropTargetEvent event) throws JavaModelException{
if (target == null)
return DND.DROP_NONE;
if (canPasteSourceReferences(target))
return handleValidateCopy(target, event);
else
return handleValidateMove(target, event);
}
private int handleValidateMove(Object target, DropTargetEvent event) throws JavaModelException{
if (target == null)
return DND.DROP_NONE;
if (canPasteSourceReferences(target)){
if (canMoveSelectedSourceReferences(target))
return DND.DROP_MOVE;
else
return DND.DROP_NONE;
}
if (fMoveRefactoring == null){
fMoveRefactoring= new MoveRefactoring(fElements, JavaPreferencesSettings.getCodeGenerationSettings());
}
if (!canMoveElements())
return DND.DROP_NONE;
if (fMoveRefactoring.isValidDestination(target))
return DND.DROP_MOVE;
else
return DND.DROP_NONE;
}
private boolean canMoveElements() {
if (fCanMoveElements == 0) {
fCanMoveElements= 2;
if (! canActivate(fMoveRefactoring))
fCanMoveElements= 1;
}
return fCanMoveElements == 2;
}
private boolean canActivate(ReorgRefactoring ref){
try{
return ref.checkActivation(new NullProgressMonitor()).isOK();
} catch(JavaModelException e){
ExceptionHandler.handle(e, PackagesMessages.getString("SelectionTransferDropAdapter.error.title"), PackagesMessages.getString("SelectionTransferDropAdapter.error.message")); //$NON-NLS-1$ //$NON-NLS-2$
return false;
}
}
private void handleDropLink(Object target, DropTargetEvent event) {
if (fAddMethodStubAction.init((IType)target, getSelection()))
fAddMethodStubAction.run();
}
private int handleValidateLink(Object target, DropTargetEvent event) {
if (target instanceof IType && AddMethodStubAction.canActionBeAdded((IType)target, getSelection()))
return DND.DROP_LINK;
else
return DND.DROP_NONE;
}
private void handleDropMove(final Object target, DropTargetEvent event) throws JavaModelException{
if (canPasteSourceReferences(target)){
pasteSourceReferences(target, event);
return;
}
new DragNDropMoveAction(new SimpleSelectionProvider(fElements), target).run();
}
private void pasteSourceReferences(final Object target, DropTargetEvent event) {
SelectionDispatchAction pasteAction= ReorgActionFactory.createPasteAction(getDragableSourceReferences(), target);
pasteAction.update(pasteAction.getSelection());
if (!pasteAction.isEnabled()){
event.detail= DND.DROP_NONE;
return;
}
pasteAction.run();
return;
}
private int handleValidateCopy(Object target, DropTargetEvent event) throws JavaModelException{
if (canPasteSourceReferences(target))
return DND.DROP_COPY;
if (fCopyRefactoring == null)
fCopyRefactoring= new CopyRefactoring(fElements, new CopyQueries());
if (!canCopyElements())
return DND.DROP_NONE;
if (fCopyRefactoring.isValidDestination(target))
return DND.DROP_COPY;
else
return DND.DROP_NONE;
}
private boolean canMoveSelectedSourceReferences(Object target) throws JavaModelException{
ICompilationUnit targetCu= getCompilationUnit(target);
if (targetCu == null)
return false;
ISourceReference[] elements= getDragableSourceReferences();
for (int i= 0; i < elements.length; i++) {
if (targetCu.equals(SourceReferenceUtil.getCompilationUnit(elements[i])))
return false;
}
return true;
}
private static ICompilationUnit getCompilationUnit(Object target){
if (target instanceof ISourceReference)
return SourceReferenceUtil.getCompilationUnit((ISourceReference)target);
else
return null;
}
private boolean canPasteSourceReferences(Object target) throws JavaModelException{
ISourceReference[] elements= getDragableSourceReferences();
if (elements.length != fElements.size())
return false;
SelectionDispatchAction pasteAction= ReorgActionFactory.createPasteAction(elements, target);
pasteAction.update(pasteAction.getSelection());
return pasteAction.isEnabled();
}
private ISourceReference[] getDragableSourceReferences(){
List result= new ArrayList(fElements.size());
for(Iterator iter= fElements.iterator(); iter.hasNext();){
Object each= iter.next();
if (isDragableSourceReferences(each))
result.add(each);
}
return (ISourceReference[])result.toArray(new ISourceReference[result.size()]);
}
private static boolean isDragableSourceReferences(Object element) {
if (!(element instanceof ISourceReference))
return false;
if (!(element instanceof IJavaElement))
return false;
if (element instanceof ICompilationUnit)
return false;
return true;
}
private boolean canCopyElements() {
if (fCanCopyElements == 0) {
fCanCopyElements= 2;
if (!canActivate(fCopyRefactoring))
fCanCopyElements= 1;
}
return fCanCopyElements == 2;
}
private void handleDropCopy(final Object target, DropTargetEvent event) throws JavaModelException{
if (canPasteSourceReferences(target)){
pasteSourceReferences(target, event);
return;
}
SelectionDispatchAction action= ReorgActionFactory.createDnDCopyAction(fElements, ResourceUtil.getResource(target));
action.run();
}
//--
private static class DragNDropMoveAction extends JdtMoveAction{
private Object fTarget;
private static final int PREVIEW_ID= IDialogConstants.CLIENT_ID + 1;
public DragNDropMoveAction(ISelectionProvider provider, Object target){
super(new MockWorkbenchSite(provider));
Assert.isNotNull(target);
fTarget= target;
}
protected Object selectDestination(ReorgRefactoring ref) {
return fTarget;
}
protected boolean isOkToProceed(ReorgRefactoring refactoring) throws JavaModelException {
if (!super.isOkToProceed(refactoring))
return false;
return askIfUpdateReferences((MoveRefactoring)refactoring);
}
//returns false iff canceled or error
private boolean askIfUpdateReferences(MoveRefactoring ref) throws JavaModelException {
if (! ref.canUpdateReferences() && !ref.canUpdateQualifiedNames()) {
setShowPreview(false);
return true;
}
switch (showMoveDialog(ref)){
case IDialogConstants.CANCEL_ID:
setShowPreview(false);
return false;
case IDialogConstants.YES_ID:
setShowPreview(false);
return true;
case PREVIEW_ID:
setShowPreview(true);
return true;
default:
Assert.isTrue(false); //not expected to get here
return false;
}
}
private static int showMoveDialog(MoveRefactoring ref) {
Shell shell= JavaPlugin.getActiveWorkbenchShell().getShell();
final UpdateDialog dialog= new UpdateDialog(shell, ref);
shell.getDisplay().syncExec(new Runnable() {
public void run() {
dialog.open();
}
});
return dialog.getReturnCode();
}
private static class UpdateDialog extends Dialog {
private Button fPreview;
private MoveRefactoring fRefactoring;
private Button fReferenceCheckbox;
private Button fQualifiedNameCheckbox;
private QualifiedNameComponent fQualifiedNameComponent;
public UpdateDialog(Shell parentShell, MoveRefactoring refactoring) {
super(parentShell);
fRefactoring= refactoring;
}
protected void configureShell(Shell shell) {
shell.setText(PackagesMessages.getString("SelectionTransferDropAdapter.dialog.title")); //$NON-NLS-1$
super.configureShell(shell);
}
protected void createButtonsForButtonBar(Composite parent) {
fPreview= createButton(parent, PREVIEW_ID, ReorgMessages.getString("JdtMoveAction.preview"), false); //$NON-NLS-1$
super.createButtonsForButtonBar(parent);
}
protected void buttonPressed(int buttonId) {
if (buttonId == PREVIEW_ID) {
setReturnCode(PREVIEW_ID);
close();
} else {
super.buttonPressed(buttonId);
}
}
protected Control createDialogArea(Composite parent) {
Composite result= (Composite)super.createDialogArea(parent);
addUpdateReferenceComponent(result);
addUpdateQualifiedNameComponent(result, ((GridLayout)result.getLayout()).marginWidth);
return result;
}
private void updateButtons() {
Button okButton= getButton(IDialogConstants.OK_ID);
boolean okEnabled= true; // we keep this since the code got copied from JdtMoveAction.
okButton.setEnabled(okEnabled);
fReferenceCheckbox.setEnabled(okEnabled && canUpdateReferences());
fRefactoring.setUpdateReferences(fReferenceCheckbox.getEnabled() && fReferenceCheckbox.getSelection());
if (fQualifiedNameCheckbox != null) {
boolean enabled= okEnabled && fRefactoring.canEnableQualifiedNameUpdating();
fQualifiedNameCheckbox.setEnabled(enabled);
if (enabled) {
fQualifiedNameComponent.setEnabled(fRefactoring.getUpdateQualifiedNames());
if (fRefactoring.getUpdateQualifiedNames())
okButton.setEnabled(false);
} else {
fQualifiedNameComponent.setEnabled(false);
}
fRefactoring.setUpdateQualifiedNames(fQualifiedNameCheckbox.getEnabled() && fQualifiedNameCheckbox.getSelection());
}
boolean preview= okEnabled;
if (preview)
preview=
fRefactoring.getUpdateQualifiedNames() && fRefactoring.canEnableQualifiedNameUpdating() ||
fReferenceCheckbox.getSelection() && canUpdateReferences();
fPreview.setEnabled(preview);
}
private void addUpdateReferenceComponent(Composite result) {
fReferenceCheckbox= new Button(result, SWT.CHECK);
fReferenceCheckbox.setText(ReorgMessages.getString("JdtMoveAction.update_references")); //$NON-NLS-1$
fReferenceCheckbox.setSelection(true);
fReferenceCheckbox.setEnabled(canUpdateReferences());
fReferenceCheckbox.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
fRefactoring.setUpdateReferences(((Button)e.widget).getSelection());
updateButtons();
}
});
}
private boolean canUpdateReferences() {
try{
return fRefactoring.canUpdateReferences();
} catch (JavaModelException e){
return false;
}
}
private void addUpdateQualifiedNameComponent(Composite parent, int marginWidth) {
if (!fRefactoring.canUpdateQualifiedNames())
return;
fQualifiedNameCheckbox= new Button(parent, SWT.CHECK);
int indent= marginWidth + fQualifiedNameCheckbox.computeSize(SWT.DEFAULT, SWT.DEFAULT).x;
fQualifiedNameCheckbox.setText(RefactoringMessages.getString("RenameInputWizardPage.update_qualified_names")); //$NON-NLS-1$
fQualifiedNameCheckbox.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
fQualifiedNameCheckbox.setSelection(fRefactoring.getUpdateQualifiedNames());
fQualifiedNameComponent= new QualifiedNameComponent(parent, SWT.NONE, fRefactoring, getRefactoringSettings());
fQualifiedNameComponent.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
GridData gd= (GridData)fQualifiedNameComponent.getLayoutData();
gd.horizontalAlignment= GridData.FILL;
gd.horizontalIndent= indent;
fQualifiedNameComponent.setEnabled(false);
fQualifiedNameCheckbox.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
boolean enabled= ((Button)e.widget).getSelection();
fQualifiedNameComponent.setEnabled(enabled);
fRefactoring.setUpdateQualifiedNames(enabled);
updateButtons();
}
});
}
protected IDialogSettings getRefactoringSettings() {
IDialogSettings settings= JavaPlugin.getDefault().getDialogSettings();
if (settings == null)
return null;
IDialogSettings result= settings.getSection(RefactoringWizardPage.REFACTORING_SETTINGS);
if (result == null) {
result= new DialogSettings(RefactoringWizardPage.REFACTORING_SETTINGS);
settings.addSection(result);
}
return result;
}
}
}
}
|
29,698 |
Bug 29698 drag and drop of java files between packages in package explorer doesn't work
|
the <preview> <ok> <cancel> dialog shows up, but <ok> has the same effect as <cancel> and <preview> would only show movements of files and no changes in imports of other java files. on <ok> in the preview it only moves the file(s) (as indicated ) without changing referencing imports.
|
resolved fixed
|
386c5c6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-17T14:02:05Z | 2003-01-17T10:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/reorg/JdtMoveAction.java
|
package org.eclipse.jdt.internal.ui.reorg;
import java.lang.reflect.InvocationTargetException;
import java.util.Iterator;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.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.Shell;
import org.eclipse.jface.dialogs.DialogSettings;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.MoveProjectAction;
import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.StandardJavaElementContentProvider;
import org.eclipse.jdt.internal.corext.Assert;
import org.eclipse.jdt.internal.corext.refactoring.base.RefactoringStatus;
import org.eclipse.jdt.internal.corext.refactoring.reorg.MoveRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgUtils;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation;
import org.eclipse.jdt.internal.ui.refactoring.QualifiedNameComponent;
import org.eclipse.jdt.internal.ui.refactoring.RefactoringMessages;
import org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard;
import org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog;
import org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardPage;
import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringErrorDialogUtil;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
public class JdtMoveAction extends ReorgDestinationAction {
private boolean fShowPreview= false;
public JdtMoveAction(IWorkbenchSite site) {
super(site);
setText(ReorgMessages.getString("moveAction.label"));//$NON-NLS-1$
}
public boolean canOperateOn(IStructuredSelection selection) {
if (selection.isEmpty())
return false;
if (ClipboardActionUtil.hasOnlyProjects(selection))
return selection.size() == 1;
else
return super.canOperateOn(selection);
}
protected void run(IStructuredSelection selection) {
if (ClipboardActionUtil.hasOnlyProjects(selection)){
moveProject(selection);
} else {
super.run(selection);
}
}
/* non java-doc
* see @ReorgDestinationAction#isOkToProceed
*/
String getActionName() {
return ReorgMessages.getString("moveAction.name"); //$NON-NLS-1$
}
/* non java-doc
* see @ReorgDestinationAction#getDestinationDialogMessage
*/
String getDestinationDialogMessage() {
return ReorgMessages.getString("moveAction.destination.label"); //$NON-NLS-1$
}
/* non java-doc
* see @ReorgDestinationAction#createRefactoring
*/
ReorgRefactoring createRefactoring(List elements){
return new MoveRefactoring(elements, JavaPreferencesSettings.getCodeGenerationSettings());
}
ElementTreeSelectionDialog createDestinationSelectionDialog(Shell parent, ILabelProvider labelProvider, StandardJavaElementContentProvider cp, ReorgRefactoring refactoring){
return new MoveDestinationDialog(parent, labelProvider, cp, (MoveRefactoring)refactoring);
}
/* non java-doc
* see @ReorgDestinationAction#isOkToProceed
*/
protected boolean isOkToProceed(ReorgRefactoring refactoring) throws JavaModelException{
return (isOkToMoveReadOnly(refactoring));
}
protected void setShowPreview(boolean showPreview) {
fShowPreview = showPreview;
}
private static boolean isOkToMoveReadOnly(ReorgRefactoring refactoring){
if (! hasReadOnlyElements(refactoring))
return true;
return MessageDialog.openQuestion(
JavaPlugin.getActiveWorkbenchShell(),
ReorgMessages.getString("moveAction.checkMove"), //$NON-NLS-1$
ReorgMessages.getString("moveAction.error.readOnly")); //$NON-NLS-1$
}
private static boolean hasReadOnlyElements(ReorgRefactoring refactoring){
for (Iterator iter= refactoring.getElementsToReorg().iterator(); iter.hasNext(); ){
if (ReorgUtils.shouldConfirmReadOnly(iter.next()))
return true;
}
return false;
}
/* non java-doc
* @see ReorgDestinationAction#doReorg(ReorgRefactoring)
*/
void doReorg(ReorgRefactoring refactoring) throws JavaModelException{
if (fShowPreview){
//XX incorrect help
RefactoringWizard wizard= new RefactoringWizard(refactoring, ReorgMessages.getString("JdtMoveAction.move"), IJavaHelpContextIds.MOVE_CU_ERROR_WIZARD_PAGE); //$NON-NLS-1$
wizard.setChangeCreationCancelable(false);
new RefactoringWizardDialog(JavaPlugin.getActiveWorkbenchShell(), wizard).open();
return;
}
CheckConditionsOperation runnable= new CheckConditionsOperation(refactoring, CheckConditionsOperation.PRECONDITIONS);
try {
PlatformUI.getWorkbench().getActiveWorkbenchWindow().run(false, false, runnable);
} catch (InvocationTargetException e) {
ExceptionHandler.handle(e, getShell(), ReorgMessages.getString("JdtMoveAction.move"), ReorgMessages.getString("JdtMoveAction.exception")); //$NON-NLS-1$ //$NON-NLS-2$
return;
} catch (InterruptedException e) {
Assert.isTrue(false); //cannot happen - not cancelable
}
RefactoringStatus status= runnable.getStatus();
if (status == null)
return;
if (status.hasFatalError())
RefactoringErrorDialogUtil.open(ReorgMessages.getString("JdtMoveAction.move"), status);//$NON-NLS-1$
else
super.doReorg(refactoring);
}
private void moveProject(IStructuredSelection selection){
MoveProjectAction action= new MoveProjectAction(JavaPlugin.getActiveWorkbenchShell());
action.selectionChanged(selection);
action.run();
}
//--- static inner classes
private class MoveDestinationDialog extends ElementTreeSelectionDialog {
private static final int PREVIEW_ID= IDialogConstants.CLIENT_ID + 1;
private MoveRefactoring fRefactoring;
private Button fReferenceCheckbox;
private Button fQualifiedNameCheckbox;
private QualifiedNameComponent fQualifiedNameComponent;
private Button fPreview;
MoveDestinationDialog(Shell parent, ILabelProvider labelProvider, ITreeContentProvider contentProvider, MoveRefactoring refactoring){
super(parent, labelProvider, contentProvider);
fRefactoring= refactoring;
fShowPreview= false;//from outter instance
setDoubleClickSelects(false);
}
protected void updateOKStatus() {
super.updateOKStatus();
try{
Button okButton= getOkButton();
boolean okEnabled= okButton.getEnabled();
fRefactoring.setDestination(getFirstResult());
fReferenceCheckbox.setEnabled(okEnabled && canUpdateReferences());
fRefactoring.setUpdateReferences(fReferenceCheckbox.getEnabled() && fReferenceCheckbox.getSelection());
if (fQualifiedNameCheckbox != null) {
boolean enabled= okEnabled && fRefactoring.canEnableQualifiedNameUpdating();
fQualifiedNameCheckbox.setEnabled(enabled);
if (enabled) {
fQualifiedNameComponent.setEnabled(fRefactoring.getUpdateQualifiedNames());
if (fRefactoring.getUpdateQualifiedNames())
okButton.setEnabled(false);
} else {
fQualifiedNameComponent.setEnabled(false);
}
fRefactoring.setUpdateQualifiedNames(fQualifiedNameCheckbox.getEnabled() && fQualifiedNameCheckbox.getSelection());
}
boolean preview= okEnabled;
if (preview)
preview=
fRefactoring.getUpdateQualifiedNames() && fRefactoring.canEnableQualifiedNameUpdating() ||
fReferenceCheckbox.getSelection() && fRefactoring.canUpdateReferences();
fPreview.setEnabled(preview);
} catch (JavaModelException e){
ExceptionHandler.handle(e, ReorgMessages.getString("JdtMoveAction.move"), ReorgMessages.getString("JdtMoveAction.exception")); //$NON-NLS-1$ //$NON-NLS-2$
}
}
protected void buttonPressed(int buttonId) {
fShowPreview= (buttonId == PREVIEW_ID);
super.buttonPressed(buttonId);
if (buttonId == PREVIEW_ID)
close();
}
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
WorkbenchHelp.setHelp(newShell, IJavaHelpContextIds.MOVE_DESTINATION_DIALOG);
}
protected void createButtonsForButtonBar(Composite parent) {
fPreview= createButton(parent, PREVIEW_ID, ReorgMessages.getString("JdtMoveAction.preview"), false); //$NON-NLS-1$
super.createButtonsForButtonBar(parent);
}
protected Control createDialogArea(Composite parent) {
Composite result= (Composite)super.createDialogArea(parent);
addUpdateReferenceComponent(result);
addUpdateQualifiedNameComponent(result, ((GridLayout)result.getLayout()).marginWidth);
return result;
}
private void addUpdateReferenceComponent(Composite result) {
fReferenceCheckbox= new Button(result, SWT.CHECK);
fReferenceCheckbox.setText(ReorgMessages.getString("JdtMoveAction.update_references")); //$NON-NLS-1$
fReferenceCheckbox.setSelection(true);
fReferenceCheckbox.setEnabled(canUpdateReferences());
fReferenceCheckbox.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
fRefactoring.setUpdateReferences(((Button)e.widget).getSelection());
updateOKStatus();
}
});
}
private boolean canUpdateReferences() {
try{
return fRefactoring.canUpdateReferences();
} catch (JavaModelException e){
return false;
}
}
private void addUpdateQualifiedNameComponent(Composite parent, int marginWidth) {
if (!fRefactoring.canUpdateQualifiedNames())
return;
fQualifiedNameCheckbox= new Button(parent, SWT.CHECK);
int indent= marginWidth + fQualifiedNameCheckbox.computeSize(SWT.DEFAULT, SWT.DEFAULT).x;
fQualifiedNameCheckbox.setText(RefactoringMessages.getString("RenameInputWizardPage.update_qualified_names")); //$NON-NLS-1$
fQualifiedNameCheckbox.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
fQualifiedNameCheckbox.setSelection(fRefactoring.getUpdateQualifiedNames());
fQualifiedNameComponent= new QualifiedNameComponent(parent, SWT.NONE, fRefactoring, getRefactoringSettings());
fQualifiedNameComponent.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
GridData gd= (GridData)fQualifiedNameComponent.getLayoutData();
gd.horizontalAlignment= GridData.FILL;
gd.horizontalIndent= indent;
fQualifiedNameComponent.setEnabled(false);
fQualifiedNameCheckbox.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
boolean enabled= ((Button)e.widget).getSelection();
fQualifiedNameComponent.setEnabled(enabled);
fRefactoring.setUpdateQualifiedNames(enabled);
updateOKStatus();
}
});
}
protected IDialogSettings getRefactoringSettings() {
IDialogSettings settings= JavaPlugin.getDefault().getDialogSettings();
if (settings == null)
return null;
IDialogSettings result= settings.getSection(RefactoringWizardPage.REFACTORING_SETTINGS);
if (result == null) {
result= new DialogSettings(RefactoringWizardPage.REFACTORING_SETTINGS);
settings.addSection(result);
}
return result;
}
}
}
|
29,698 |
Bug 29698 drag and drop of java files between packages in package explorer doesn't work
|
the <preview> <ok> <cancel> dialog shows up, but <ok> has the same effect as <cancel> and <preview> would only show movements of files and no changes in imports of other java files. on <ok> in the preview it only moves the file(s) (as indicated ) without changing referencing imports.
|
resolved fixed
|
386c5c6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-17T14:02:05Z | 2003-01-17T10:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/reorg/ReorgDestinationAction.java
| |
29,698 |
Bug 29698 drag and drop of java files between packages in package explorer doesn't work
|
the <preview> <ok> <cancel> dialog shows up, but <ok> has the same effect as <cancel> and <preview> would only show movements of files and no changes in imports of other java files. on <ok> in the preview it only moves the file(s) (as indicated ) without changing referencing imports.
|
resolved fixed
|
386c5c6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-17T14:02:05Z | 2003-01-17T10:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/refactoring/RenameSupport.java
|
/*******************************************************************************
* Copyright (c) 2002 International Business Machines Corp. 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.refactoring;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableContext;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
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.internal.corext.refactoring.base.RefactoringStatus;
import org.eclipse.jdt.internal.corext.refactoring.rename.RenameCompilationUnitRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.rename.RenameFieldRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.rename.RenameJavaProjectRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.rename.RenameMethodRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.rename.RenamePackageRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.rename.RenameSourceFolderRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.rename.RenameTypeRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.tagging.IRenameRefactoring;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.refactoring.RefactoringExecutionHelper;
import org.eclipse.jdt.internal.ui.refactoring.RefactoringPreferences;
import org.eclipse.jdt.internal.ui.refactoring.RefactoringSupport;
import org.eclipse.jdt.internal.ui.reorg.IRefactoringRenameSupport;
/**
* Central access point to execute rename refactorings.
*
* @since 2.1
*/
public class RenameSupport {
private IRefactoringRenameSupport fSupport;
private IJavaElement fElement;
private RefactoringStatus fPreCheckStatus;
/**
* Executes some light weight precondition checking. If the returned status
* is an error then the refactoring can't be executed at all. However,
* returning an OK status doesn't guarantee that the refactoring can be
* executed. It may still fail while performing the exhaustive precondition
* checking done inside the methods <code>openDialog</code> or
* <code>perform</code>.
*
* The method is mainly used to determine enable/disablement of actions.
*
* @return the result of the light weight precondition checking.
*
* @throws if an unexpected exception occurs while performing the checking.
*
* @see #openDialog(Shell)
* @see #perform(Shell, IRunnableContext)
*/
public IStatus preCheck() throws CoreException {
ensureChecked();
if (fPreCheckStatus.hasFatalError())
return fPreCheckStatus.getFirstEntry(RefactoringStatus.FATAL).asStatus();
else
return new Status(IStatus.OK, JavaPlugin.getPluginId(), 0, "", null);
}
/**
* Opens the refactoring dialog for this rename support.
*
* @param parent a shell used as a parent for the refactoring dialog.
* @throws CoreException if an unexpected exception occurs while opening the
* dialog.
*/
public void openDialog(Shell parent) throws CoreException {
ensureChecked();
if (fPreCheckStatus.hasFatalError()) {
showInformation(parent, fPreCheckStatus);
return;
}
fSupport.rename(parent, fElement);
}
/**
* Executes the rename refactoring without showing a dialog to gather
* additional user input (e.g. the new name of the <tt>IJavaElement</tt>,
* ...). Only an error dialog is shown (if necessary) to present the result
* of the refactoring's full precondition checking.
*
* @param parent a shell used as a parent for the error dialog.
* @param context a <tt>IRunnableContext</tt> to execute the operation.
*
* @throws InterruptedException if the operation has been canceled by the
* user.
* @throws InvocationTargetException if an error occured while executing the
* operation.
*
* @see #openDialog(Shell)
* @see IRunnableContext#run(boolean, boolean, org.eclipse.jface.operation.IRunnableWithProgress)
*/
public void perform(Shell parent, IRunnableContext context) throws InterruptedException, InvocationTargetException {
try {
ensureChecked();
if (fPreCheckStatus.hasFatalError()) {
showInformation(parent, fPreCheckStatus);
return;
}
} catch (CoreException e){
throw new InvocationTargetException(e);
}
RefactoringExecutionHelper helper= new RefactoringExecutionHelper(fSupport.getRefactoring(),
RefactoringPreferences.getStopSeverity(), parent, context);
helper.perform();
}
/** Flag indication that no additional update is to be performed. */
public static final int NONE= 0;
/** Flag indicating that references are to be updated as well. */
public static final int UPDATE_REFERENCES= 1 << 0;
/** Flag indicating that Java doc comments are to be updated as well. */
public static final int UPDATE_JAVADOC_COMMENTS= 1 << 1;
/** Flag indicating that regular comments are to be updated as well. */
public static final int UPDATE_REGULAR_COMMENTS= 1 << 2;
/** Flag indicating that string literals are to be updated as well. */
public static final int UPDATE_STRING_LITERALS= 1 << 3;
/** Flag indicating that the getter method is to be updated as well. */
public static final int UPDATE_GETTER_METHOD= 1 << 4;
/** Flag indicating that the setter method is to be updated as well. */
public static final int UPDATE_SETTER_METHOD= 1 << 5;
private RenameSupport(IRefactoringRenameSupport support, IJavaElement element) {
fSupport= support;
fElement= element;
}
/**
* Creates a new rename support for the given <tt>IJavaProject</tt>.
*
* @param project the <tt>IJavaProject</tt> to be renamed.
* @param newName the project's new name. <code>null</code> is a valid
* value indicating that no new name is provided.
* @param flags flags controlling additional parameters. Valid flags are
* <code>UPDATE_REFERENCES</code> or <code>NONE</code>.
* @return the <tt>RenameSupport</tt>.
* @throws CoreException if an unexpected error occured while creating
* the <tt>RenameSupport</tt>.
*/
public static RenameSupport create(IJavaProject project, String newName, int flags) throws CoreException {
RefactoringSupport.JavaProject support= new RefactoringSupport.JavaProject(project);
RenameJavaProjectRefactoring refactoring= support.getSpecificRefactoring();
setNewName(refactoring, newName);
refactoring.setUpdateReferences(updateReferences(flags));
return new RenameSupport(support, project);
}
/**
* Creates a new rename support for the given <tt>IPackageFragmentRoot</tt>.
*
* @param root the <tt>IPackageFragmentRoot</tt> to be renamed.
* @param newName the package fragment roor's new name. <code>null</code> is
* a valid value indicating that no new name is provided.
* @return the <tt>RenameSupport</tt>.
* @throws CoreException if an unexpected error occured while creating
* the <tt>RenameSupport</tt>.
*/
public static RenameSupport create(IPackageFragmentRoot root, String newName) throws CoreException {
RefactoringSupport.SourceFolder support= new RefactoringSupport.SourceFolder(root);
RenameSourceFolderRefactoring refactoring= support.getSpecificRefactoring();
setNewName(refactoring, newName);
return new RenameSupport(support, root);
}
/**
* Creates a new rename support for the given <tt>IPackageFragment</tt>.
*
* @param fragment the <tt>IPackageFragment</tt> to be renamed.
* @param newName the package fragement's new name. <code>null</code> is a
* valid value indicating that no new name is provided.
* @param flags flags controlling additional parameters. Valid flags are
* <code>UPDATE_REFERENCES</code>, <code>UPDATE_JAVADOC_COMMENTS</code>,
* <code>UPDATE_REGULAR_COMMENTS</code> and
* <code>UPDATE_STRING_LITERALS</code>, or their bitwise OR, or
* <code>NONE</code>.
* @return the <tt>RenameSupport</tt>.
* @throws CoreException if an unexpected error occured while creating
* the <tt>RenameSupport</tt>.
*/
public static RenameSupport create(IPackageFragment fragment, String newName, int flags) throws CoreException {
RefactoringSupport.PackageFragment support= new RefactoringSupport.PackageFragment(fragment);
RenamePackageRefactoring refactoring= support.getSpecificRefactoring();
setNewName(refactoring, newName);
refactoring.setUpdateReferences(updateReferences(flags));
refactoring.setUpdateJavaDoc(updateJavadocComments(flags));
refactoring.setUpdateComments(updateRegularComments(flags));
refactoring.setUpdateStrings(updateStringLiterals(flags));
return new RenameSupport(support, fragment);
}
/**
* Creates a new rename support for the given <tt>ICompilationUnit</tt>.
*
* @param unit the <tt>ICompilationUnit</tt> to be renamed.
* @param newName the compilation unit's new name. <code>null</code> is a
* valid value indicating that no new name is provided.
* @param flags flags controlling additional parameters. Valid flags are
* <code>UPDATE_REFERENCES</code>, <code>UPDATE_JAVADOC_COMMENTS</code>,
* <code>UPDATE_REGULAR_COMMENTS</code> and
* <code>UPDATE_STRING_LITERALS</code>, or their bitwise OR, or
* <code>NONE</code>.
* @return the <tt>RenameSupport</tt>.
* @throws CoreException if an unexpected error occured while creating
* the <tt>RenameSupport</tt>.
*/
public static RenameSupport create(ICompilationUnit unit, String newName, int flags) throws CoreException {
RefactoringSupport.CompilationUnit support= new RefactoringSupport.CompilationUnit(unit);
RenameCompilationUnitRefactoring refactoring= support.getSpecificRefactoring();
setNewName(refactoring, newName);
refactoring.setUpdateReferences(updateReferences(flags));
refactoring.setUpdateJavaDoc(updateJavadocComments(flags));
refactoring.setUpdateComments(updateRegularComments(flags));
refactoring.setUpdateStrings(updateStringLiterals(flags));
return new RenameSupport(support, unit);
}
/**
* Creates a new rename support for the given <tt>IType</tt>.
*
* @param type the <tt>IType</tt> to be renamed.
* @param newName the type's new name. <code>null</code> is a valid value
* indicating that no new name is provided.
* @param flags flags controlling additional parameters. Valid flags are
* <code>UPDATE_REFERENCES</code>, <code>UPDATE_JAVADOC_COMMENTS</code>,
* <code>UPDATE_REGULAR_COMMENTS</code> and
* <code>UPDATE_STRING_LITERALS</code>, or their bitwise OR, or
* <code>NONE</code>.
* @return the <tt>RenameSupport</tt>.
* @throws CoreException if an unexpected error occured while creating
* the <tt>RenameSupport</tt>.
*/
public static RenameSupport create(IType type, String newName, int flags) throws CoreException {
RefactoringSupport.Type support= new RefactoringSupport.Type(type);
RenameTypeRefactoring refactoring= support.getSpecificRefactoring();
setNewName(refactoring, newName);
refactoring.setUpdateReferences(updateReferences(flags));
refactoring.setUpdateJavaDoc(updateJavadocComments(flags));
refactoring.setUpdateComments(updateRegularComments(flags));
refactoring.setUpdateStrings(updateStringLiterals(flags));
return new RenameSupport(support, type);
}
/**
* Creates a new rename support for the given <tt>IMethod</tt>.
*
* @param method the <tt>IMethod</tt> to be renamed.
* @param newName the method's new name. <code>null</code> is a valid value
* indicating that no new name is provided.
* @param flags flags controlling additional parameters. Valid flags are
* <code>UPDATE_REFERENCES</code> or <code>NONE</code>.
* @return the <tt>RenameSupport</tt>.
* @throws CoreException if an unexpected error occured while creating
* the <tt>RenameSupport</tt>.
*/
public static RenameSupport create(IMethod method, String newName, int flags) throws CoreException {
RefactoringSupport.Method support= new RefactoringSupport.Method(method);
RenameMethodRefactoring refactoring= support.getSpecificRefactoring();
setNewName(refactoring, newName);
refactoring.setUpdateReferences(updateReferences(flags));
return new RenameSupport(support, method);
}
/**
* Creates a new rename support for the given <tt>IField</tt>.
*
* @param method the <tt>IField</tt> to be renamed.
* @param newName the field's new name. <code>null</code> is a valid value
* indicating that no new name is provided.
* @param flags flags controlling additional parameters. Valid flags are
* <code>UPDATE_REFERENCES</code>, <code>UPDATE_JAVADOC_COMMENTS</code>,
* <code>UPDATE_REGULAR_COMMENTS</code>,
* <code>UPDATE_STRING_LITERALS</code>, </code>UPDATE_GETTER_METHOD</code>
* and </code>UPDATE_SETTER_METHOD</code>, or their bitwise OR, or
* <code>NONE</code>.
* @return the <tt>RenameSupport</tt>.
* @throws CoreException if an unexpected error occured while creating
* the <tt>RenameSupport</tt>.
*/
public static RenameSupport create(IField field, String newName, int flags) throws CoreException {
RefactoringSupport.Field support= new RefactoringSupport.Field(field);
RenameFieldRefactoring refactoring= support.getSpecificRefactoring();
setNewName(refactoring, newName);
refactoring.setUpdateReferences(updateReferences(flags));
refactoring.setUpdateJavaDoc(updateJavadocComments(flags));
refactoring.setUpdateComments(updateRegularComments(flags));
refactoring.setUpdateStrings(updateStringLiterals(flags));
refactoring.setRenameGetter(updateGetterMethod(flags));
refactoring.setRenameSetter(updateSetterMethod(flags));
return new RenameSupport(support, field);
}
/**
* Creates a new <tt>RenameSupport</tt> for the given <tt>IJavaElement</tt>
* by forwarding the creation to one of the concrete create methods
* depending on the type of the given <tt>IJavaElement</tt>.
* @param element the <tt>IJavaElement</tt> to be renamed
* @param newName the Java element's new name. <code>null</code> is a valid
* value indicating that no new name is provided.
* @param flags flags controlling additional parameters. For a list of valid
* flags see the corresponding create methods of this class.
* @return the <tt>RenameSupport</tt>.
* @throws CoreException if an unexpected error occured while creating
* the <tt>RenameSupport</tt>.
*
* @see #create(IJavaProject, int)
* @see #create(IPackageFragmentRoot)
* @see #create(IPackageFragment, int)
* @see #create(ICompilationUnit, int)
* @see #create(IType, int)
* @see #create(IMethod, int)
* @see #create(IField, int)
*/
public static RenameSupport create(IJavaElement element, String newName, int flags) throws CoreException {
switch (element.getElementType()) {
case IJavaElement.JAVA_PROJECT:
return create((IJavaProject)element, newName, flags);
case IJavaElement.PACKAGE_FRAGMENT_ROOT:
return create((IPackageFragmentRoot)element, newName);
case IJavaElement.PACKAGE_FRAGMENT:
return create((IPackageFragment)element, newName, flags);
case IJavaElement.COMPILATION_UNIT:
return create((ICompilationUnit)element, newName, flags);
case IJavaElement.TYPE:
return create((IType)element, newName, flags);
case IJavaElement.METHOD:
return create((IMethod)element, newName, flags);
case IJavaElement.FIELD:
return create((IField)element, newName, flags);
}
return null;
}
private static void setNewName(IRenameRefactoring refactoring, String newName) {
if (newName != null)
refactoring.setNewName(newName);
}
private static boolean updateReferences(int flags) {
return (flags & UPDATE_REFERENCES) != 0;
}
private static boolean updateJavadocComments(int flags) {
return (flags & UPDATE_JAVADOC_COMMENTS) != 0;
}
private static boolean updateRegularComments(int flags) {
return (flags & UPDATE_REGULAR_COMMENTS) != 0;
}
private static boolean updateStringLiterals(int flags) {
return (flags & UPDATE_STRING_LITERALS) != 0;
}
private static boolean updateGetterMethod(int flags) {
return (flags & UPDATE_GETTER_METHOD) != 0;
}
private static boolean updateSetterMethod(int flags) {
return (flags & UPDATE_SETTER_METHOD) != 0;
}
private void ensureChecked() throws CoreException {
if (fPreCheckStatus == null)
fPreCheckStatus= fSupport.lightCheck();
}
private void showInformation(Shell parent, RefactoringStatus status) {
String message= status.getFirstMessage(RefactoringStatus.FATAL);
MessageDialog.openInformation(parent, fSupport.getRefactoring().getName(), message);
}
}
|
28,054 |
Bug 28054 awkward to change default output folder
|
Build I20021210 1. Create a new Java project P1 On the Java Settings page hit the Browse next to Default output folder. Observe: The dialog is empty, shows an error "No entries available", and only allows Cancel. Expectation: As with other dialogs, it would be better if I had an opportunity to create folders at this time. unable to create a linked output folder
|
resolved fixed
|
aa4b231
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-17T16:50:28Z | 2002-12-10T22:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/NewProjectCreationWizard.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.wizards;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExecutableExtension;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.dialogs.WizardNewProjectCreationPage;
import org.eclipse.ui.wizards.newresource.BasicNewProjectResourceWizard;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
public class NewProjectCreationWizard extends NewElementWizard implements IExecutableExtension {
public static final String NEW_PROJECT_WIZARD_ID= "org.eclipse.jdt.ui.wizards.NewProjectCreationWizard"; //$NON-NLS-1$
private NewProjectCreationWizardPage fJavaPage;
private WizardNewProjectCreationPage fMainPage;
private IConfigurationElement fConfigElement;
public NewProjectCreationWizard() {
super();
setDefaultPageImageDescriptor(JavaPluginImages.DESC_WIZBAN_NEWJPRJ);
setDialogSettings(JavaPlugin.getDefault().getDialogSettings());
setWindowTitle(NewWizardMessages.getString("NewProjectCreationWizard.title")); //$NON-NLS-1$
}
/*
* @see Wizard#addPages
*/
public void addPages() {
super.addPages();
fMainPage= new WizardNewProjectCreationPage("NewProjectCreationWizard"); //$NON-NLS-1$
fMainPage.setTitle(NewWizardMessages.getString("NewProjectCreationWizard.MainPage.title")); //$NON-NLS-1$
fMainPage.setDescription(NewWizardMessages.getString("NewProjectCreationWizard.MainPage.description")); //$NON-NLS-1$
addPage(fMainPage);
fJavaPage= new NewProjectCreationWizardPage(fMainPage);
addPage(fJavaPage);
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.wizards.NewElementWizard#finishPage(org.eclipse.core.runtime.IProgressMonitor)
*/
protected void finishPage(IProgressMonitor monitor) throws InterruptedException, CoreException {
fJavaPage.createProject(monitor); // use the full progress monitor
BasicNewProjectResourceWizard.updatePerspective(fConfigElement);
selectAndReveal(fJavaPage.getJavaProject().getProject());
}
protected void handleFinishException(Shell shell, InvocationTargetException e) {
String title= NewWizardMessages.getString("NewProjectCreationWizard.op_error.title"); //$NON-NLS-1$
String message= NewWizardMessages.getString("NewProjectCreationWizard.op_error.message"); //$NON-NLS-1$
ExceptionHandler.handle(e, getShell(), title, message);
}
/*
* Stores the configuration element for the wizard. The config element will be used
* in <code>performFinish</code> to set the result perspective.
*/
public void setInitializationData(IConfigurationElement cfig, String propertyName, Object data) {
fConfigElement= cfig;
}
/* (non-Javadoc)
* @see IWizard#performCancel()
*/
public boolean performCancel() {
fJavaPage.performCancel();
return super.performCancel();
}
}
|
28,054 |
Bug 28054 awkward to change default output folder
|
Build I20021210 1. Create a new Java project P1 On the Java Settings page hit the Browse next to Default output folder. Observe: The dialog is empty, shows an error "No entries available", and only allows Cancel. Expectation: As with other dialogs, it would be better if I had an opportunity to create folders at this time. unable to create a linked output folder
|
resolved fixed
|
aa4b231
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-17T16:50:28Z | 2002-12-10T22:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/NewProjectCreationWizardPage.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.wizards;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.ui.dialogs.WizardNewProjectCreationPage;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.ui.wizards.JavaCapabilityConfigurationPage;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.wizards.buildpaths.BuildPathsBlock;
/**
* As addition to the JavaCapabilityConfigurationPage, the wizard checks if an existing external
* location was specified and offers to do an early project creation so that classpath can be detected.
*/
public class NewProjectCreationWizardPage extends JavaCapabilityConfigurationPage {
private WizardNewProjectCreationPage fMainPage;
private IPath fCurrProjectLocation;
private boolean fProjectCreated;
/**
* Constructor for ProjectWizardPage.
*/
public NewProjectCreationWizardPage(WizardNewProjectCreationPage mainPage) {
super();
fMainPage= mainPage;
fCurrProjectLocation= fMainPage.getLocationPath();
fProjectCreated= false;
}
private boolean canDetectExistingClassPath(IPath projLocation) {
return projLocation.toFile().exists() && !Platform.getLocation().equals(projLocation);
}
private void update() {
IPath projLocation= fMainPage.getLocationPath();
if (!projLocation.equals(fCurrProjectLocation) && canDetectExistingClassPath(projLocation)) {
String title= NewWizardMessages.getString("NewProjectCreationWizardPage.EarlyCreationDialog.title"); //$NON-NLS-1$
String description= NewWizardMessages.getString("NewProjectCreationWizardPage.EarlyCreationDialog.description"); //$NON-NLS-1$
if (MessageDialog.openQuestion(getShell(), title, description)) {
createAndDetect();
}
}
fCurrProjectLocation= projLocation;
IJavaProject prevProject= getJavaProject();
IProject currProject= fMainPage.getProjectHandle();
if ((prevProject == null) || !currProject.equals(prevProject.getProject())) {
init(JavaCore.create(currProject), null, null, false);
}
}
private void createAndDetect() {
IRunnableWithProgress op= new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
if (monitor == null)
monitor= new NullProgressMonitor();
monitor.beginTask(NewWizardMessages.getString("NewProjectCreationWizardPage.EarlyCreationOperation.desc"), 3); //$NON-NLS-1$
try {
BuildPathsBlock.createProject(fMainPage.getProjectHandle(), fMainPage.getLocationPath(), new SubProgressMonitor(monitor, 1));
fProjectCreated= true;
initFromExistingStructures(new SubProgressMonitor(monitor, 2));
} catch (CoreException e) {
throw new InvocationTargetException(e);
}
}
};
try {
getContainer().run(false, true, op);
} catch (InvocationTargetException e) {
String title= NewWizardMessages.getString("NewProjectCreationWizardPage.EarlyCreationOperation.error.title"); //$NON-NLS-1$
String message= NewWizardMessages.getString("NewProjectCreationWizardPage.EarlyCreationOperation.error.desc"); //$NON-NLS-1$
ExceptionHandler.handle(e, getShell(), title, message);
} catch (InterruptedException e) {
// cancel pressed
}
}
/* (non-Javadoc)
* @see IDialogPage#setVisible(boolean)
*/
public void setVisible(boolean visible) {
if (visible) {
update();
}
super.setVisible(visible);
}
/* (non-Javadoc)
* @see IWizardPage#getPreviousPage()
*/
public IWizardPage getPreviousPage() {
if (fProjectCreated) {
return null;
}
return super.getPreviousPage();
}
public void createProject(IProgressMonitor monitor) throws CoreException, InterruptedException {
if (monitor == null) {
monitor= new NullProgressMonitor();
}
try {
monitor.beginTask(NewWizardMessages.getString("NewProjectCreationWizardPage.NormalCreationOperation.desc"), 4); //$NON-NLS-1$
BuildPathsBlock.createProject(fMainPage.getProjectHandle(), fMainPage.getLocationPath(), new SubProgressMonitor(monitor, 1));
if (getJavaProject() == null) {
initFromExistingStructures(new SubProgressMonitor(monitor, 1));
} else {
monitor.worked(1);
}
configureJavaProject(new SubProgressMonitor(monitor, 2));
} finally {
monitor.done();
}
}
private void initFromExistingStructures(IProgressMonitor monitor) throws CoreException {
monitor.beginTask(NewWizardMessages.getString("NewProjectCreationWizardPage.DetectingClasspathOperation.desc"), 2); //$NON-NLS-1$
try {
IProject project= fMainPage.getProjectHandle();
if (project.getFile(".classpath").exists()) { //$NON-NLS-1$
init(JavaCore.create(project), null, null, false);
monitor.worked(2);
} else{
ClassPathDetector detector= new ClassPathDetector(project);
IClasspathEntry[] entries= detector.getClasspath();
IPath outputLocation= detector.getOutputLocation();
init(JavaCore.create(project), outputLocation, entries, false);
monitor.worked(2);
}
} finally {
monitor.done();
}
}
/**
* Called from the wizard on cancel.
*/
public void performCancel() {
if (fProjectCreated) {
try {
fMainPage.getProjectHandle().delete(false, false, null);
} catch (CoreException e) {
JavaPlugin.log(e);
}
}
}
}
|
28,054 |
Bug 28054 awkward to change default output folder
|
Build I20021210 1. Create a new Java project P1 On the Java Settings page hit the Browse next to Default output folder. Observe: The dialog is empty, shows an error "No entries available", and only allows Cancel. Expectation: As with other dialogs, it would be better if I had an opportunity to create folders at this time. unable to create a linked output folder
|
resolved fixed
|
aa4b231
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-17T16:50:28Z | 2002-12-10T22:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/BuildPathsBlock.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.wizards.buildpaths;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.dialogs.ISelectionStatusValidator;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.model.WorkbenchContentProvider;
import org.eclipse.ui.model.WorkbenchLabelProvider;
import org.eclipse.ui.views.navigator.ResourceSorter;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaModelStatus;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaConventions;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.dialogs.StatusUtil;
import org.eclipse.jdt.internal.ui.util.CoreUtility;
import org.eclipse.jdt.internal.ui.util.PixelConverter;
import org.eclipse.jdt.internal.ui.util.TabFolderLayout;
import org.eclipse.jdt.internal.ui.viewsupport.ImageDisposer;
import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener;
import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages;
import org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator;
import org.eclipse.jdt.internal.ui.wizards.TypedViewerFilter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.CheckedListDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField;
public class BuildPathsBlock {
public static interface IRemoveOldBinariesQuery {
/**
* Do the callback. Returns <code>true</code> if .class files should be removed from the
* old output location.
*/
boolean doQuery(IPath oldOutputLocation) throws InterruptedException;
}
private IWorkspaceRoot fWorkspaceRoot;
private CheckedListDialogField fClassPathList;
private StringButtonDialogField fBuildPathDialogField;
private StatusInfo fClassPathStatus;
private StatusInfo fOutputFolderStatus;
private StatusInfo fBuildPathStatus;
private IJavaProject fCurrJProject;
private IPath fOutputLocationPath;
private IStatusChangeListener fContext;
private Control fSWTWidget;
private int fPageIndex;
private SourceContainerWorkbookPage fSourceContainerPage;
private ProjectsWorkbookPage fProjectsPage;
private LibrariesWorkbookPage fLibrariesPage;
private BuildPathBasePage fCurrPage;
public BuildPathsBlock(IStatusChangeListener context, int pageToShow) {
fWorkspaceRoot= JavaPlugin.getWorkspace().getRoot();
fContext= context;
fPageIndex= pageToShow;
fSourceContainerPage= null;
fLibrariesPage= null;
fProjectsPage= null;
fCurrPage= null;
BuildPathAdapter adapter= new BuildPathAdapter();
String[] buttonLabels= new String[] {
/* 0 */ NewWizardMessages.getString("BuildPathsBlock.classpath.up.button"), //$NON-NLS-1$
/* 1 */ NewWizardMessages.getString("BuildPathsBlock.classpath.down.button"), //$NON-NLS-1$
/* 2 */ null,
/* 3 */ NewWizardMessages.getString("BuildPathsBlock.classpath.checkall.button"), //$NON-NLS-1$
/* 4 */ NewWizardMessages.getString("BuildPathsBlock.classpath.uncheckall.button") //$NON-NLS-1$
};
fClassPathList= new CheckedListDialogField(null, buttonLabels, new CPListLabelProvider());
fClassPathList.setDialogFieldListener(adapter);
fClassPathList.setLabelText(NewWizardMessages.getString("BuildPathsBlock.classpath.label")); //$NON-NLS-1$
fClassPathList.setUpButtonIndex(0);
fClassPathList.setDownButtonIndex(1);
fClassPathList.setCheckAllButtonIndex(3);
fClassPathList.setUncheckAllButtonIndex(4);
fBuildPathDialogField= new StringButtonDialogField(adapter);
fBuildPathDialogField.setButtonLabel(NewWizardMessages.getString("BuildPathsBlock.buildpath.button")); //$NON-NLS-1$
fBuildPathDialogField.setDialogFieldListener(adapter);
fBuildPathDialogField.setLabelText(NewWizardMessages.getString("BuildPathsBlock.buildpath.label")); //$NON-NLS-1$
fBuildPathStatus= new StatusInfo();
fClassPathStatus= new StatusInfo();
fOutputFolderStatus= new StatusInfo();
fCurrJProject= null;
}
// -------- UI creation ---------
public Control createControl(Composite parent) {
fSWTWidget= parent;
PixelConverter converter= new PixelConverter(parent);
Composite composite= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
layout.marginWidth= 0;
layout.numColumns= 1;
composite.setLayout(layout);
TabFolder folder= new TabFolder(composite, SWT.NONE);
folder.setLayout(new TabFolderLayout());
folder.setLayoutData(new GridData(GridData.FILL_BOTH));
ImageRegistry imageRegistry= JavaPlugin.getDefault().getImageRegistry();
TabItem item;
fSourceContainerPage= new SourceContainerWorkbookPage(fWorkspaceRoot, fClassPathList, fBuildPathDialogField);
item= new TabItem(folder, SWT.NONE);
item.setText(NewWizardMessages.getString("BuildPathsBlock.tab.source")); //$NON-NLS-1$
item.setImage(imageRegistry.get(JavaPluginImages.IMG_OBJS_PACKFRAG_ROOT));
item.setData(fSourceContainerPage);
item.setControl(fSourceContainerPage.getControl(folder));
IWorkbench workbench= JavaPlugin.getDefault().getWorkbench();
Image projectImage= workbench.getSharedImages().getImage(ISharedImages.IMG_OBJ_PROJECT);
fProjectsPage= new ProjectsWorkbookPage(fClassPathList);
item= new TabItem(folder, SWT.NONE);
item.setText(NewWizardMessages.getString("BuildPathsBlock.tab.projects")); //$NON-NLS-1$
item.setImage(projectImage);
item.setData(fProjectsPage);
item.setControl(fProjectsPage.getControl(folder));
fLibrariesPage= new LibrariesWorkbookPage(fWorkspaceRoot, fClassPathList);
item= new TabItem(folder, SWT.NONE);
item.setText(NewWizardMessages.getString("BuildPathsBlock.tab.libraries")); //$NON-NLS-1$
item.setImage(imageRegistry.get(JavaPluginImages.IMG_OBJS_LIBRARY));
item.setData(fLibrariesPage);
item.setControl(fLibrariesPage.getControl(folder));
// a non shared image
Image cpoImage= JavaPluginImages.DESC_TOOL_CLASSPATH_ORDER.createImage();
composite.addDisposeListener(new ImageDisposer(cpoImage));
ClasspathOrderingWorkbookPage ordpage= new ClasspathOrderingWorkbookPage(fClassPathList);
item= new TabItem(folder, SWT.NONE);
item.setText(NewWizardMessages.getString("BuildPathsBlock.tab.order")); //$NON-NLS-1$
item.setImage(cpoImage);
item.setData(ordpage);
item.setControl(ordpage.getControl(folder));
if (fCurrJProject != null) {
fSourceContainerPage.init(fCurrJProject);
fLibrariesPage.init(fCurrJProject);
fProjectsPage.init(fCurrJProject);
}
Composite editorcomp= new Composite(composite, SWT.NONE);
DialogField[] editors= new DialogField[] { fBuildPathDialogField };
LayoutUtil.doDefaultLayout(editorcomp, editors, true, 0, 0);
int maxFieldWidth= converter.convertWidthInCharsToPixels(40);
LayoutUtil.setWidthHint(fBuildPathDialogField.getTextControl(null), maxFieldWidth);
LayoutUtil.setHorizontalGrabbing(fBuildPathDialogField.getTextControl(null));
editorcomp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
folder.setSelection(fPageIndex);
fCurrPage= (BuildPathBasePage) folder.getItem(fPageIndex).getData();
folder.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
tabChanged(e.item);
}
});
WorkbenchHelp.setHelp(composite, IJavaHelpContextIds.BUILD_PATH_BLOCK);
return composite;
}
private Shell getShell() {
if (fSWTWidget != null) {
return fSWTWidget.getShell();
}
return JavaPlugin.getActiveWorkbenchShell();
}
/**
* Initializes the classpath for the given project. Multiple calls to init are allowed,
* but all existing settings will be cleared and replace by the given or default paths.
* @param project The java project to configure. Does not have to exist.
* @param outputLocation The output location to be set in the page. If <code>null</code>
* is passed, jdt default settings are used, or - if the project is an existing Java project- the
* output location of the existing project
* @param classpathEntries The classpath entries to be set in the page. If <code>null</code>
* is passed, jdt default settings are used, or - if the project is an existing Java project - the
* classpath entries of the existing project
*/
public void init(IJavaProject jproject, IPath outputLocation, IClasspathEntry[] classpathEntries) {
fCurrJProject= jproject;
boolean projectExists= false;
List newClassPath= null;
try {
IProject project= fCurrJProject.getProject();
projectExists= (project.exists() && project.getFile(".classpath").exists()); //$NON-NLS-1$
if (projectExists) {
if (outputLocation == null) {
outputLocation= fCurrJProject.getOutputLocation();
}
if (classpathEntries == null) {
classpathEntries= fCurrJProject.getRawClasspath();
}
}
if (outputLocation == null) {
outputLocation= getDefaultBuildPath(jproject);
}
if (classpathEntries != null) {
newClassPath= getExistingEntries(classpathEntries);
}
} catch (CoreException e) {
JavaPlugin.log(e);
}
if (newClassPath == null) {
newClassPath= getDefaultClassPath(jproject);
}
List exportedEntries = new ArrayList();
for (int i= 0; i < newClassPath.size(); i++) {
CPListElement curr= (CPListElement) newClassPath.get(i);
if (curr.isExported() || curr.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
exportedEntries.add(curr);
}
}
// inits the dialog field
fBuildPathDialogField.setText(outputLocation.makeRelative().toString());
fBuildPathDialogField.enableButton(fCurrJProject.exists());
fClassPathList.setElements(newClassPath);
fClassPathList.setCheckedElements(exportedEntries);
if (fSourceContainerPage != null) {
fSourceContainerPage.init(fCurrJProject);
fProjectsPage.init(fCurrJProject);
fLibrariesPage.init(fCurrJProject);
}
doStatusLineUpdate();
}
private ArrayList getExistingEntries(IClasspathEntry[] classpathEntries) {
ArrayList newClassPath= new ArrayList();
for (int i= 0; i < classpathEntries.length; i++) {
IClasspathEntry curr= classpathEntries[i];
newClassPath.add(CPListElement.createFromExisting(curr, fCurrJProject));
}
return newClassPath;
}
// -------- public api --------
/**
* Returns the Java project. Can return <code>null<code> if the page has not
* been initialized.
*/
public IJavaProject getJavaProject() {
return fCurrJProject;
}
/**
* Returns the current output location. Note that the path returned must not be valid.
*/
public IPath getOutputLocation() {
return new Path(fBuildPathDialogField.getText()).makeAbsolute();
}
/**
* Returns the current class path (raw). Note that the entries returned must not be valid.
*/
public IClasspathEntry[] getRawClassPath() {
List elements= fClassPathList.getElements();
int nElements= elements.size();
IClasspathEntry[] entries= new IClasspathEntry[elements.size()];
for (int i= 0; i < nElements; i++) {
CPListElement currElement= (CPListElement) elements.get(i);
entries[i]= currElement.getClasspathEntry();
}
return entries;
}
public int getPageIndex() {
return fPageIndex;
}
// -------- evaluate default settings --------
private List getDefaultClassPath(IJavaProject jproj) {
List list= new ArrayList();
IResource srcFolder;
IPreferenceStore store= PreferenceConstants.getPreferenceStore();
String sourceFolderName= store.getString(PreferenceConstants.SRCBIN_SRCNAME);
if (store.getBoolean(PreferenceConstants.SRCBIN_FOLDERS_IN_NEWPROJ) && sourceFolderName.length() > 0) {
srcFolder= jproj.getProject().getFolder(sourceFolderName);
} else {
srcFolder= jproj.getProject();
}
list.add(new CPListElement(jproj, IClasspathEntry.CPE_SOURCE, srcFolder.getFullPath(), srcFolder));
IClasspathEntry[] jreEntries= PreferenceConstants.getDefaultJRELibrary();
list.addAll(getExistingEntries(jreEntries));
return list;
}
private IPath getDefaultBuildPath(IJavaProject jproj) {
IPreferenceStore store= PreferenceConstants.getPreferenceStore();
if (store.getBoolean(PreferenceConstants.SRCBIN_FOLDERS_IN_NEWPROJ)) {
String outputLocationName= store.getString(PreferenceConstants.SRCBIN_BINNAME);
return jproj.getProject().getFullPath().append(outputLocationName);
} else {
return jproj.getProject().getFullPath();
}
}
private class BuildPathAdapter implements IStringButtonAdapter, IDialogFieldListener {
// -------- IStringButtonAdapter --------
public void changeControlPressed(DialogField field) {
buildPathChangeControlPressed(field);
}
// ---------- IDialogFieldListener --------
public void dialogFieldChanged(DialogField field) {
buildPathDialogFieldChanged(field);
}
}
private void buildPathChangeControlPressed(DialogField field) {
if (field == fBuildPathDialogField) {
IContainer container= chooseContainer();
if (container != null) {
fBuildPathDialogField.setText(container.getFullPath().toString());
}
}
}
private void buildPathDialogFieldChanged(DialogField field) {
if (field == fClassPathList) {
updateClassPathStatus();
} else if (field == fBuildPathDialogField) {
updateOutputLocationStatus();
}
doStatusLineUpdate();
}
// -------- verification -------------------------------
private void doStatusLineUpdate() {
IStatus res= findMostSevereStatus();
fContext.statusChanged(res);
}
private IStatus findMostSevereStatus() {
return StatusUtil.getMostSevere(new IStatus[] { fClassPathStatus, fOutputFolderStatus, fBuildPathStatus });
}
/**
* Validates the build path.
*/
public void updateClassPathStatus() {
fClassPathStatus.setOK();
List elements= fClassPathList.getElements();
CPListElement entryMissing= null;
int nEntriesMissing= 0;
IClasspathEntry[] entries= new IClasspathEntry[elements.size()];
for (int i= elements.size()-1 ; i >= 0 ; i--) {
CPListElement currElement= (CPListElement)elements.get(i);
boolean isChecked= fClassPathList.isChecked(currElement);
if (currElement.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
if (!isChecked) {
fClassPathList.setCheckedWithoutUpdate(currElement, true);
}
} else {
currElement.setExported(isChecked);
}
entries[i]= currElement.getClasspathEntry();
if (currElement.isMissing()) {
nEntriesMissing++;
if (entryMissing == null) {
entryMissing= currElement;
}
}
}
if (nEntriesMissing > 0) {
if (nEntriesMissing == 1) {
fClassPathStatus.setWarning(NewWizardMessages.getFormattedString("BuildPathsBlock.warning.EntryMissing", entryMissing.getPath().toString())); //$NON-NLS-1$
} else {
fClassPathStatus.setWarning(NewWizardMessages.getFormattedString("BuildPathsBlock.warning.EntriesMissing", String.valueOf(nEntriesMissing))); //$NON-NLS-1$
}
}
/* if (fCurrJProject.hasClasspathCycle(entries)) {
fClassPathStatus.setWarning(NewWizardMessages.getString("BuildPathsBlock.warning.CycleInClassPath")); //$NON-NLS-1$
}
*/
updateBuildPathStatus();
}
/**
* Validates output location & build path.
*/
private void updateOutputLocationStatus() {
fOutputLocationPath= null;
String text= fBuildPathDialogField.getText();
if ("".equals(text)) { //$NON-NLS-1$
fOutputFolderStatus.setError(NewWizardMessages.getString("BuildPathsBlock.error.EnterBuildPath")); //$NON-NLS-1$
return;
}
IPath path= getOutputLocation();
fOutputLocationPath= path;
IResource res= fWorkspaceRoot.findMember(path);
if (res != null) {
// if exists, must be a folder or project
if (res.getType() == IResource.FILE) {
fOutputFolderStatus.setError(NewWizardMessages.getString("BuildPathsBlock.error.InvalidBuildPath")); //$NON-NLS-1$
return;
}
}
fOutputFolderStatus.setOK();
updateBuildPathStatus();
}
private void updateBuildPathStatus() {
List elements= fClassPathList.getElements();
IClasspathEntry[] entries= new IClasspathEntry[elements.size()];
for (int i= elements.size()-1 ; i >= 0 ; i--) {
CPListElement currElement= (CPListElement)elements.get(i);
entries[i]= currElement.getClasspathEntry();
}
IJavaModelStatus status= JavaConventions.validateClasspath(fCurrJProject, entries, fOutputLocationPath);
if (!status.isOK()) {
fBuildPathStatus.setError(status.getMessage());
return;
}
fBuildPathStatus.setOK();
}
// -------- creation -------------------------------
public static void createProject(IProject project, IPath locationPath, IProgressMonitor monitor) throws CoreException {
// create the project
try {
if (!project.exists()) {
IProjectDescription desc= project.getWorkspace().newProjectDescription(project.getName());
if (Platform.getLocation().equals(locationPath)) {
locationPath= null;
}
desc.setLocation(locationPath);
project.create(desc, monitor);
monitor= null;
}
if (!project.isOpen()) {
project.open(monitor);
monitor= null;
}
} finally {
if (monitor != null) {
monitor.done();
}
}
}
public static void addJavaNature(IProject project, IProgressMonitor monitor) throws CoreException {
if (!project.hasNature(JavaCore.NATURE_ID)) {
IProjectDescription description = project.getDescription();
String[] prevNatures= description.getNatureIds();
String[] newNatures= new String[prevNatures.length + 1];
System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length);
newNatures[prevNatures.length]= JavaCore.NATURE_ID;
description.setNatureIds(newNatures);
project.setDescription(description, monitor);
}
}
public void configureJavaProject(IProgressMonitor monitor) throws CoreException, InterruptedException {
if (monitor == null) {
monitor= new NullProgressMonitor();
}
monitor.beginTask(NewWizardMessages.getString("BuildPathsBlock.operationdesc"), 10); //$NON-NLS-1$
try {
Shell shell= null;
if (fSWTWidget != null && !fSWTWidget.getShell().isDisposed()) {
shell= fSWTWidget.getShell();
}
internalConfigureJavaProject(fClassPathList.getElements(), getOutputLocation(), shell, monitor);
} finally {
monitor.done();
}
}
/**
* Creates the Java project and sets the configured build path and output location.
* If the project already exists only build paths are updated.
*/
private void internalConfigureJavaProject(List classPathEntries, IPath outputLocation, Shell shell, IProgressMonitor monitor) throws CoreException, InterruptedException {
// 10 monitor steps to go
IRemoveOldBinariesQuery reorgQuery= null;
if (shell != null) {
reorgQuery= getRemoveOldBinariesQuery(shell);
}
// remove old .class files
if (reorgQuery != null) {
IPath oldOutputLocation= fCurrJProject.getOutputLocation();
if (!outputLocation.equals(oldOutputLocation)) {
IResource res= fWorkspaceRoot.findMember(oldOutputLocation);
if (res instanceof IContainer && hasClassfiles(res)) {
if (reorgQuery.doQuery(oldOutputLocation)) {
removeOldClassfiles(res);
}
}
}
}
// create and set the output path first
if (!fWorkspaceRoot.exists(outputLocation)) {
IFolder folder= fWorkspaceRoot.getFolder(outputLocation);
CoreUtility.createFolder(folder, true, true, null);
}
monitor.worked(2);
int nEntries= classPathEntries.size();
IClasspathEntry[] classpath= new IClasspathEntry[nEntries];
// create and set the class path
for (int i= 0; i < nEntries; i++) {
CPListElement entry= ((CPListElement)classPathEntries.get(i));
IResource res= entry.getResource();
if ((res instanceof IFolder) && !res.exists()) {
CoreUtility.createFolder((IFolder)res, true, true, null);
}
if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
IPath folderOutput= (IPath) entry.getAttribute(CPListElement.OUTPUT);
if (folderOutput != null && folderOutput.segmentCount() > 1) {
IFolder folder= fWorkspaceRoot.getFolder(folderOutput);
CoreUtility.createFolder((IFolder)folder, true, true, null);
}
}
classpath[i]= entry.getClasspathEntry();
// set javadoc location
URL javadocLocation= (URL) entry.getAttribute(CPListElement.JAVADOC);
IPath path= entry.getPath();
if (entry.getEntryKind() == IClasspathEntry.CPE_VARIABLE) {
path= JavaCore.getResolvedVariablePath(path);
}
if (path != null) {
JavaUI.setLibraryJavadocLocation(path, javadocLocation);
}
}
monitor.worked(1);
fCurrJProject.setRawClasspath(classpath, outputLocation, new SubProgressMonitor(monitor, 7));
}
public static boolean hasClassfiles(IResource resource) throws CoreException {
if (resource.isDerived()) { //$NON-NLS-1$
return true;
}
if (resource instanceof IContainer) {
IResource[] members= ((IContainer) resource).members();
for (int i= 0; i < members.length; i++) {
if (hasClassfiles(members[i])) {
return true;
}
}
}
return false;
}
public static void removeOldClassfiles(IResource resource) throws CoreException {
if (resource.isDerived()) {
resource.delete(false, null);
} else if (resource instanceof IContainer) {
IResource[] members= ((IContainer) resource).members();
for (int i= 0; i < members.length; i++) {
removeOldClassfiles(members[i]);
}
}
}
public static IRemoveOldBinariesQuery getRemoveOldBinariesQuery(final Shell shell) {
return new IRemoveOldBinariesQuery() {
public boolean doQuery(final IPath oldOutputLocation) throws InterruptedException {
final int[] res= new int[] { 1 };
shell.getDisplay().syncExec(new Runnable() {
public void run() {
String title= NewWizardMessages.getString("BuildPathsBlock.RemoveBinariesDialog.title"); //$NON-NLS-1$
String message= NewWizardMessages.getFormattedString("BuildPathsBlock.RemoveBinariesDialog.description", oldOutputLocation.toString()); //$NON-NLS-1$
MessageDialog dialog= new MessageDialog(shell, title, null, message, MessageDialog.QUESTION, new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL }, 2);
res[0]= dialog.open();
}
});
if (res[0] == 0) {
return true;
} else if (res[0] == 1) {
return false;
}
throw new InterruptedException();
}
};
}
// ---------- util method ------------
private IContainer chooseContainer() {
Class[] acceptedClasses= new Class[] { IProject.class, IFolder.class };
ISelectionStatusValidator validator= new TypedElementSelectionValidator(acceptedClasses, false);
IProject[] allProjects= fWorkspaceRoot.getProjects();
ArrayList rejectedElements= new ArrayList(allProjects.length);
IProject currProject= fCurrJProject.getProject();
for (int i= 0; i < allProjects.length; i++) {
if (!allProjects[i].equals(currProject)) {
rejectedElements.add(allProjects[i]);
}
}
ViewerFilter filter= new TypedViewerFilter(acceptedClasses, rejectedElements.toArray());
ILabelProvider lp= new WorkbenchLabelProvider();
ITreeContentProvider cp= new WorkbenchContentProvider();
IResource initSelection= null;
if (fOutputLocationPath != null) {
initSelection= fWorkspaceRoot.findMember(fOutputLocationPath);
}
FolderSelectionDialog dialog= new FolderSelectionDialog(getShell(), lp, cp);
dialog.setTitle(NewWizardMessages.getString("BuildPathsBlock.ChooseOutputFolderDialog.title")); //$NON-NLS-1$
dialog.setValidator(validator);
dialog.setMessage(NewWizardMessages.getString("BuildPathsBlock.ChooseOutputFolderDialog.description")); //$NON-NLS-1$
dialog.addFilter(filter);
dialog.setInput(fWorkspaceRoot);
dialog.setInitialSelection(initSelection);
dialog.setSorter(new ResourceSorter(ResourceSorter.NAME));
if (dialog.open() == FolderSelectionDialog.OK) {
return (IContainer)dialog.getFirstResult();
}
return null;
}
// -------- tab switching ----------
private void tabChanged(Widget widget) {
if (widget instanceof TabItem) {
TabItem tabItem= (TabItem) widget;
BuildPathBasePage newPage= (BuildPathBasePage) tabItem.getData();
if (fCurrPage != null) {
List selection= fCurrPage.getSelection();
if (!selection.isEmpty()) {
newPage.setSelection(selection);
}
}
fCurrPage= newPage;
fPageIndex= tabItem.getParent().getSelectionIndex();
}
}
}
|
28,054 |
Bug 28054 awkward to change default output folder
|
Build I20021210 1. Create a new Java project P1 On the Java Settings page hit the Browse next to Default output folder. Observe: The dialog is empty, shows an error "No entries available", and only allows Cancel. Expectation: As with other dialogs, it would be better if I had an opportunity to create folders at this time. unable to create a linked output folder
|
resolved fixed
|
aa4b231
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-17T16:50:28Z | 2002-12-10T22:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/wizards/JavaCapabilityConfigurationPage.java
|
/*******************************************************************************
* Copyright (c) 2002 International Business Machines Corp. 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.wizards;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener;
import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages;
import org.eclipse.jdt.internal.ui.wizards.buildpaths.BuildPathsBlock;
/**
* Standard wizard page for creating new Java projects. This page can be used in
* project creation wizards. The page shows UI to configure the project with a Java
* build path and output location. On finish the page will also configure the Java nature.
* <p>
* This is a replacement for <code>NewJavaProjectWizardPage</code> with a cleaner API.
* </p>
*
* @since 2.0
*/
public class JavaCapabilityConfigurationPage extends NewElementWizardPage {
private static final String PAGE_NAME= "JavaCapabilityConfigurationPage"; //$NON-NLS-1$
private IJavaProject fJavaProject;
private BuildPathsBlock fBuildPathsBlock;
/**
* Creates a wizard page that can be used in a Java project creation wizard.
* It contains UI to configure a the classpath and the output folder.
*
* <p>
* After constructing, a call to <code>init</code> is required
* </p>
*/
public JavaCapabilityConfigurationPage() {
super(PAGE_NAME);
fJavaProject= null;
setTitle(NewWizardMessages.getString("JavaCapabilityConfigurationPage.title")); //$NON-NLS-1$
setDescription(NewWizardMessages.getString("JavaCapabilityConfigurationPage.description")); //$NON-NLS-1$
IStatusChangeListener listener= new IStatusChangeListener() {
public void statusChanged(IStatus status) {
updateStatus(status);
}
};
fBuildPathsBlock= new BuildPathsBlock(listener, 0);
}
/**
* Initializes the page with the project and default classpaths.
* <p>
* The default classpath entries must correspond the the given project.
* </p>
* <p>
* The caller of this method is responsible for creating the underlying project. The page will create the output,
* source and library folders if required.
* </p>
* <p>
* The project does not have to exist at the time of initialization, but must exist when executing the runnable
* obtained by <code>getRunnable()</code>.
* </p>
* @param project The Java project.
* @param entries The default classpath entries or <code>null</code> to let the page choose the default
* @param path The folder to be taken as the default output path or <code>null</code> to let the page choose the default
* @return overrideExistingClasspath If set to <code>true</code>, an existing '.classpath' file is ignored. If set to <code>false</code>
* the given default classpath and output location is only used if no '.classpath' exists.
*/
public void init(IJavaProject jproject, IPath defaultOutputLocation, IClasspathEntry[] defaultEntries, boolean defaultsOverrideExistingClasspath) {
if (!defaultsOverrideExistingClasspath && jproject.exists() && jproject.getProject().getFile(".classpath").exists()) { //$NON-NLS-1$
defaultOutputLocation= null;
defaultEntries= null;
}
fBuildPathsBlock.init(jproject, defaultOutputLocation, defaultEntries);
fJavaProject= jproject;
}
/* (non-Javadoc)
* @see WizardPage#createControl
*/
public void createControl(Composite parent) {
Control control= fBuildPathsBlock.createControl(parent);
setControl(control);
WorkbenchHelp.setHelp(control, IJavaHelpContextIds.NEW_JAVAPROJECT_WIZARD_PAGE);
}
/**
* Returns the currently configured output location. Note that the returned path
* might not be a valid path.
*
* @return the currently configured output location
*/
public IPath getOutputLocation() {
return fBuildPathsBlock.getOutputLocation();
}
/**
* Returns the currently configured classpath. Note that the classpath might
* not be valid.
*
* @return the currently configured classpath
*/
public IClasspathEntry[] getRawClassPath() {
return fBuildPathsBlock.getRawClassPath();
}
/**
* Returns the Java project that was passed in <code>init</code> or <code>null</code> if the
* page has not been initialized yet.
*
* @return the managed Java project or <code>null</code>
*/
public IJavaProject getJavaProject() {
return fJavaProject;
}
/**
* Returns the runnable that will create the Java project or <code>null</code> if the page has
* not been initialized. The runnable sets the project's classpath and output location to the values
* configured in the page and adds the Java nature if not set yet. The method requires that the
* project is created and opened.
*
* @return the runnable that creates the new Java project
*/
public IRunnableWithProgress getRunnable() {
if (getJavaProject() != null) {
return new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
try {
configureJavaProject(monitor);
} catch (CoreException e) {
throw new InvocationTargetException(e);
}
}
};
}
return null;
}
/**
* Adds the Java nature to the project (if not set yet) and configures the build classpath.
*
* @param monitor a progress monitor to report progress or <code>null</code> if
* progress reporting is not desired
*/
public void configureJavaProject(IProgressMonitor monitor) throws CoreException, InterruptedException {
if (monitor == null) {
monitor= new NullProgressMonitor();
}
int nSteps= 5;
monitor.beginTask(NewWizardMessages.getString("JavaCapabilityConfigurationPage.op_desc"), nSteps); //$NON-NLS-1$
try {
IProject project= getJavaProject().getProject();
BuildPathsBlock.addJavaNature(project, new SubProgressMonitor(monitor, 1));
fBuildPathsBlock.configureJavaProject(new SubProgressMonitor(monitor, 5));
} finally {
monitor.done();
}
}
}
|
28,398 |
Bug 28398 New Java Project Wizard: no source folder after using "Back"
|
Build 20021213 1. Start the new Java Project wizard 2. Enter "JUnix" 3. Press "Next" - see: there's a source folder 4. Press "Back" 5. Change project name to "JUnit" 6. Press "Next" ==> no source folder
|
resolved fixed
|
046e710
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-17T17:03:57Z | 2002-12-16T17:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/SourceContainerWorkbookPage.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.wizards.buildpaths;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.ui.model.WorkbenchContentProvider;
import org.eclipse.ui.model.WorkbenchLabelProvider;
import org.eclipse.ui.views.navigator.ResourceSorter;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
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.util.PixelConverter;
import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages;
import org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator;
import org.eclipse.jdt.internal.ui.wizards.TypedViewerFilter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.ITreeListAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.TreeListDialogField;
public class SourceContainerWorkbookPage extends BuildPathBasePage {
private ListDialogField fClassPathList;
private IJavaProject fCurrJProject;
private IPath fProjPath;
private Control fSWTControl;
private IWorkspaceRoot fWorkspaceRoot;
private TreeListDialogField fFoldersList;
private StringDialogField fOutputLocationField;
private SelectionButtonDialogField fUseFolderOutputs;
private final int IDX_ADD= 0;
private final int IDX_EDIT= 2;
private final int IDX_REMOVE= 3;
public SourceContainerWorkbookPage(IWorkspaceRoot root, ListDialogField classPathList, StringDialogField outputLocationField) {
fWorkspaceRoot= root;
fClassPathList= classPathList;
fOutputLocationField= outputLocationField;
fSWTControl= null;
SourceContainerAdapter adapter= new SourceContainerAdapter();
String[] buttonLabels;
int removeIndex;
buttonLabels= new String[] {
/* 0 = IDX_ADDEXIST */ NewWizardMessages.getString("SourceContainerWorkbookPage.folders.add.button"), //$NON-NLS-1$
/* 1 */ null,
/* 2 = IDX_EDIT */ NewWizardMessages.getString("SourceContainerWorkbookPage.folders.edit.button"), //$NON-NLS-1$
/* 3 = IDX_REMOVE */ NewWizardMessages.getString("SourceContainerWorkbookPage.folders.remove.button") //$NON-NLS-1$
};
removeIndex= IDX_REMOVE;
fFoldersList= new TreeListDialogField(adapter, buttonLabels, new CPListLabelProvider());
fFoldersList.setDialogFieldListener(adapter);
fFoldersList.setLabelText(NewWizardMessages.getString("SourceContainerWorkbookPage.folders.label")); //$NON-NLS-1$
fFoldersList.setRemoveButtonIndex(removeIndex);
fFoldersList.setViewerSorter(new CPListElementSorter());
fFoldersList.enableButton(IDX_EDIT, false);
fUseFolderOutputs= new SelectionButtonDialogField(SWT.CHECK);
fUseFolderOutputs.setSelection(false);
fUseFolderOutputs.setLabelText(NewWizardMessages.getString("SourceContainerWorkbookPage.folders.check"));
fUseFolderOutputs.setDialogFieldListener(adapter);
}
public void init(IJavaProject jproject) {
fCurrJProject= jproject;
fProjPath= fCurrJProject.getProject().getFullPath();
updateFoldersList();
}
private void updateFoldersList() {
fFoldersList.removeAllElements();
boolean useFolderOutputs= false;
List cpelements= fClassPathList.getElements();
for (int i= 0; i < cpelements.size(); i++) {
CPListElement cpe= (CPListElement)cpelements.get(i);
if (cpe.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
fFoldersList.addElement(cpe);
boolean hasOutputFolder= (cpe.getAttribute(CPListElement.OUTPUT) != null);
if (hasOutputFolder) {
useFolderOutputs= true;
}
IPath[] patterns= (IPath[]) cpe.getAttribute(CPListElement.EXCLUSION);
if (patterns.length > 0 || hasOutputFolder) {
fFoldersList.expandElement(cpe, 3);
}
}
}
fUseFolderOutputs.setSelection(useFolderOutputs);
}
public Control getControl(Composite parent) {
PixelConverter converter= new PixelConverter(parent);
Composite composite= new Composite(parent, SWT.NONE);
LayoutUtil.doDefaultLayout(composite, new DialogField[] { fFoldersList, fUseFolderOutputs }, true);
LayoutUtil.setHorizontalGrabbing(fFoldersList.getTreeControl(null));
int buttonBarWidth= converter.convertWidthInCharsToPixels(24);
fFoldersList.setButtonsMinWidth(buttonBarWidth);
fSWTControl= composite;
// expand
List elements= fFoldersList.getElements();
for (int i= 0; i < elements.size(); i++) {
CPListElement elem= (CPListElement) elements.get(i);
IPath[] patterns= (IPath[]) elem.getAttribute(CPListElement.EXCLUSION);
IPath output= (IPath) elem.getAttribute(CPListElement.OUTPUT);
if (patterns.length > 0 || output != null) {
fFoldersList.expandElement(elem, 3);
}
}
return composite;
}
private Shell getShell() {
if (fSWTControl != null) {
return fSWTControl.getShell();
}
return JavaPlugin.getActiveWorkbenchShell();
}
private class SourceContainerAdapter implements ITreeListAdapter, IDialogFieldListener {
private final Object[] EMPTY_ARR= new Object[0];
// -------- IListAdapter --------
public void customButtonPressed(TreeListDialogField field, int index) {
sourcePageCustomButtonPressed(field, index);
}
public void selectionChanged(TreeListDialogField field) {
sourcePageSelectionChanged(field);
}
public void doubleClicked(TreeListDialogField field) {
sourcePageDoubleClicked(field);
}
public Object[] getChildren(TreeListDialogField field, Object element) {
if (element instanceof CPListElement) {
return ((CPListElement) element).getChildren(!fUseFolderOutputs.isSelected());
}
return EMPTY_ARR;
}
public Object getParent(TreeListDialogField field, Object element) {
if (element instanceof CPListElementAttribute) {
return ((CPListElementAttribute) element).getParent();
}
return null;
}
public boolean hasChildren(TreeListDialogField field, Object element) {
return (element instanceof CPListElement);
}
// ---------- IDialogFieldListener --------
public void dialogFieldChanged(DialogField field) {
sourcePageDialogFieldChanged(field);
}
}
protected void sourcePageDoubleClicked(TreeListDialogField field) {
if (field == fFoldersList) {
List selection= fFoldersList.getSelectedElements();
if (canEdit(selection)) {
editEntry();
}
}
}
protected void sourcePageCustomButtonPressed(DialogField field, int index) {
if (field == fFoldersList) {
if (index == IDX_ADD) {
List elementsToAdd= new ArrayList(10);
if (fCurrJProject.exists()) {
CPListElement[] srcentries= openSourceContainerDialog(null);
if (srcentries != null) {
for (int i= 0; i < srcentries.length; i++) {
elementsToAdd.add(srcentries[i]);
}
}
} else {
CPListElement entry= openNewSourceContainerDialog(null);
if (entry != null) {
elementsToAdd.add(entry);
}
}
if (!elementsToAdd.isEmpty()) {
if (fFoldersList.getSize() == 1) {
CPListElement existing= (CPListElement) fFoldersList.getElement(0);
if (existing.getResource() instanceof IProject) {
askForChangingBuildPathDialog(existing);
}
}
HashSet modifiedElements= new HashSet();
askForAddingExclusionPatternsDialog(elementsToAdd, modifiedElements);
fFoldersList.addElements(elementsToAdd);
fFoldersList.postSetSelection(new StructuredSelection(elementsToAdd));
if (!modifiedElements.isEmpty()) {
for (Iterator iter= modifiedElements.iterator(); iter.hasNext();) {
Object elem= iter.next();
fFoldersList.refresh(elem);
fFoldersList.expandElement(elem, 3);
}
}
}
} else if (index == IDX_EDIT) {
editEntry();
}
}
}
private void editEntry() {
List selElements= fFoldersList.getSelectedElements();
if (selElements.size() != 1) {
return;
}
Object elem= selElements.get(0);
if (fFoldersList.getIndexOfElement(elem) != -1) {
editElementEntry((CPListElement) elem);
} else if (elem instanceof CPListElementAttribute) {
editAttributeEntry((CPListElementAttribute) elem);
}
}
private void editElementEntry(CPListElement elem) {
CPListElement res= null;
IResource resource= elem.getResource();
if (resource.exists()) {
CPListElement[] arr= openSourceContainerDialog(elem);
if (arr != null) {
res= arr[0];
}
} else {
res= openNewSourceContainerDialog(elem);
}
if (res != null) {
fFoldersList.replaceElement(elem, res);
}
}
private void editAttributeEntry(CPListElementAttribute elem) {
String key= elem.getKey();
if (key.equals(CPListElement.OUTPUT)) {
CPListElement selElement= (CPListElement) elem.getParent();
OutputLocationDialog dialog= new OutputLocationDialog(getShell(), selElement);
if (dialog.open() == OutputLocationDialog.OK) {
selElement.setAttribute(CPListElement.OUTPUT, dialog.getOutputLocation());
fFoldersList.refresh();
fClassPathList.dialogFieldChanged(); // validate
}
} else if (key.equals(CPListElement.EXCLUSION)) {
CPListElement selElement= (CPListElement) elem.getParent();
ExclusionPatternDialog dialog= new ExclusionPatternDialog(getShell(), selElement);
if (dialog.open() == OutputLocationDialog.OK) {
selElement.setAttribute(CPListElement.EXCLUSION, dialog.getExclusionPattern());
fFoldersList.refresh();
fClassPathList.dialogFieldChanged(); // validate
}
}
}
protected void sourcePageSelectionChanged(DialogField field) {
List selected= fFoldersList.getSelectedElements();
fFoldersList.enableButton(IDX_EDIT, canEdit(selected));
}
private boolean canEdit(List selElements) {
if (selElements.size() != 1) {
return false;
}
Object elem= selElements.get(0);
if (fFoldersList.getIndexOfElement(elem) != -1) {
return true;
}
if (elem instanceof CPListElementAttribute) {
return true;
}
return false;
}
private void sourcePageDialogFieldChanged(DialogField field) {
if (fCurrJProject == null) {
// not initialized
return;
}
if (field == fUseFolderOutputs) {
if (!fUseFolderOutputs.isSelected()) {
int nFolders= fFoldersList.getSize();
for (int i= 0; i < nFolders; i++) {
CPListElement cpe= (CPListElement) fFoldersList.getElement(i);
cpe.setAttribute(CPListElement.OUTPUT, null);
}
}
fFoldersList.refresh();
} else if (field == fFoldersList) {
updateClasspathList();
}
}
private void updateClasspathList() {
List cpelements= fClassPathList.getElements();
List srcelements= fFoldersList.getElements();
boolean changeDone= false;
CPListElement lastSourceFolder= null;
// backwards, as entries will be deleted
for (int i= cpelements.size() - 1; i >= 0 ; i--) {
CPListElement cpe= (CPListElement)cpelements.get(i);
if (isEntryKind(cpe.getEntryKind())) {
// if it is a source folder, but not one of the accepted entries, remove it
// at the same time, for the entries seen, remove them from the accepted list
if (!srcelements.remove(cpe)) {
cpelements.remove(i);
changeDone= true;
} else if (lastSourceFolder == null) {
lastSourceFolder= cpe;
}
}
}
if (!srcelements.isEmpty()) {
int insertIndex= (lastSourceFolder == null) ? 0 : cpelements.indexOf(lastSourceFolder) + 1;
cpelements.addAll(insertIndex, srcelements);
changeDone= true;
}
if (changeDone) {
fClassPathList.setElements(cpelements);
}
}
private CPListElement openNewSourceContainerDialog(CPListElement existing) {
String title= (existing == null) ? NewWizardMessages.getString("SourceContainerWorkbookPage.NewSourceFolderDialog.new.title") : NewWizardMessages.getString("SourceContainerWorkbookPage.NewSourceFolderDialog.edit.title"); //$NON-NLS-1$ //$NON-NLS-2$
IProject proj= fCurrJProject.getProject();
NewSourceFolderDialog dialog= new NewSourceFolderDialog(getShell(), title, proj, getExistingContainers(existing), existing);
dialog.setMessage(NewWizardMessages.getFormattedString("SourceContainerWorkbookPage.NewSourceFolderDialog.description", fProjPath.toString())); //$NON-NLS-1$
if (dialog.open() == NewContainerDialog.OK) {
IResource folder= dialog.getSourceFolder();
return newCPSourceElement(folder);
}
return null;
}
/**
* Asks to change the output folder to 'proj/bin' when no source folders were existing
*/
private void askForChangingBuildPathDialog(CPListElement existing) {
IPath outputFolder= new Path(fOutputLocationField.getText());
IPath newOutputFolder= null;
String message;
if (outputFolder.segmentCount() == 1) {
String outputFolderName= PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.SRCBIN_BINNAME);
newOutputFolder= outputFolder.append(outputFolderName);
message= NewWizardMessages.getFormattedString("SourceContainerWorkbookPage.ChangeOutputLocationDialog.project_and_output.message", newOutputFolder); //$NON-NLS-1$
} else {
message= NewWizardMessages.getString("SourceContainerWorkbookPage.ChangeOutputLocationDialog.project.message"); //$NON-NLS-1$
}
String title= NewWizardMessages.getString("SourceContainerWorkbookPage.ChangeOutputLocationDialog.title"); //$NON-NLS-1$
if (MessageDialog.openQuestion(getShell(), title, message)) {
fFoldersList.removeElement(existing);
if (newOutputFolder != null) {
fOutputLocationField.setText(newOutputFolder.toString());
}
}
}
private void askForAddingExclusionPatternsDialog(List newEntries, Set modifiedEntries) {
for (int i= 0; i < newEntries.size(); i++) {
CPListElement curr= (CPListElement) newEntries.get(i);
addExclusionPatterns(curr, modifiedEntries);
}
if (!modifiedEntries.isEmpty()) {
String title= NewWizardMessages.getString("SourceContainerWorkbookPage.exclusion_added.title"); //$NON-NLS-1$
String message= NewWizardMessages.getString("SourceContainerWorkbookPage.exclusion_added.message"); //$NON-NLS-1$
MessageDialog.openInformation(getShell(), title, message);
}
}
private void addExclusionPatterns(CPListElement newEntry, Set modifiedEntries) {
IPath entryPath= newEntry.getPath();
List existing= fFoldersList.getElements();
for (int i= 0; i < existing.size(); i++) {
CPListElement curr= (CPListElement) existing.get(i);
IPath currPath= curr.getPath();
if (currPath.isPrefixOf(entryPath)) {
IPath[] exclusionFilters= (IPath[]) curr.getAttribute(CPListElement.EXCLUSION);
if (!JavaModelUtil.isExcludedPath(entryPath, exclusionFilters)) {
IPath pathToExclude= entryPath.removeFirstSegments(currPath.segmentCount()).addTrailingSeparator();
IPath[] newExclusionFilters= new IPath[exclusionFilters.length + 1];
System.arraycopy(exclusionFilters, 0, newExclusionFilters, 0, exclusionFilters.length);
newExclusionFilters[exclusionFilters.length]= pathToExclude;
curr.setAttribute(CPListElement.EXCLUSION, newExclusionFilters);
modifiedEntries.add(curr);
}
}
}
}
private CPListElement[] openSourceContainerDialog(CPListElement existing) {
Class[] acceptedClasses= new Class[] { IProject.class, IFolder.class };
TypedElementSelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, existing == null, getExistingContainers(null));
IProject[] allProjects= fWorkspaceRoot.getProjects();
ArrayList rejectedElements= new ArrayList(allProjects.length);
IProject currProject= fCurrJProject.getProject();
for (int i= 0; i < allProjects.length; i++) {
if (!allProjects[i].equals(currProject)) {
rejectedElements.add(allProjects[i]);
}
}
ViewerFilter filter= new TypedViewerFilter(acceptedClasses, rejectedElements.toArray());
ILabelProvider lp= new WorkbenchLabelProvider();
ITreeContentProvider cp= new WorkbenchContentProvider();
String title= (existing == null) ? NewWizardMessages.getString("SourceContainerWorkbookPage.ExistingSourceFolderDialog.new.title") : NewWizardMessages.getString("SourceContainerWorkbookPage.ExistingSourceFolderDialog.edit.title"); //$NON-NLS-1$ //$NON-NLS-2$
String message= (existing == null) ? NewWizardMessages.getString("SourceContainerWorkbookPage.ExistingSourceFolderDialog.new.description") : NewWizardMessages.getString("SourceContainerWorkbookPage.ExistingSourceFolderDialog.edit.description"); //$NON-NLS-1$ //$NON-NLS-2$
FolderSelectionDialog dialog= new FolderSelectionDialog(getShell(), lp, cp);
dialog.setValidator(validator);
dialog.setTitle(title);
dialog.setMessage(message);
dialog.addFilter(filter);
dialog.setInput(fCurrJProject.getProject().getParent());
dialog.setSorter(new ResourceSorter(ResourceSorter.NAME));
if (existing == null) {
dialog.setInitialSelection(fCurrJProject.getProject());
} else {
dialog.setInitialSelection(existing.getResource());
}
if (dialog.open() == FolderSelectionDialog.OK) {
Object[] elements= dialog.getResult();
CPListElement[] res= new CPListElement[elements.length];
for (int i= 0; i < res.length; i++) {
IResource elem= (IResource)elements[i];
res[i]= newCPSourceElement(elem);
}
return res;
}
return null;
}
private List getExistingContainers(CPListElement existing) {
List res= new ArrayList();
List cplist= fFoldersList.getElements();
for (int i= 0; i < cplist.size(); i++) {
CPListElement elem= (CPListElement)cplist.get(i);
if (elem != existing) {
IResource resource= elem.getResource();
if (resource instanceof IContainer) { // defensive code
res.add(resource);
}
}
}
return res;
}
private CPListElement newCPSourceElement(IResource res) {
Assert.isNotNull(res);
return new CPListElement(fCurrJProject, IClasspathEntry.CPE_SOURCE, res.getFullPath(), res);
}
/*
* @see BuildPathBasePage#getSelection
*/
public List getSelection() {
return fFoldersList.getSelectedElements();
}
/*
* @see BuildPathBasePage#setSelection
*/
public void setSelection(List selElements) {
fFoldersList.selectElements(new StructuredSelection(selElements));
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.wizards.buildpaths.BuildPathBasePage#isEntryKind(int)
*/
public boolean isEntryKind(int kind) {
return kind == IClasspathEntry.CPE_SOURCE;
}
}
|
25,068 |
Bug 25068 Reuse editor in Search view causes the menubar to refresh a lot.
| null |
resolved fixed
|
b37b167
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-18T13:54:06Z | 2002-10-18T16:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/GotoMarkerAction.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.search;
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.widgets.Shell;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.search.ui.ISearchResultView;
import org.eclipse.search.ui.ISearchResultViewEntry;
import org.eclipse.search.ui.SearchUI;
import org.eclipse.search.internal.ui.SearchPlugin;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.ui.IPackagesViewPart;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.javaeditor.InternalClassFileEditorInput;
import org.eclipse.jdt.internal.ui.util.SelectionUtil;
public class GotoMarkerAction extends Action {
private IEditorPart fEditor;
public GotoMarkerAction(){
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.GOTO_MARKER_ACTION);
}
public void run() {
ISearchResultView view= SearchUI.getSearchResultView();
Object element= SelectionUtil.getSingleElement(view.getSelection());
if (element instanceof ISearchResultViewEntry) {
ISearchResultViewEntry entry= (ISearchResultViewEntry)element;
show(entry.getSelectedMarker());
}
}
private void show(IMarker marker) {
IResource resource= marker.getResource();
if (resource == null || !resource.exists())
return;
IWorkbenchPage wbPage= JavaPlugin.getActivePage();
IJavaElement javaElement= SearchUtil.getJavaElement(marker);
if (javaElement != null && javaElement.getElementType() == IJavaElement.PACKAGE_FRAGMENT)
gotoPackagesView(javaElement, wbPage);
else {
if (SearchUI.reuseEditor())
showWithReuse(marker, resource, javaElement, wbPage);
else
showWithoutReuse(marker, javaElement, wbPage);
}
}
private void showWithoutReuse(IMarker marker, IJavaElement javaElement, IWorkbenchPage wbPage) {
IEditorPart editor= null;
try {
Object objectToOpen= javaElement;
if (objectToOpen == null)
objectToOpen= marker.getResource();
editor= EditorUtility.openInEditor(objectToOpen, false);
} catch (CoreException ex) {
MessageDialog.openError(SearchPlugin.getActiveWorkbenchShell(), SearchMessages.getString("Search.Error.openEditor.title"), SearchMessages.getString("Search.Error.openEditor.message")); //$NON-NLS-2$ //$NON-NLS-1$
}
if (editor != null)
editor.gotoMarker(marker);
}
private void showWithReuse(IMarker marker, IResource resource, IJavaElement javaElement, IWorkbenchPage wbPage) {
if (javaElement == null || !isBinary(javaElement)) {
if (resource instanceof IFile)
showInEditor(marker, wbPage, new FileEditorInput((IFile)resource), JavaUI.ID_CU_EDITOR);
}
else {
IClassFile cf= getClassFile(javaElement);
if (cf != null)
showInEditor(marker, wbPage, new InternalClassFileEditorInput(cf), JavaUI.ID_CF_EDITOR);
}
}
private boolean isPinned(IEditorPart editor) {
if (editor == null)
return false;
IEditorReference[] editorRefs= editor.getEditorSite().getPage().getEditorReferences();
int i= 0;
while (i < editorRefs.length) {
if (editor.equals(editorRefs[i].getEditor(false)))
return editorRefs[i].isPinned();
i++;
}
return false;
}
private void showInEditor(IMarker marker, IWorkbenchPage page, IEditorInput input, String editorId) {
IEditorPart editor= page.findEditor(input);
if (editor == null) {
if (fEditor != null && !fEditor.isDirty() && !isPinned(fEditor))
page.closeEditor(fEditor, false);
try {
editor= page.openEditor(input, editorId, false);
} catch (PartInitException ex) {
MessageDialog.openError(SearchPlugin.getActiveWorkbenchShell(), SearchMessages.getString("Search.Error.openEditor.title"), SearchMessages.getString("Search.Error.openEditor.message")); //$NON-NLS-2$ //$NON-NLS-1$
return;
}
} else {
page.bringToTop(editor);
}
if (editor != null) {
editor.gotoMarker(marker);
fEditor = editor;
}
}
private void gotoPackagesView(IJavaElement javaElement, IWorkbenchPage wbPage) {
try {
IViewPart view= wbPage.showView(JavaUI.ID_PACKAGES);
if (view instanceof IPackagesViewPart)
((IPackagesViewPart)view).selectAndReveal(javaElement);
} catch (PartInitException ex) {
MessageDialog.openError(SearchPlugin.getActiveWorkbenchShell(), SearchMessages.getString("Search.Error.openEditor.title"), SearchMessages.getString("Search.Error.openEditor.message")); //$NON-NLS-2$ //$NON-NLS-1$
}
}
private IClassFile getClassFile(IJavaElement jElement) {
if (jElement instanceof IMember)
return ((IMember)jElement).getClassFile();
return null;
}
private boolean isBinary(IJavaElement jElement) {
if (jElement instanceof IMember)
return ((IMember)jElement).isBinary();
return false;
}
private void beep() {
Shell shell= JavaPlugin.getActiveWorkbenchShell();
if (shell != null && shell.getDisplay() != null)
shell.getDisplay().beep();
}
}
|
29,726 |
Bug 29726 New compiler setting added: OPTION_ReportIncompatibleNonInheritedInterfaceMethod
|
JavaCore#OPTION_ReportIncompatibleNonInheritedInterfaceMethod COMPILER / Reporting Interface Method not Compatible with non-Inherited Methods When enabled, the compiler will issue an error or a warning whenever an interface defines a method incompatible with a non-inherited Object one. - option id: "org.eclipse.jdt.core.compiler.incompatibleNonInheritedInterfaceMeth od" - possible values: { "error", "warning", "ignore" } - default: "warning" --- FYI - we used to always be reporting an error, where we should not. Now we default to a warning - not critical for 2.1M5, default is likely the best anyway. test case: interface I { int clone(); // should only be a warning }
|
resolved fixed
|
1b01b65
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-20T09:39:58Z | 2003-01-17T16:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/CompilerConfigurationBlock.java
|
package org.eclipse.jdt.internal.ui.preferences;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.Map;
import java.util.StringTokenizer;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
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.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.util.PixelConverter;
import org.eclipse.jdt.internal.ui.util.TabFolderLayout;
import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener;
/**
*/
public class CompilerConfigurationBlock {
// Preference store keys, see JavaCore.getOptions
private static final String PREF_LOCAL_VARIABLE_ATTR= JavaCore.COMPILER_LOCAL_VARIABLE_ATTR;
private static final String PREF_LINE_NUMBER_ATTR= JavaCore.COMPILER_LINE_NUMBER_ATTR;
private static final String PREF_SOURCE_FILE_ATTR= JavaCore.COMPILER_SOURCE_FILE_ATTR;
private static final String PREF_CODEGEN_UNUSED_LOCAL= JavaCore.COMPILER_CODEGEN_UNUSED_LOCAL;
private static final String PREF_CODEGEN_TARGET_PLATFORM= JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM;
private static final String PREF_PB_UNREACHABLE_CODE= JavaCore.COMPILER_PB_UNREACHABLE_CODE;
private static final String PREF_PB_INVALID_IMPORT= JavaCore.COMPILER_PB_INVALID_IMPORT;
private static final String PREF_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD= JavaCore.COMPILER_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD;
private static final String PREF_PB_METHOD_WITH_CONSTRUCTOR_NAME= JavaCore.COMPILER_PB_METHOD_WITH_CONSTRUCTOR_NAME;
private static final String PREF_PB_DEPRECATION= JavaCore.COMPILER_PB_DEPRECATION;
private static final String PREF_PB_HIDDEN_CATCH_BLOCK= JavaCore.COMPILER_PB_HIDDEN_CATCH_BLOCK;
private static final String PREF_PB_UNUSED_LOCAL= JavaCore.COMPILER_PB_UNUSED_LOCAL;
private static final String PREF_PB_UNUSED_PARAMETER= JavaCore.COMPILER_PB_UNUSED_PARAMETER;
private static final String PREF_PB_SYNTHETIC_ACCESS_EMULATION= JavaCore.COMPILER_PB_SYNTHETIC_ACCESS_EMULATION;
private static final String PREF_PB_NON_EXTERNALIZED_STRINGS= JavaCore.COMPILER_PB_NON_NLS_STRING_LITERAL;
private static final String PREF_PB_ASSERT_AS_IDENTIFIER= JavaCore.COMPILER_PB_ASSERT_IDENTIFIER;
private static final String PREF_PB_MAX_PER_UNIT= JavaCore.COMPILER_PB_MAX_PER_UNIT;
private static final String PREF_PB_UNUSED_IMPORT= JavaCore.COMPILER_PB_UNUSED_IMPORT;
private static final String PREF_PB_STATIC_ACCESS_RECEIVER= JavaCore.COMPILER_PB_STATIC_ACCESS_RECEIVER;
private static final String PREF_PB_NO_EFFECT_ASSIGNMENT= JavaCore.COMPILER_PB_NO_EFFECT_ASSIGNMENT;
private static final String PREF_SOURCE_COMPATIBILITY= JavaCore.COMPILER_SOURCE;
private static final String PREF_COMPLIANCE= JavaCore.COMPILER_COMPLIANCE;
private static final String PREF_RESOURCE_FILTER= JavaCore.CORE_JAVA_BUILD_RESOURCE_COPY_FILTER;
private static final String PREF_BUILD_INVALID_CLASSPATH= JavaCore.CORE_JAVA_BUILD_INVALID_CLASSPATH;
private static final String PREF_BUILD_CLEAN_OUTPUT_FOLDER= JavaCore.CORE_JAVA_BUILD_CLEAN_OUTPUT_FOLDER;
private static final String PREF_PB_INCOMPLETE_BUILDPATH= JavaCore.CORE_INCOMPLETE_CLASSPATH;
private static final String PREF_PB_CIRCULAR_BUILDPATH= JavaCore.CORE_CIRCULAR_CLASSPATH;
private static final String PREF_COMPILER_PB_DEPRECATION_IN_DEPRECATED_CODE= JavaCore.COMPILER_PB_DEPRECATION_IN_DEPRECATED_CODE;
private static final String PREF_PB_DUPLICATE_RESOURCE= JavaCore.CORE_JAVA_BUILD_DUPLICATE_RESOURCE;
private static final String INTR_DEFAULT_COMPLIANCE= "internal.default.compliance"; //$NON-NLS-1$
// values
private static final String GENERATE= JavaCore.GENERATE;
private static final String DO_NOT_GENERATE= JavaCore.DO_NOT_GENERATE;
private static final String PRESERVE= JavaCore.PRESERVE;
private static final String OPTIMIZE_OUT= JavaCore.OPTIMIZE_OUT;
private static final String VERSION_1_1= JavaCore.VERSION_1_1;
private static final String VERSION_1_2= JavaCore.VERSION_1_2;
private static final String VERSION_1_3= JavaCore.VERSION_1_3;
private static final String VERSION_1_4= JavaCore.VERSION_1_4;
private static final String ERROR= JavaCore.ERROR;
private static final String WARNING= JavaCore.WARNING;
private static final String IGNORE= JavaCore.IGNORE;
private static final String ABORT= JavaCore.ABORT;
private static final String CLEAN= JavaCore.CLEAN;
private static final String ENABLED= JavaCore.ENABLED;
private static final String DISABLED= JavaCore.DISABLED;
private static final String PRIORITY_HIGH= JavaCore.COMPILER_TASK_PRIORITY_HIGH;
private static final String PRIORITY_NORMAL= JavaCore.COMPILER_TASK_PRIORITY_NORMAL;
private static final String PRIORITY_LOW= JavaCore.COMPILER_TASK_PRIORITY_LOW;
private static final String DEFAULT= "default"; //$NON-NLS-1$
private static final String USER= "user"; //$NON-NLS-1$
private static String[] getAllKeys() {
return new String[] {
PREF_LOCAL_VARIABLE_ATTR, PREF_LINE_NUMBER_ATTR, PREF_SOURCE_FILE_ATTR, PREF_CODEGEN_UNUSED_LOCAL,
PREF_CODEGEN_TARGET_PLATFORM, PREF_PB_UNREACHABLE_CODE, PREF_PB_INVALID_IMPORT, PREF_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD,
PREF_PB_METHOD_WITH_CONSTRUCTOR_NAME, PREF_PB_DEPRECATION, PREF_PB_HIDDEN_CATCH_BLOCK, PREF_PB_UNUSED_LOCAL,
PREF_PB_UNUSED_PARAMETER, PREF_PB_SYNTHETIC_ACCESS_EMULATION, PREF_PB_NON_EXTERNALIZED_STRINGS,
PREF_PB_ASSERT_AS_IDENTIFIER, PREF_PB_UNUSED_IMPORT, PREF_PB_MAX_PER_UNIT, PREF_SOURCE_COMPATIBILITY, PREF_COMPLIANCE,
PREF_RESOURCE_FILTER, PREF_BUILD_INVALID_CLASSPATH, PREF_PB_STATIC_ACCESS_RECEIVER, PREF_PB_INCOMPLETE_BUILDPATH,
PREF_PB_CIRCULAR_BUILDPATH, PREF_COMPILER_PB_DEPRECATION_IN_DEPRECATED_CODE, PREF_BUILD_CLEAN_OUTPUT_FOLDER,
PREF_PB_DUPLICATE_RESOURCE, PREF_PB_NO_EFFECT_ASSIGNMENT
};
}
private static class ControlData {
private String fKey;
private String[] fValues;
public ControlData(String key, String[] values) {
fKey= key;
fValues= values;
}
public String getKey() {
return fKey;
}
public String getValue(boolean selection) {
int index= selection ? 0 : 1;
return fValues[index];
}
public String getValue(int index) {
return fValues[index];
}
public int getSelection(String value) {
for (int i= 0; i < fValues.length; i++) {
if (value.equals(fValues[i])) {
return i;
}
}
throw new IllegalArgumentException();
}
}
private Map fWorkingValues;
private ArrayList fCheckBoxes;
private ArrayList fComboBoxes;
private ArrayList fTextBoxes;
private SelectionListener fSelectionListener;
private ModifyListener fTextModifyListener;
private ArrayList fComplianceControls;
private PixelConverter fPixelConverter;
private IStatus fComplianceStatus, fMaxNumberProblemsStatus, fResourceFilterStatus;
private IStatusChangeListener fContext;
private Shell fShell;
private IJavaProject fProject; // project or null
public CompilerConfigurationBlock(IStatusChangeListener context, IJavaProject project) {
fContext= context;
fProject= project;
fWorkingValues= getOptions(true);
fWorkingValues.put(INTR_DEFAULT_COMPLIANCE, getCurrentCompliance());
fCheckBoxes= new ArrayList();
fComboBoxes= new ArrayList();
fTextBoxes= new ArrayList(2);
fComplianceControls= new ArrayList();
fSelectionListener= new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {}
public void widgetSelected(SelectionEvent e) {
controlChanged(e.widget);
}
};
fTextModifyListener= new ModifyListener() {
public void modifyText(ModifyEvent e) {
textChanged((Text) e.widget);
}
};
fComplianceStatus= new StatusInfo();
fMaxNumberProblemsStatus= new StatusInfo();
fResourceFilterStatus= new StatusInfo();
}
private Map getOptions(boolean inheritJavaCoreOptions) {
if (fProject != null) {
return fProject.getOptions(inheritJavaCoreOptions);
} else {
return JavaCore.getOptions();
}
}
public boolean hasProjectSpecificOptions() {
if (fProject != null) {
Map settings= fProject.getOptions(false);
String[] allKeys= getAllKeys();
for (int i= 0; i < allKeys.length; i++) {
if (settings.get(allKeys[i]) != null) {
return true;
}
}
}
return false;
}
private void setOptions(Map map) {
if (fProject != null) {
fProject.setOptions(map);
} else {
JavaCore.setOptions((Hashtable) map);
}
}
/**
* Returns the shell.
* @return Shell
*/
public Shell getShell() {
return fShell;
}
/**
* @see PreferencePage#createContents(Composite)
*/
protected Control createContents(Composite parent) {
fPixelConverter= new PixelConverter(parent);
fShell= parent.getShell();
TabFolder folder= new TabFolder(parent, SWT.NONE);
folder.setLayout(new TabFolderLayout());
folder.setLayoutData(new GridData(GridData.FILL_BOTH));
Composite warningsComposite= createWarningsTabContent(folder);
Composite markersComposite= createMarkersTabContent(folder);
Composite codeGenComposite= createCodeGenTabContent(folder);
Composite complianceComposite= createComplianceTabContent(folder);
Composite othersComposite= createOthersTabContent(folder);
TabItem item= new TabItem(folder, SWT.NONE);
item.setText(PreferencesMessages.getString("CompilerConfigurationBlock.warnings.tabtitle")); //$NON-NLS-1$
item.setControl(warningsComposite);
item= new TabItem(folder, SWT.NONE);
item.setText(PreferencesMessages.getString("CompilerConfigurationBlock.markers.tabtitle")); //$NON-NLS-1$
item.setControl(markersComposite);
item= new TabItem(folder, SWT.NONE);
item.setText(PreferencesMessages.getString("CompilerConfigurationBlock.generation.tabtitle")); //$NON-NLS-1$
item.setControl(codeGenComposite);
item= new TabItem(folder, SWT.NONE);
item.setText(PreferencesMessages.getString("CompilerConfigurationBlock.compliance.tabtitle")); //$NON-NLS-1$
item.setControl(complianceComposite);
item= new TabItem(folder, SWT.NONE);
item.setText(PreferencesMessages.getString("CompilerConfigurationBlock.others.tabtitle")); //$NON-NLS-1$
item.setControl(othersComposite);
validateSettings(null, null);
return folder;
}
private Composite createMarkersTabContent(TabFolder folder) {
String[] errorWarningIgnore= new String[] { ERROR, WARNING, IGNORE };
String[] errorWarningIgnoreLabels= new String[] {
PreferencesMessages.getString("CompilerConfigurationBlock.error"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.warning"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.ignore") //$NON-NLS-1$
};
String[] enabledDisabled= new String[] { ENABLED, DISABLED };
Composite markersComposite= new Composite(folder, SWT.NULL);
markersComposite.setLayout(new GridLayout());
GridLayout layout= new GridLayout();
layout.numColumns= 2;
Group group= new Group(markersComposite, SWT.NONE);
group.setText(PreferencesMessages.getString("CompilerConfigurationBlock.markers.deprecated.label"));
group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
group.setLayout(layout);
String label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_deprecation.label"); //$NON-NLS-1$
addComboBox(group, label, PREF_PB_DEPRECATION, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_deprecation_in_deprecation.label"); //$NON-NLS-1$
addCheckBox(group, label, PREF_COMPILER_PB_DEPRECATION_IN_DEPRECATED_CODE, enabledDisabled, 0);
layout= new GridLayout();
layout.numColumns= 2;
group= new Group(markersComposite, SWT.NONE);
group.setText(PreferencesMessages.getString("CompilerConfigurationBlock.markers.nls.label"));
group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
group.setLayout(layout);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_non_externalized_strings.label"); //$NON-NLS-1$
addComboBox(group, label, PREF_PB_NON_EXTERNALIZED_STRINGS, errorWarningIgnore, errorWarningIgnoreLabels, 0);
return markersComposite;
}
private Composite createOthersTabContent(TabFolder folder) {
String[] abortIgnoreValues= new String[] { ABORT, IGNORE };
String[] cleanIgnoreValues= new String[] { CLEAN, IGNORE };
String[] errorWarning= new String[] { ERROR, WARNING };
String[] errorWarningLabels= new String[] {
PreferencesMessages.getString("CompilerConfigurationBlock.error"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.warning") //$NON-NLS-1$
};
GridLayout layout= new GridLayout();
layout.numColumns= 2;
Composite othersComposite= new Composite(folder, SWT.NULL);
othersComposite.setLayout(layout);
Label description= new Label(othersComposite, SWT.WRAP);
description.setText(PreferencesMessages.getString("CompilerConfigurationBlock.build_warnings.description")); //$NON-NLS-1$
GridData gd= new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL);
gd.horizontalSpan= 2;
// gd.widthHint= convertWidthInCharsToPixels(50);
description.setLayoutData(gd);
Composite combos= new Composite(othersComposite, SWT.NULL);
gd= new GridData(GridData.FILL | GridData.GRAB_HORIZONTAL);
gd.horizontalSpan= 2;
combos.setLayoutData(gd);
GridLayout cl= new GridLayout();
cl.numColumns=2; cl.marginWidth= 0; cl.marginHeight= 0;
combos.setLayout(cl);
String label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_incomplete_build_path.label"); //$NON-NLS-1$
addComboBox(combos, label, PREF_PB_INCOMPLETE_BUILDPATH, errorWarning, errorWarningLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_build_path_cycles.label"); //$NON-NLS-1$
addComboBox(combos, label, PREF_PB_CIRCULAR_BUILDPATH, errorWarning, errorWarningLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_duplicate_resources.label"); //$NON-NLS-1$
addComboBox(combos, label, PREF_PB_DUPLICATE_RESOURCE, errorWarning, errorWarningLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.build_invalid_classpath.label"); //$NON-NLS-1$
addCheckBox(othersComposite, label, PREF_BUILD_INVALID_CLASSPATH, abortIgnoreValues, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.build_clean_outputfolder.label"); //$NON-NLS-1$
addCheckBox(othersComposite, label, PREF_BUILD_CLEAN_OUTPUT_FOLDER, cleanIgnoreValues, 0);
description= new Label(othersComposite, SWT.WRAP);
description.setText(PreferencesMessages.getString("CompilerConfigurationBlock.resource_filter.description")); //$NON-NLS-1$
gd= new GridData(GridData.FILL);
gd.horizontalSpan= 2;
gd.widthHint= fPixelConverter.convertWidthInCharsToPixels(60);
description.setLayoutData(gd);
label= PreferencesMessages.getString("CompilerConfigurationBlock.resource_filter.label"); //$NON-NLS-1$
Text text= addTextField(othersComposite, label, PREF_RESOURCE_FILTER);
gd= (GridData) text.getLayoutData();
gd.grabExcessHorizontalSpace= true;
gd.widthHint= fPixelConverter.convertWidthInCharsToPixels(10);
return othersComposite;
}
private Composite createWarningsTabContent(Composite folder) {
String[] errorWarningIgnore= new String[] { ERROR, WARNING, IGNORE };
String[] errorWarningIgnoreLabels= new String[] {
PreferencesMessages.getString("CompilerConfigurationBlock.error"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.warning"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.ignore") //$NON-NLS-1$
};
GridLayout layout= new GridLayout();
layout.numColumns= 2;
layout.verticalSpacing= 2;
Composite warningsComposite= new Composite(folder, SWT.NULL);
warningsComposite.setLayout(layout);
Label description= new Label(warningsComposite, SWT.WRAP);
description.setText(PreferencesMessages.getString("CompilerConfigurationBlock.warnings.description")); //$NON-NLS-1$
GridData gd= new GridData();
gd.horizontalSpan= 2;
gd.widthHint= fPixelConverter.convertWidthInCharsToPixels(50);
description.setLayoutData(gd);
String label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_unreachable_code.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_UNREACHABLE_CODE, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_invalid_import.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_INVALID_IMPORT, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_unused_local.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_UNUSED_LOCAL, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_overriding_pkg_dflt.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_method_naming.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_METHOD_WITH_CONSTRUCTOR_NAME, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_hidden_catchblock.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_HIDDEN_CATCH_BLOCK, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_unused_imports.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_UNUSED_IMPORT, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_unused_parameter.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_UNUSED_PARAMETER, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_static_access_receiver.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_STATIC_ACCESS_RECEIVER, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_synth_access_emul.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_SYNTHETIC_ACCESS_EMULATION, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_no_effect_assignment.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_NO_EFFECT_ASSIGNMENT, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_max_per_unit.label"); //$NON-NLS-1$
Text text= addTextField(warningsComposite, label, PREF_PB_MAX_PER_UNIT);
text.setTextLimit(6);
return warningsComposite;
}
private Composite createCodeGenTabContent(Composite folder) {
String[] generateValues= new String[] { GENERATE, DO_NOT_GENERATE };
GridLayout layout= new GridLayout();
layout.numColumns= 2;
Composite codeGenComposite= new Composite(folder, SWT.NULL);
codeGenComposite.setLayout(layout);
String label= PreferencesMessages.getString("CompilerConfigurationBlock.variable_attr.label"); //$NON-NLS-1$
addCheckBox(codeGenComposite, label, PREF_LOCAL_VARIABLE_ATTR, generateValues, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.line_number_attr.label"); //$NON-NLS-1$
addCheckBox(codeGenComposite, label, PREF_LINE_NUMBER_ATTR, generateValues, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.source_file_attr.label"); //$NON-NLS-1$
addCheckBox(codeGenComposite, label, PREF_SOURCE_FILE_ATTR, generateValues, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.codegen_unused_local.label"); //$NON-NLS-1$
addCheckBox(codeGenComposite, label, PREF_CODEGEN_UNUSED_LOCAL, new String[] { PRESERVE, OPTIMIZE_OUT }, 0);
return codeGenComposite;
}
private Composite createComplianceTabContent(Composite folder) {
GridLayout layout= new GridLayout();
layout.numColumns= 2;
Composite complianceComposite= new Composite(folder, SWT.NULL);
complianceComposite.setLayout(layout);
String[] values34= new String[] { VERSION_1_3, VERSION_1_4 };
String[] values34Labels= new String[] {
PreferencesMessages.getString("CompilerConfigurationBlock.version13"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.version14") //$NON-NLS-1$
};
String label= PreferencesMessages.getString("CompilerConfigurationBlock.compiler_compliance.label"); //$NON-NLS-1$
addComboBox(complianceComposite, label, PREF_COMPLIANCE, values34, values34Labels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.default_settings.label"); //$NON-NLS-1$
addCheckBox(complianceComposite, label, INTR_DEFAULT_COMPLIANCE, new String[] { DEFAULT, USER }, 0);
int indent= fPixelConverter.convertWidthInCharsToPixels(2);
Control[] otherChildren= complianceComposite.getChildren();
String[] values14= new String[] { VERSION_1_1, VERSION_1_2, VERSION_1_3, VERSION_1_4 };
String[] values14Labels= new String[] {
PreferencesMessages.getString("CompilerConfigurationBlock.version11"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.version12"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.version13"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.version14") //$NON-NLS-1$
};
label= PreferencesMessages.getString("CompilerConfigurationBlock.codegen_targetplatform.label"); //$NON-NLS-1$
addComboBox(complianceComposite, label, PREF_CODEGEN_TARGET_PLATFORM, values14, values14Labels, indent);
label= PreferencesMessages.getString("CompilerConfigurationBlock.source_compatibility.label"); //$NON-NLS-1$
addComboBox(complianceComposite, label, PREF_SOURCE_COMPATIBILITY, values34, values34Labels, indent);
String[] errorWarningIgnore= new String[] { ERROR, WARNING, IGNORE };
String[] errorWarningIgnoreLabels= new String[] {
PreferencesMessages.getString("CompilerConfigurationBlock.error"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.warning"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.ignore") //$NON-NLS-1$
};
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_assert_as_identifier.label"); //$NON-NLS-1$
addComboBox(complianceComposite, label, PREF_PB_ASSERT_AS_IDENTIFIER, errorWarningIgnore, errorWarningIgnoreLabels, indent);
Control[] allChildren= complianceComposite.getChildren();
fComplianceControls.addAll(Arrays.asList(allChildren));
fComplianceControls.removeAll(Arrays.asList(otherChildren));
return complianceComposite;
}
private void addCheckBox(Composite parent, String label, String key, String[] values, int indent) {
ControlData data= new ControlData(key, values);
GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= 2;
gd.horizontalIndent= indent;
Button checkBox= new Button(parent, SWT.CHECK);
checkBox.setText(label);
checkBox.setData(data);
checkBox.setLayoutData(gd);
checkBox.addSelectionListener(fSelectionListener);
String currValue= (String)fWorkingValues.get(key);
checkBox.setSelection(data.getSelection(currValue) == 0);
fCheckBoxes.add(checkBox);
}
private void addComboBox(Composite parent, String label, String key, String[] values, String[] valueLabels, int indent) {
ControlData data= new ControlData(key, values);
GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
gd.horizontalIndent= indent;
Label labelControl= new Label(parent, SWT.LEFT | SWT.WRAP);
labelControl.setText(label);
labelControl.setLayoutData(gd);
Combo comboBox= new Combo(parent, SWT.READ_ONLY);
comboBox.setItems(valueLabels);
comboBox.setData(data);
comboBox.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
comboBox.addSelectionListener(fSelectionListener);
String currValue= (String)fWorkingValues.get(key);
comboBox.select(data.getSelection(currValue));
fComboBoxes.add(comboBox);
}
private Text addTextField(Composite parent, String label, String key) {
Label labelControl= new Label(parent, SWT.NONE);
labelControl.setText(label);
labelControl.setLayoutData(new GridData());
Text textBox= new Text(parent, SWT.BORDER | SWT.SINGLE);
textBox.setData(key);
textBox.setLayoutData(new GridData());
String currValue= (String) fWorkingValues.get(key);
textBox.setText(currValue);
textBox.addModifyListener(fTextModifyListener);
textBox.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
fTextBoxes.add(textBox);
return textBox;
}
private void controlChanged(Widget widget) {
ControlData data= (ControlData) widget.getData();
String newValue= null;
if (widget instanceof Button) {
newValue= data.getValue(((Button)widget).getSelection());
} else if (widget instanceof Combo) {
newValue= data.getValue(((Combo)widget).getSelectionIndex());
} else {
return;
}
fWorkingValues.put(data.getKey(), newValue);
validateSettings(data.getKey(), newValue);
}
private void textChanged(Text textControl) {
String key= (String) textControl.getData();
String number= textControl.getText();
fWorkingValues.put(key, number);
validateSettings(key, number);
}
private boolean checkValue(String key, String value) {
return value.equals(fWorkingValues.get(key));
}
/* (non-javadoc)
* Update fields and validate.
* @param changedKey Key that changed, or null, if all changed.
*/
private void validateSettings(String changedKey, String newValue) {
if (changedKey != null) {
if (INTR_DEFAULT_COMPLIANCE.equals(changedKey)) {
updateComplianceEnableState();
if (DEFAULT.equals(newValue)) {
updateComplianceDefaultSettings();
}
} else if (PREF_COMPLIANCE.equals(changedKey)) {
if (checkValue(INTR_DEFAULT_COMPLIANCE, DEFAULT)) {
updateComplianceDefaultSettings();
}
fComplianceStatus= validateCompliance();
} else if (PREF_SOURCE_COMPATIBILITY.equals(changedKey) ||
PREF_CODEGEN_TARGET_PLATFORM.equals(changedKey) ||
PREF_PB_ASSERT_AS_IDENTIFIER.equals(changedKey)) {
fComplianceStatus= validateCompliance();
} else if (PREF_PB_MAX_PER_UNIT.equals(changedKey)) {
fMaxNumberProblemsStatus= validateMaxNumberProblems();
} else if (PREF_RESOURCE_FILTER.equals(changedKey)) {
fResourceFilterStatus= validateResourceFilters();
} else {
return;
}
} else {
updateComplianceEnableState();
fComplianceStatus= validateCompliance();
fMaxNumberProblemsStatus= validateMaxNumberProblems();
fResourceFilterStatus= validateResourceFilters();
}
IStatus status= StatusUtil.getMostSevere(new IStatus[] { fComplianceStatus, fMaxNumberProblemsStatus, fResourceFilterStatus });
fContext.statusChanged(status);
}
private IStatus validateCompliance() {
StatusInfo status= new StatusInfo();
if (checkValue(PREF_COMPLIANCE, VERSION_1_3)) {
if (checkValue(PREF_SOURCE_COMPATIBILITY, VERSION_1_4)) {
status.setError(PreferencesMessages.getString("CompilerConfigurationBlock.cpl13src14.error")); //$NON-NLS-1$
return status;
} else if (checkValue(PREF_CODEGEN_TARGET_PLATFORM, VERSION_1_4)) {
status.setError(PreferencesMessages.getString("CompilerConfigurationBlock.cpl13trg14.error")); //$NON-NLS-1$
return status;
}
}
if (checkValue(PREF_SOURCE_COMPATIBILITY, VERSION_1_4)) {
if (!checkValue(PREF_PB_ASSERT_AS_IDENTIFIER, ERROR)) {
status.setError(PreferencesMessages.getString("CompilerConfigurationBlock.src14asrterr.error")); //$NON-NLS-1$
return status;
}
}
if (checkValue(PREF_SOURCE_COMPATIBILITY, VERSION_1_4)) {
if (!checkValue(PREF_CODEGEN_TARGET_PLATFORM, VERSION_1_4)) {
status.setError(PreferencesMessages.getString("CompilerConfigurationBlock.src14tgt14.error")); //$NON-NLS-1$
return status;
}
}
return status;
}
private IStatus validateMaxNumberProblems() {
String number= (String) fWorkingValues.get(PREF_PB_MAX_PER_UNIT);
StatusInfo status= new StatusInfo();
if (number.length() == 0) {
status.setError(PreferencesMessages.getString("CompilerConfigurationBlock.empty_input")); //$NON-NLS-1$
} else {
try {
int value= Integer.parseInt(number);
if (value <= 0) {
status.setError(PreferencesMessages.getFormattedString("CompilerConfigurationBlock.invalid_input", number)); //$NON-NLS-1$
}
} catch (NumberFormatException e) {
status.setError(PreferencesMessages.getFormattedString("CompilerConfigurationBlock.invalid_input", number)); //$NON-NLS-1$
}
}
return status;
}
private IStatus validateResourceFilters() {
String text= (String) fWorkingValues.get(PREF_RESOURCE_FILTER);
IWorkspace workspace= ResourcesPlugin.getWorkspace();
String[] filters= getTokens(text);
for (int i= 0; i < filters.length; i++) {
String fileName= filters[i].replace('*', 'x');
int resourceType= IResource.FILE;
int lastCharacter= fileName.length() - 1;
if (lastCharacter >= 0 && fileName.charAt(lastCharacter) == '/') {
fileName= fileName.substring(0, lastCharacter);
resourceType= IResource.FOLDER;
}
IStatus status= workspace.validateName(fileName, resourceType);
if (status.matches(IStatus.ERROR)) {
String message= PreferencesMessages.getFormattedString("CompilerConfigurationBlock.filter.invalidsegment.error", status.getMessage()); //$NON-NLS-1$
return new StatusInfo(IStatus.ERROR, message);
}
}
return new StatusInfo();
}
private IStatus validateTaskTags() {
return new StatusInfo();
}
private String[] getTokens(String text) {
StringTokenizer tok= new StringTokenizer(text, ","); //$NON-NLS-1$
int nTokens= tok.countTokens();
String[] res= new String[nTokens];
for (int i= 0; i < res.length; i++) {
res[i]= tok.nextToken();
}
return res;
}
/*
* Update the compliance controls' enable state
*/
private void updateComplianceEnableState() {
boolean enabled= checkValue(INTR_DEFAULT_COMPLIANCE, USER);
for (int i= fComplianceControls.size() - 1; i >= 0; i--) {
Control curr= (Control) fComplianceControls.get(i);
curr.setEnabled(enabled);
}
}
/*
* Set the default compliance values derived from the chosen level
*/
private void updateComplianceDefaultSettings() {
Object complianceLevel= fWorkingValues.get(PREF_COMPLIANCE);
if (VERSION_1_3.equals(complianceLevel)) {
fWorkingValues.put(PREF_PB_ASSERT_AS_IDENTIFIER, IGNORE);
fWorkingValues.put(PREF_SOURCE_COMPATIBILITY, VERSION_1_3);
fWorkingValues.put(PREF_CODEGEN_TARGET_PLATFORM, VERSION_1_1);
} else if (VERSION_1_4.equals(complianceLevel)) {
fWorkingValues.put(PREF_PB_ASSERT_AS_IDENTIFIER, ERROR);
fWorkingValues.put(PREF_SOURCE_COMPATIBILITY, VERSION_1_4);
fWorkingValues.put(PREF_CODEGEN_TARGET_PLATFORM, VERSION_1_4);
}
updateControls();
}
/*
* Evaluate if the current compliance setting correspond to a default setting
*/
private String getCurrentCompliance() {
Object complianceLevel= fWorkingValues.get(PREF_COMPLIANCE);
if ((VERSION_1_3.equals(complianceLevel)
&& checkValue(PREF_PB_ASSERT_AS_IDENTIFIER, IGNORE)
&& checkValue(PREF_SOURCE_COMPATIBILITY, VERSION_1_3)
&& checkValue(PREF_CODEGEN_TARGET_PLATFORM, VERSION_1_1))
|| (VERSION_1_4.equals(complianceLevel)
&& checkValue(PREF_PB_ASSERT_AS_IDENTIFIER, ERROR)
&& checkValue(PREF_SOURCE_COMPATIBILITY, VERSION_1_4)
&& checkValue(PREF_CODEGEN_TARGET_PLATFORM, VERSION_1_4))) {
return DEFAULT;
}
return USER;
}
public boolean performOk(boolean enabled) {
String[] allKeys= getAllKeys();
Map actualOptions= getOptions(false);
// preserve other options
boolean hasChanges= false;
for (int i= 0; i < allKeys.length; i++) {
String key= allKeys[i];
String oldVal= (String) actualOptions.get(key);
String val= null;
if (enabled) {
val= (String) fWorkingValues.get(key);
if (!val.equals(oldVal)) {
hasChanges= true;
actualOptions.put(key, val);
}
} else {
if (oldVal != null) {
actualOptions.remove(key);
hasChanges= true;
}
}
}
if (hasChanges) {
String title= PreferencesMessages.getString("CompilerConfigurationBlock.needsbuild.title"); //$NON-NLS-1$
String message;
if (fProject == null) {
message= PreferencesMessages.getString("CompilerConfigurationBlock.needsfullbuild.message"); //$NON-NLS-1$
} else {
message= PreferencesMessages.getString("CompilerConfigurationBlock.needsprojectbuild.message"); //$NON-NLS-1$
}
MessageDialog dialog= new MessageDialog(getShell(), title, null, message, MessageDialog.QUESTION, new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL }, 2);
int res= dialog.open();
if (res != 0 && res != 1) {
return false;
}
setOptions(actualOptions);
if (res == 0) {
doFullBuild();
}
}
return true;
}
private static boolean openQuestion(Shell parent, String title, String message) {
MessageDialog dialog= new MessageDialog(parent, title, null, message, MessageDialog.QUESTION, new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL }, 2);
return dialog.open() == 0;
}
private void doFullBuild() {
ProgressMonitorDialog dialog= new ProgressMonitorDialog(getShell());
try {
dialog.run(true, true, new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException {
try {
if (fProject != null) {
fProject.getProject().build(IncrementalProjectBuilder.FULL_BUILD, monitor);
} else {
JavaPlugin.getWorkspace().build(IncrementalProjectBuilder.FULL_BUILD, monitor);
}
} catch (CoreException e) {
throw new InvocationTargetException(e);
}
}
});
} catch (InterruptedException e) {
// cancelled by user
} catch (InvocationTargetException e) {
String title= PreferencesMessages.getString("CompilerConfigurationBlock.builderror.title"); //$NON-NLS-1$
String message= PreferencesMessages.getString("CompilerConfigurationBlock.builderror.message"); //$NON-NLS-1$
ExceptionHandler.handle(e, getShell(), title, message);
}
}
public void performDefaults() {
fWorkingValues= JavaCore.getDefaultOptions();
fWorkingValues.put(INTR_DEFAULT_COMPLIANCE, getCurrentCompliance());
updateControls();
validateSettings(null, null);
}
private void updateControls() {
// update the UI
for (int i= fCheckBoxes.size() - 1; i >= 0; i--) {
Button curr= (Button) fCheckBoxes.get(i);
ControlData data= (ControlData) curr.getData();
String currValue= (String) fWorkingValues.get(data.getKey());
curr.setSelection(data.getSelection(currValue) == 0);
}
for (int i= fComboBoxes.size() - 1; i >= 0; i--) {
Combo curr= (Combo) fComboBoxes.get(i);
ControlData data= (ControlData) curr.getData();
String currValue= (String) fWorkingValues.get(data.getKey());
curr.select(data.getSelection(currValue));
}
for (int i= fTextBoxes.size() - 1; i >= 0; i--) {
Text curr= (Text) fTextBoxes.get(i);
String key= (String) curr.getData();
String currValue= (String) fWorkingValues.get(key);
curr.setText(currValue);
}
}
}
|
23,112 |
Bug 23112 [search] need a way to search for references to the implicit non-arg constructor
|
i'd like to search for references to all constructors of a class - it's easy when the class has some declared construcotrs. the problem is that when the class does not declare any explicit constructors, you can still have (super()) references to the non-arg implicit constructor. but how do i search for these?
|
resolved wontfix
|
af4f733
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-20T15:30:02Z | 2002-09-03T13:33:20Z |
org.eclipse.jdt.ui/core
| |
23,112 |
Bug 23112 [search] need a way to search for references to the implicit non-arg constructor
|
i'd like to search for references to all constructors of a class - it's easy when the class has some declared construcotrs. the problem is that when the class does not declare any explicit constructors, you can still have (super()) references to the non-arg implicit constructor. but how do i search for these?
|
resolved wontfix
|
af4f733
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-20T15:30:02Z | 2002-09-03T13:33:20Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ConstructorReferenceFinder.java
| |
25,845 |
Bug 25845 Support for manually attaching source to a class path container
|
From Dejan: There is a work item on the ability to manually attach source to classpath entries managed by classpath container. We discussed it and we have workable options but we would like if we can have it by M3 because we want to start self-hosting using classpath containers ourselves.
|
resolved fixed
|
3eaf7d8
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-20T17:30:52Z | 2002-11-07T17:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/ClassFileEditor.java
|
/**********************************************************************
Copyright (c) 2000, 2002 IBM Corp. 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 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.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.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.jface.resource.JFaceResources;
import org.eclipse.jface.text.IWidgetTokenKeeper;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.IVerticalRuler;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
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.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;
/**
* 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 {
final IPackageFragmentRoot root= getPackageFragmentRoot(fFile);
if (root != null) {
IClasspathEntry entry= root.getRawClasspathEntry();
if (!root.isArchive()) {
createLabel(composite, JavaEditorMessages.getFormattedString("SourceAttachmentForm.message.noSource", fFile.getElementName())); //$NON-NLS-1$
} else if (entry != null && entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
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$
} else {
Button button;
IPath path= root.getSourceAttachmentPath();
if (path == null) {
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(new SelectionListener() {
public void widgetSelected(SelectionEvent event) {
try {
SourceAttachmentDialog dialog= new SourceAttachmentDialog(fScrolledComposite.getShell(), root);
if (dialog.open() == SourceAttachmentDialog.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) {}
});
}
}
} 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;
}
/*
* @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$
}
};
private StackLayout fStackLayout;
private Composite fParent;
private Composite fViewerComposite;
private Control fSourceAttachmentForm;
/**
* 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$
*/
setAction(ITextEditorActionConstants.BOOKMARK, null);
setAction(ITextEditorActionConstants.ADD_TASK, null);
}
/*
* @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 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"),
null)); //$NON-NLS-1$
JavaModelException e= probeInputForSource(input);
if (e != null) {
IClassFileEditorInput classFileEditorInput= (IClassFileEditorInput) input;
IClassFile file= classFileEditorInput.getClassFile();
if (!file.getJavaProject().isOnClasspath(file)) {
throw new CoreException(JavaUIStatus.createError(
IJavaModelStatusConstants.INVALID_RESOURCE,
JavaEditorMessages.getString("ClassFileEditor.error.classfile_not_on_classpath"),
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);
}
}
/**
* Returns the package fragment root corresponding to the class file.
*/
private static IPackageFragmentRoot getPackageFragmentRoot(IClassFile file) {
IJavaElement element= file.getParent();
while (element != null && element.getElementType() != IJavaElement.PACKAGE_FRAGMENT_ROOT)
element= element.getParent();
return (IPackageFragmentRoot) element;
}
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(final IClassFileEditorInput input) {
if (input != null && input.equals(getEditorInput())) {
ISourceViewer viewer= getSourceViewer();
if (viewer != null) {
StyledText textWidget= viewer.getTextWidget();
if (textWidget != null && !textWidget.isDisposed()) {
textWidget.getDisplay().asyncExec(new Runnable() {
public void run() {
setInput(input);
}
});
}
}
}
}
/*
* @see JavaEditor#createJavaSourceViewer(Composite, IVerticalRuler, int)
*/
protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler ruler, int styles) {
return new SourceViewer(parent, ruler, styles) {
public boolean requestWidgetToken(IWidgetTokenKeeper requester) {
if (WorkbenchHelp.isContextHelpDisplayed())
return false;
return super.requestWidgetToken(requester);
}
};
}
/*
* @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();
}
}
|
25,845 |
Bug 25845 Support for manually attaching source to a class path container
|
From Dejan: There is a work item on the ability to manually attach source to classpath entries managed by classpath container. We discussed it and we have workable options but we would like if we can have it by M3 because we want to start self-hosting using classpath containers ourselves.
|
resolved fixed
|
3eaf7d8
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-20T17:30:52Z | 2002-11-07T17:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/SourceAttachmentDialog.java
|
package org.eclipse.jdt.internal.ui.javaeditor;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.dialogs.StatusDialog;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener;
import org.eclipse.jdt.internal.ui.wizards.buildpaths.SourceAttachmentBlock;
/**
* A dialog to attach source to a jar file.
*
* copied from org.eclipse.jdt.internal.ui.wizards.buildpaths.LibrariesWorkbookPage.SourceAttachmentDialog.
*/
public class SourceAttachmentDialog extends StatusDialog implements IStatusChangeListener {
private SourceAttachmentBlock fSourceAttachmentBlock;
private IPackageFragmentRoot fRoot;
public SourceAttachmentDialog(Shell parent, IPackageFragmentRoot root) throws JavaModelException {
super(parent);
fRoot= root;
IClasspathEntry entry= fRoot.getRawClasspathEntry();
setTitle(JavaEditorMessages.getFormattedString("SourceAttachmentDialog.title", entry.getPath().toString())); //$NON-NLS-1$
fSourceAttachmentBlock= new SourceAttachmentBlock(ResourcesPlugin.getWorkspace().getRoot(), this, entry);
}
/*
* @see Windows#configureShell
*/
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
WorkbenchHelp.setHelp(newShell, IJavaHelpContextIds.SOURCE_ATTACHMENT_DIALOG);
}
protected Control createDialogArea(Composite parent) {
Composite composite= (Composite)super.createDialogArea(parent);
Control inner= fSourceAttachmentBlock.createControl(composite);
inner.setLayoutData(new GridData(GridData.FILL_BOTH));
return composite;
}
public void statusChanged(IStatus status) {
updateStatus(status);
}
public IPath getSourceAttachmentPath() {
return fSourceAttachmentBlock.getSourceAttachmentPath();
}
public IPath getSourceAttachmentRootPath() {
return fSourceAttachmentBlock.getSourceAttachmentRootPath();
}
protected void okPressed() {
super.okPressed();
try {
IJavaProject project= fRoot.getJavaProject();
IRunnableWithProgress runnable= fSourceAttachmentBlock.getRunnable(project, getShell());
new ProgressMonitorDialog(getShell()).run(true, true, runnable);
} catch (InvocationTargetException e) {
String title= JavaEditorMessages.getString("SourceAttachmentDialog.error.title"); //$NON-NLS-1$
String message= JavaEditorMessages.getString("SourceAttachmentDialog.error.message"); //$NON-NLS-1$
ExceptionHandler.handle(e, getShell(), title, message);
} catch (InterruptedException e) {
// cancelled
}
}
}
|
25,845 |
Bug 25845 Support for manually attaching source to a class path container
|
From Dejan: There is a work item on the ability to manually attach source to classpath entries managed by classpath container. We discussed it and we have workable options but we would like if we can have it by M3 because we want to start self-hosting using classpath containers ourselves.
|
resolved fixed
|
3eaf7d8
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-20T17:30:52Z | 2002-11-07T17:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/SourceAttachmentPropertyPage.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.preferences;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.ui.dialogs.PropertyPage;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.IClasspathContainer;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.dialogs.StatusUtil;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener;
import org.eclipse.jdt.internal.ui.wizards.buildpaths.SourceAttachmentBlock;
/**
* Property page to configure a archive's JARs source attachment
*/
public class SourceAttachmentPropertyPage extends PropertyPage implements IStatusChangeListener {
private SourceAttachmentBlock fSourceAttachmentBlock;
private IPackageFragmentRoot fJarRoot;
public SourceAttachmentPropertyPage() {
}
/*
* @see PreferencePage#createContents
*/
protected Control createContents(Composite composite) {
initializeDialogUnits(composite);
WorkbenchHelp.setHelp(composite, IJavaHelpContextIds.SOURCE_ATTACHMENT_PROPERTY_PAGE);
fJarRoot= getJARPackageFragmentRoot();
if (fJarRoot == null) {
return createMessageContent(composite, PreferencesMessages.getString("SourceAttachmentPropertyPage.noarchive.message")); //$NON-NLS-1$
}
try {
IClasspathEntry entry= fJarRoot.getRawClasspathEntry();
if (entry == null) {
// use a dummy entry to use for initialization
entry= JavaCore.newLibraryEntry(fJarRoot.getPath(), null, null);
} else if (entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
IClasspathContainer container= JavaCore.getClasspathContainer(entry.getPath(), fJarRoot.getJavaProject());
String containerName= container != null ? container.getDescription() : entry.getPath().toString();
return createMessageContent(composite, PreferencesMessages.getFormattedString("SourceAttachmentPropertyPage.containerentry.message", containerName)); //$NON-NLS-1$
}
IWorkspaceRoot wsroot= fJarRoot.getJavaModel().getWorkspace().getRoot();
fSourceAttachmentBlock= new SourceAttachmentBlock(wsroot, this, entry);
return fSourceAttachmentBlock.createControl(composite);
} catch (CoreException e) {
JavaPlugin.log(e);
return createMessageContent(composite, PreferencesMessages.getString("SourceAttachmentPropertyPage.noarchive.message")); //$NON-NLS-1$
}
}
private Control createMessageContent(Composite composite, String message) {
Composite inner= new Composite(composite, SWT.NONE);
GridLayout layout= new GridLayout();
layout.marginHeight= 0;
layout.marginWidth= 0;
inner.setLayout(layout);
GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.widthHint= convertWidthInCharsToPixels(80);
Label label= new Label(inner, SWT.LEFT + SWT.WRAP);
label.setText(message);
label.setLayoutData(gd);
return inner;
}
/*
* @see IPreferencePage#performOk
*/
public boolean performOk() {
if (fSourceAttachmentBlock != null) {
try {
IRunnableWithProgress runnable= fSourceAttachmentBlock.getRunnable(fJarRoot.getJavaProject(), getShell());
new ProgressMonitorDialog(getShell()).run(true, true, runnable);
} catch (InvocationTargetException e) {
String title= PreferencesMessages.getString("SourceAttachmentPropertyPage.error.title"); //$NON-NLS-1$
String message= PreferencesMessages.getString("SourceAttachmentPropertyPage.error.message"); //$NON-NLS-1$
ExceptionHandler.handle(e, getShell(), title, message);
return false;
} catch (InterruptedException e) {
// cancelled
return false;
}
}
return true;
}
/*
* @see PreferencePage#performDefaults()
*/
protected void performDefaults() {
if (fSourceAttachmentBlock != null) {
fSourceAttachmentBlock.setDefaults();
}
super.performDefaults();
}
private IPackageFragmentRoot getJARPackageFragmentRoot() {
// try to find it as Java element (needed for external jars)
IAdaptable adaptable= getElement();
IJavaElement elem= (IJavaElement) adaptable.getAdapter(IJavaElement.class);
if (elem instanceof IPackageFragmentRoot) {
IPackageFragmentRoot root= (IPackageFragmentRoot) elem;
if (root.isArchive()) {
return root;
} else {
return null;
}
}
// not on classpath or not in a java project
IResource resource= (IResource) adaptable.getAdapter(IResource.class);
if (resource instanceof IFile) {
IProject proj= resource.getProject();
try {
if (proj.hasNature(JavaCore.NATURE_ID)) {
IJavaProject jproject= JavaCore.create(proj);
return jproject.getPackageFragmentRoot(resource);
}
} catch (CoreException e) {
JavaPlugin.log(e.getStatus());
}
}
return null;
}
/*
* @see IStatusChangeListener#statusChanged
*/
public void statusChanged(IStatus status) {
setValid(!status.matches(IStatus.ERROR));
StatusUtil.applyToStatusLine(this, status);
}
}
|
25,845 |
Bug 25845 Support for manually attaching source to a class path container
|
From Dejan: There is a work item on the ability to manually attach source to classpath entries managed by classpath container. We discussed it and we have workable options but we would like if we can have it by M3 because we want to start self-hosting using classpath containers ourselves.
|
resolved fixed
|
3eaf7d8
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-20T17:30:52Z | 2002-11-07T17:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/LibrariesWorkbookPage.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.wizards.buildpaths;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
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.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.model.WorkbenchContentProvider;
import org.eclipse.ui.model.WorkbenchLabelProvider;
import org.eclipse.ui.views.navigator.ResourceSorter;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaModel;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.IUIConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.dialogs.StatusDialog;
import org.eclipse.jdt.internal.ui.preferences.JavadocConfigurationBlock;
import org.eclipse.jdt.internal.ui.util.PixelConverter;
import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener;
import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages;
import org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator;
import org.eclipse.jdt.internal.ui.wizards.TypedViewerFilter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.ComboDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.ITreeListAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.TreeListDialogField;
public class LibrariesWorkbookPage extends BuildPathBasePage {
private ListDialogField fClassPathList;
private IJavaProject fCurrJProject;
private TreeListDialogField fLibrariesList;
private IWorkspaceRoot fWorkspaceRoot;
private IDialogSettings fDialogSettings;
private Control fSWTControl;
private final int IDX_ADDJAR= 0;
private final int IDX_ADDEXT= 1;
private final int IDX_ADDVAR= 2;
private final int IDX_ADDLIB= 3;
private final int IDX_ADDFOL= 4;
private final int IDX_EDIT= 6;
private final int IDX_REMOVE= 7;
public LibrariesWorkbookPage(IWorkspaceRoot root, ListDialogField classPathList) {
fClassPathList= classPathList;
fWorkspaceRoot= root;
fSWTControl= null;
fDialogSettings= JavaPlugin.getDefault().getDialogSettings();
String[] buttonLabels= new String[] {
/* IDX_ADDJAR*/ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.addjar.button"), //$NON-NLS-1$
/* IDX_ADDEXT */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.addextjar.button"), //$NON-NLS-1$
/* IDX_ADDVAR */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.addvariable.button"), //$NON-NLS-1$
/* IDX_ADDLIB */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.addlibrary.button"), //$NON-NLS-1$
/* IDX_ADDFOL */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.addclassfolder.button"), //$NON-NLS-1$
/* */ null,
/* IDX_EDIT */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.edit.button"), //$NON-NLS-1$
/* IDX_REMOVE */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.remove.button") //$NON-NLS-1$
};
LibrariesAdapter adapter= new LibrariesAdapter();
fLibrariesList= new TreeListDialogField(adapter, buttonLabels, new CPListLabelProvider());
fLibrariesList.setDialogFieldListener(adapter);
fLibrariesList.setLabelText(NewWizardMessages.getString("LibrariesWorkbookPage.libraries.label")); //$NON-NLS-1$
fLibrariesList.setRemoveButtonIndex(IDX_REMOVE); //$NON-NLS-1$
fLibrariesList.enableButton(IDX_EDIT, false);
fLibrariesList.setViewerSorter(new CPListElementSorter());
}
public void init(IJavaProject jproject) {
fCurrJProject= jproject;
updateLibrariesList();
}
private void updateLibrariesList() {
List cpelements= fClassPathList.getElements();
List libelements= new ArrayList(cpelements.size());
int nElements= cpelements.size();
for (int i= 0; i < nElements; i++) {
CPListElement cpe= (CPListElement)cpelements.get(i);
if (isEntryKind(cpe.getEntryKind())) {
libelements.add(cpe);
}
}
fLibrariesList.setElements(libelements);
}
// -------- ui creation
public Control getControl(Composite parent) {
PixelConverter converter= new PixelConverter(parent);
Composite composite= new Composite(parent, SWT.NONE);
LayoutUtil.doDefaultLayout(composite, new DialogField[] { fLibrariesList }, true);
LayoutUtil.setHorizontalGrabbing(fLibrariesList.getTreeControl(null));
int buttonBarWidth= converter.convertWidthInCharsToPixels(24);
fLibrariesList.setButtonsMinWidth(buttonBarWidth);
fLibrariesList.getTreeViewer().setSorter(new CPListElementSorter());
fSWTControl= composite;
return composite;
}
private Shell getShell() {
if (fSWTControl != null) {
return fSWTControl.getShell();
}
return JavaPlugin.getActiveWorkbenchShell();
}
private class LibrariesAdapter implements IDialogFieldListener, ITreeListAdapter {
private final Object[] EMPTY_ARR= new Object[0];
// -------- IListAdapter --------
public void customButtonPressed(TreeListDialogField field, int index) {
libaryPageCustomButtonPressed(field, index);
}
public void selectionChanged(TreeListDialogField field) {
libaryPageSelectionChanged(field);
}
public void doubleClicked(TreeListDialogField field) {
libaryPageDoubleClicked(field);
}
public Object[] getChildren(TreeListDialogField field, Object element) {
if (element instanceof CPListElement) {
return ((CPListElement) element).getChildren(false);
}
return EMPTY_ARR;
}
public Object getParent(TreeListDialogField field, Object element) {
if (element instanceof CPListElementAttribute) {
return ((CPListElementAttribute) element).getParent();
}
return null;
}
public boolean hasChildren(TreeListDialogField field, Object element) {
return (element instanceof CPListElement);
}
// ---------- IDialogFieldListener --------
public void dialogFieldChanged(DialogField field) {
libaryPageDialogFieldChanged(field);
}
}
private void libaryPageCustomButtonPressed(DialogField field, int index) {
CPListElement[] libentries= null;
switch (index) {
case IDX_ADDJAR: /* add jar */
libentries= openJarFileDialog(null);
break;
case IDX_ADDEXT: /* add external jar */
libentries= openExtJarFileDialog(null);
break;
case IDX_ADDVAR: /* add variable */
libentries= openVariableSelectionDialog(null);
break;
case IDX_ADDLIB: /* addvanced */
libentries= openContainerSelectionDialog(null);
break;
case IDX_ADDFOL: /* addvanced */
libentries= openClassFolderDialog(null);
break;
case IDX_EDIT: /* edit */
editEntry();
return;
}
if (libentries != null) {
int nElementsChosen= libentries.length;
// remove duplicates
List cplist= fLibrariesList.getElements();
List elementsToAdd= new ArrayList(nElementsChosen);
for (int i= 0; i < nElementsChosen; i++) {
CPListElement curr= libentries[i];
if (!cplist.contains(curr) && !elementsToAdd.contains(curr)) {
elementsToAdd.add(curr);
addAttachmentsFromExistingLibs(curr);
}
}
fLibrariesList.addElements(elementsToAdd);
fLibrariesList.postSetSelection(new StructuredSelection(libentries));
}
}
protected void libaryPageDoubleClicked(TreeListDialogField field) {
List selection= fLibrariesList.getSelectedElements();
if (canEdit(selection)) {
editEntry();
}
}
/**
* Method editEntry.
*/
private void editEntry() {
List selElements= fLibrariesList.getSelectedElements();
if (selElements.size() != 1) {
return;
}
Object elem= selElements.get(0);
if (fLibrariesList.getIndexOfElement(elem) != -1) {
editElementEntry((CPListElement) elem);
} else if (elem instanceof CPListElementAttribute) {
editAttributeEntry((CPListElementAttribute) elem);
}
}
private void editAttributeEntry(CPListElementAttribute elem) {
String key= elem.getKey();
if (key.equals(CPListElement.SOURCEATTACHMENT)) {
CPListElement selElement= (CPListElement) elem.getParent();
SourceAttachmentDialog dialog= new SourceAttachmentDialog(getShell(), fWorkspaceRoot, selElement);
if (dialog.open() == SourceAttachmentDialog.OK) {
selElement.setAttribute(CPListElement.SOURCEATTACHMENT, dialog.getSourceAttachmentPath());
fLibrariesList.refresh();
fClassPathList.refresh(); // images
}
} else if (key.equals(CPListElement.JAVADOC)) {
CPListElement selElement= (CPListElement) elem.getParent();
JavadocPropertyDialog dialog= new JavadocPropertyDialog(getShell(), selElement);
if (dialog.open() == JavadocPropertyDialog.OK) {
selElement.setAttribute(CPListElement.JAVADOC, dialog.getJavaDocLocation());
fLibrariesList.refresh();
}
}
}
private void editElementEntry(CPListElement elem) {
CPListElement[] res= null;
switch (elem.getEntryKind()) {
case IClasspathEntry.CPE_CONTAINER:
res= openContainerSelectionDialog(elem);
break;
case IClasspathEntry.CPE_LIBRARY:
IResource resource= elem.getResource();
if (resource == null) {
res= openExtJarFileDialog(elem);
} else if (resource.getType() == IResource.FOLDER) {
if (resource.exists()) {
res= openClassFolderDialog(elem);
} else {
res= openNewClassFolderDialog(elem);
}
} else if (resource.getType() == IResource.FILE) {
res= openJarFileDialog(elem);
}
break;
case IClasspathEntry.CPE_VARIABLE:
res= openVariableSelectionDialog(elem);
break;
}
if (res != null && res.length > 0) {
fLibrariesList.replaceElement(elem, res[0]);
}
}
private void libaryPageSelectionChanged(DialogField field) {
List selElements= fLibrariesList.getSelectedElements();
fLibrariesList.enableButton(IDX_EDIT, canEdit(selElements));
}
private boolean canEdit(List selElements) {
if (selElements.size() != 1) {
return false;
}
Object elem= selElements.get(0);
if (fLibrariesList.getIndexOfElement(elem) != -1) {
return true;
}
if (elem instanceof CPListElementAttribute) {
/*CPListElementAttribute attrib= (CPListElementAttribute) elem;
if (attrib.getKey().equals(CPListElement.JAVADOC)) {
return true;
}*/
return ((CPListElementAttribute) elem).getParent().getParentContainer() == null;
}
return false;
}
private void libaryPageDialogFieldChanged(DialogField field) {
if (fCurrJProject != null) {
// already initialized
updateClasspathList();
}
}
private void updateClasspathList() {
List projelements= fLibrariesList.getElements();
boolean remove= false;
List cpelements= fClassPathList.getElements();
// backwards, as entries will be deleted
for (int i= cpelements.size() - 1; i >= 0; i--) {
CPListElement cpe= (CPListElement)cpelements.get(i);
int kind= cpe.getEntryKind();
if (isEntryKind(kind)) {
if (!projelements.remove(cpe)) {
cpelements.remove(i);
remove= true;
}
}
}
for (int i= 0; i < projelements.size(); i++) {
cpelements.add(projelements.get(i));
}
if (remove || (projelements.size() > 0)) {
fClassPathList.setElements(cpelements);
}
}
private CPListElement[] openNewClassFolderDialog(CPListElement existing) {
String title= (existing == null) ? NewWizardMessages.getString("LibrariesWorkbookPage.NewClassFolderDialog.new.title") : NewWizardMessages.getString("LibrariesWorkbookPage.NewClassFolderDialog.edit.title"); //$NON-NLS-1$ //$NON-NLS-2$
IProject currProject= fCurrJProject.getProject();
NewContainerDialog dialog= new NewContainerDialog(getShell(), title, currProject, getUsedContainers(existing), existing);
IPath projpath= currProject.getFullPath();
dialog.setMessage(NewWizardMessages.getFormattedString("LibrariesWorkbookPage.NewClassFolderDialog.description", projpath.toString())); //$NON-NLS-1$
if (dialog.open() == NewContainerDialog.OK) {
IFolder folder= dialog.getFolder();
return new CPListElement[] { newCPLibraryElement(folder) };
}
return null;
}
private CPListElement[] openClassFolderDialog(CPListElement existing) {
Class[] acceptedClasses= new Class[] { IFolder.class };
TypedElementSelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, existing == null);
acceptedClasses= new Class[] { IProject.class, IFolder.class };
ViewerFilter filter= new TypedViewerFilter(acceptedClasses, getUsedContainers(existing));
ILabelProvider lp= new WorkbenchLabelProvider();
ITreeContentProvider cp= new WorkbenchContentProvider();
String title= (existing == null) ? NewWizardMessages.getString("LibrariesWorkbookPage.ExistingClassFolderDialog.new.title") : NewWizardMessages.getString("LibrariesWorkbookPage.ExistingClassFolderDialog.edit.title"); //$NON-NLS-1$ //$NON-NLS-2$
String message= (existing == null) ? NewWizardMessages.getString("LibrariesWorkbookPage.ExistingClassFolderDialog.new.description") : NewWizardMessages.getString("LibrariesWorkbookPage.ExistingClassFolderDialog.edit.description"); //$NON-NLS-1$ //$NON-NLS-2$
FolderSelectionDialog dialog= new FolderSelectionDialog(getShell(), lp, cp);
dialog.setValidator(validator);
dialog.setTitle(title);
dialog.setMessage(message);
dialog.addFilter(filter);
dialog.setInput(fWorkspaceRoot);
dialog.setSorter(new ResourceSorter(ResourceSorter.NAME));
if (existing == null) {
dialog.setInitialSelection(fCurrJProject.getProject());
} else {
dialog.setInitialSelection(existing.getResource());
}
if (dialog.open() == FolderSelectionDialog.OK) {
Object[] elements= dialog.getResult();
CPListElement[] res= new CPListElement[elements.length];
for (int i= 0; i < res.length; i++) {
IResource elem= (IResource) elements[i];
res[i]= newCPLibraryElement(elem);
}
return res;
}
return null;
}
private CPListElement[] openJarFileDialog(CPListElement existing) {
Class[] acceptedClasses= new Class[] { IFile.class };
TypedElementSelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, existing == null);
ViewerFilter filter= new ArchiveFileFilter(getUsedJARFiles(existing), true);
ILabelProvider lp= new WorkbenchLabelProvider();
ITreeContentProvider cp= new WorkbenchContentProvider();
String title= (existing == null) ? NewWizardMessages.getString("LibrariesWorkbookPage.JARArchiveDialog.new.title") : NewWizardMessages.getString("LibrariesWorkbookPage.JARArchiveDialog.edit.title"); //$NON-NLS-1$ //$NON-NLS-2$
String message= (existing == null) ? NewWizardMessages.getString("LibrariesWorkbookPage.JARArchiveDialog.new.description") : NewWizardMessages.getString("LibrariesWorkbookPage.JARArchiveDialog.edit.description"); //$NON-NLS-1$ //$NON-NLS-2$
ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), lp, cp);
dialog.setValidator(validator);
dialog.setTitle(title);
dialog.setMessage(message);
dialog.addFilter(filter);
dialog.setInput(fWorkspaceRoot);
dialog.setSorter(new ResourceSorter(ResourceSorter.NAME));
if (existing == null) {
dialog.setInitialSelection(fCurrJProject.getProject());
} else {
dialog.setInitialSelection(existing.getResource());
}
if (dialog.open() == ElementTreeSelectionDialog.OK) {
Object[] elements= dialog.getResult();
CPListElement[] res= new CPListElement[elements.length];
for (int i= 0; i < res.length; i++) {
IResource elem= (IResource)elements[i];
res[i]= newCPLibraryElement(elem);
}
return res;
}
return null;
}
private IContainer[] getUsedContainers(CPListElement existing) {
ArrayList res= new ArrayList();
if (fCurrJProject.exists()) {
try {
IPath outputLocation= fCurrJProject.getOutputLocation();
if (outputLocation != null) {
IResource resource= fWorkspaceRoot.findMember(outputLocation);
if (resource instanceof IFolder) { // != Project
res.add(resource);
}
}
} catch (JavaModelException e) {
// ignore it here, just log
JavaPlugin.log(e.getStatus());
}
}
List cplist= fLibrariesList.getElements();
for (int i= 0; i < cplist.size(); i++) {
CPListElement elem= (CPListElement)cplist.get(i);
if (elem.getEntryKind() == IClasspathEntry.CPE_LIBRARY && (elem != existing)) {
IResource resource= elem.getResource();
if (resource instanceof IContainer && !resource.equals(existing)) {
res.add(resource);
}
}
}
return (IContainer[]) res.toArray(new IContainer[res.size()]);
}
private IFile[] getUsedJARFiles(CPListElement existing) {
List res= new ArrayList();
List cplist= fLibrariesList.getElements();
for (int i= 0; i < cplist.size(); i++) {
CPListElement elem= (CPListElement)cplist.get(i);
if (elem.getEntryKind() == IClasspathEntry.CPE_LIBRARY && (elem != existing)) {
IResource resource= elem.getResource();
if (resource instanceof IFile) {
res.add(resource);
}
}
}
return (IFile[]) res.toArray(new IFile[res.size()]);
}
private CPListElement newCPLibraryElement(IResource res) {
return new CPListElement(fCurrJProject, IClasspathEntry.CPE_LIBRARY, res.getFullPath(), res);
};
private CPListElement[] openExtJarFileDialog(CPListElement existing) {
String lastUsedPath;
if (existing != null) {
lastUsedPath= existing.getPath().removeLastSegments(1).toOSString();
} else {
lastUsedPath= fDialogSettings.get(IUIConstants.DIALOGSTORE_LASTEXTJAR);
if (lastUsedPath == null) {
lastUsedPath= ""; //$NON-NLS-1$
}
}
String title= (existing == null) ? NewWizardMessages.getString("LibrariesWorkbookPage.ExtJARArchiveDialog.new.title") : NewWizardMessages.getString("LibrariesWorkbookPage.ExtJARArchiveDialog.edit.title"); //$NON-NLS-1$ //$NON-NLS-2$
FileDialog dialog= new FileDialog(getShell(), existing == null ? SWT.MULTI : SWT.SINGLE);
dialog.setText(title);
dialog.setFilterExtensions(new String[] {"*.jar;*.zip"}); //$NON-NLS-1$
dialog.setFilterPath(lastUsedPath);
if (existing != null) {
dialog.setFileName(existing.getPath().lastSegment());
}
String res= dialog.open();
if (res == null) {
return null;
}
String[] fileNames= dialog.getFileNames();
int nChosen= fileNames.length;
IPath filterPath= new Path(dialog.getFilterPath());
CPListElement[] elems= new CPListElement[nChosen];
for (int i= 0; i < nChosen; i++) {
IPath path= filterPath.append(fileNames[i]).makeAbsolute();
elems[i]= new CPListElement(fCurrJProject, IClasspathEntry.CPE_LIBRARY, path, null);
}
fDialogSettings.put(IUIConstants.DIALOGSTORE_LASTEXTJAR, filterPath.toOSString());
return elems;
}
private CPListElement[] openVariableSelectionDialog(CPListElement existing) {
if (existing == null) {
NewVariableEntryDialog dialog= new NewVariableEntryDialog(getShell());
dialog.setTitle(NewWizardMessages.getString("LibrariesWorkbookPage.VariableSelectionDialog.new.title"));
if (dialog.open() == NewVariableEntryDialog.OK) {
List existingElements= fLibrariesList.getElements();
IPath[] paths= dialog.getResult();
ArrayList result= new ArrayList();
for (int i = 0; i < paths.length; i++) {
CPListElement elem= new CPListElement(fCurrJProject, IClasspathEntry.CPE_VARIABLE, paths[i], null);
IPath resolvedPath= JavaCore.getResolvedVariablePath(paths[i]);
elem.setIsMissing((resolvedPath == null) || !resolvedPath.toFile().exists());
if (!existingElements.contains(elem)) {
result.add(elem);
}
}
return (CPListElement[]) result.toArray(new CPListElement[result.size()]);
}
} else {
List existingElements= fLibrariesList.getElements();
ArrayList existingPaths= new ArrayList(existingElements.size());
for (int i= 0; i < existingElements.size(); i++) {
CPListElement elem= (CPListElement) existingElements.get(i);
if (elem.getEntryKind() == IClasspathEntry.CPE_VARIABLE) {
existingPaths.add(elem.getPath());
}
}
EditVariableEntryDialog dialog= new EditVariableEntryDialog(getShell(), existing.getPath(), existingPaths);
dialog.setTitle(NewWizardMessages.getString("LibrariesWorkbookPage.VariableSelectionDialog.edit.title"));
if (dialog.open() == EditVariableEntryDialog.OK) {
CPListElement elem= new CPListElement(fCurrJProject, IClasspathEntry.CPE_VARIABLE, dialog.getPath(), null);
return new CPListElement[] { elem };
}
}
return null;
}
private CPListElement[] openContainerSelectionDialog(CPListElement existing) {
IClasspathEntry elem= null;
String title;
if (existing == null) {
title= NewWizardMessages.getString("LibrariesWorkbookPage.ContainerDialog.new.title"); //$NON-NLS-1$
} else {
title= NewWizardMessages.getString("LibrariesWorkbookPage.ContainerDialog.edit.title"); //$NON-NLS-1$
elem= existing.getClasspathEntry();
}
return openContainerDialog(title, new ClasspathContainerWizard(elem, fCurrJProject, getRawClasspath()));
}
private CPListElement[] openContainerDialog(String title, ClasspathContainerWizard wizard) {
WizardDialog dialog= new WizardDialog(getShell(), wizard);
PixelConverter converter= new PixelConverter(getShell());
dialog.setMinimumPageSize(converter.convertWidthInCharsToPixels(40), converter.convertHeightInCharsToPixels(20));
dialog.create();
dialog.getShell().setText(title);
if (dialog.open() == WizardDialog.OK) {
IClasspathEntry created= wizard.getNewEntry();
if (created != null) {
CPListElement elem= new CPListElement(fCurrJProject, IClasspathEntry.CPE_CONTAINER, created.getPath(), null);
if (elem != null) {
return new CPListElement[] { elem };
}
}
}
return null;
}
private void addAttachmentsFromExistingLibs(CPListElement elem) {
if (elem.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
return;
}
try {
IJavaModel jmodel= fCurrJProject.getJavaModel();
IJavaProject[] jprojects= jmodel.getJavaProjects();
for (int i= 0; i < jprojects.length; i++) {
IJavaProject curr= jprojects[i];
if (!curr.equals(fCurrJProject)) {
IClasspathEntry[] entries= curr.getRawClasspath();
for (int k= 0; k < entries.length; k++) {
IClasspathEntry entry= entries[k];
if (entry.getEntryKind() == elem.getEntryKind()
&& entry.getPath().equals(elem.getPath())) {
IPath attachPath= entry.getSourceAttachmentPath();
if (attachPath != null && !attachPath.isEmpty()) {
elem.setAttribute(CPListElement.SOURCEATTACHMENT, attachPath);
return;
}
}
}
}
}
elem.setAttribute(CPListElement.JAVADOC, JavaUI.getLibraryJavadocLocation(elem.getPath()));
} catch (JavaModelException e) {
JavaPlugin.log(e.getStatus());
}
}
private class AdvancedDialog extends Dialog {
private static final String DIALOGSTORE_ADV_SECTION= "LibrariesWorkbookPage.advanced"; //$NON-NLS-1$
private static final String DIALOGSTORE_SELECTED= "selected"; //$NON-NLS-1$
private static final String DIALOGSTORE_CONTAINER_IDX= "containerindex"; //$NON-NLS-1$
private DialogField fLabelField;
private SelectionButtonDialogField fCreateFolderField;
private SelectionButtonDialogField fAddFolderField;
private SelectionButtonDialogField fAddContainerField;
private ComboDialogField fCombo;
private CPListElement[] fResult;
private IDialogSettings fAdvSettings;
private ClasspathContainerDescriptor[] fDescriptors;
public AdvancedDialog(Shell parent) {
super(parent);
fAdvSettings= fDialogSettings.getSection(DIALOGSTORE_ADV_SECTION);
if (fAdvSettings == null) {
fAdvSettings= fDialogSettings.addNewSection(DIALOGSTORE_ADV_SECTION);
fAdvSettings.put(DIALOGSTORE_SELECTED, 2); // container
fAdvSettings.put(DIALOGSTORE_CONTAINER_IDX, 0);
}
fDescriptors= ClasspathContainerDescriptor.getDescriptors();
fLabelField= new DialogField();
fLabelField.setLabelText(NewWizardMessages.getString("LibrariesWorkbookPage.AdvancedDialog.description")); //$NON-NLS-1$
fCreateFolderField= new SelectionButtonDialogField(SWT.RADIO);
fCreateFolderField.setLabelText(NewWizardMessages.getString("LibrariesWorkbookPage.AdvancedDialog.createfolder")); //$NON-NLS-1$
fAddFolderField= new SelectionButtonDialogField(SWT.RADIO);
fAddFolderField.setLabelText(NewWizardMessages.getString("LibrariesWorkbookPage.AdvancedDialog.addfolder")); //$NON-NLS-1$
fAddContainerField= new SelectionButtonDialogField(SWT.RADIO);
fAddContainerField.setLabelText(NewWizardMessages.getString("LibrariesWorkbookPage.AdvancedDialog.addcontainer")); //$NON-NLS-1$
String[] names= new String[fDescriptors.length];
for (int i = 0; i < names.length; i++) {
names[i]= fDescriptors[i].getName();
}
fCombo= new ComboDialogField(SWT.READ_ONLY);
fCombo.setItems(names);
fAddContainerField.attachDialogField(fCombo);
int selected= fAdvSettings.getInt(DIALOGSTORE_SELECTED);
fCreateFolderField.setSelection(selected == 0);
fAddFolderField.setSelection(selected == 1);
fAddContainerField.setSelection(selected == 2);
fCombo.selectItem(fAdvSettings.getInt(DIALOGSTORE_CONTAINER_IDX));
}
/*
* @see Window#create(Shell)
*/
protected void configureShell(Shell shell) {
super.configureShell(shell);
shell.setText(NewWizardMessages.getString("LibrariesWorkbookPage.AdvancedDialog.title")); //$NON-NLS-1$
WorkbenchHelp.setHelp(shell, IJavaHelpContextIds.LIBRARIES_WORKBOOK_PAGE_ADVANCED_DIALOG);
}
protected Control createDialogArea(Composite parent) {
initializeDialogUnits(parent);
Composite composite= (Composite) super.createDialogArea(parent);
Composite inner= new Composite(composite, SWT.NONE);
GridLayout layout= new GridLayout();
layout.marginHeight= 0;
layout.marginWidth= 0;
inner.setLayout(layout);
fLabelField.doFillIntoGrid(inner, 1);
fCreateFolderField.doFillIntoGrid(inner, 1);
fAddFolderField.doFillIntoGrid(inner, 1);
fAddContainerField.doFillIntoGrid(inner, 1);
Control control= fCombo.getComboControl(inner);
GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalIndent= convertWidthInCharsToPixels(3);
control.setLayoutData(gd);
return composite;
}
/* (non-Javadoc)
* @see Dialog#okPressed()
*/
protected void okPressed() {
fResult= null;
if (fCreateFolderField.isSelected()) {
fResult= openNewClassFolderDialog(null);
fAdvSettings.put(DIALOGSTORE_SELECTED, 0);
} else if (fAddFolderField.isSelected()) {
fResult= openClassFolderDialog(null);
fAdvSettings.put(DIALOGSTORE_SELECTED, 1);
} else if (fAddContainerField.isSelected()) {
String selected= fCombo.getText();
for (int i = 0; i < fDescriptors.length; i++) {
if (fDescriptors[i].getName().equals(selected)) {
String title= NewWizardMessages.getString("LibrariesWorkbookPage.ContainerDialog.new.title"); //$NON-NLS-1$
fResult= openContainerDialog(title, new ClasspathContainerWizard(fDescriptors[i], fCurrJProject, getRawClasspath()));
fAdvSettings.put(DIALOGSTORE_CONTAINER_IDX, i);
break;
}
}
fAdvSettings.put(DIALOGSTORE_SELECTED, 2);
}
if (fResult != null) {
super.okPressed();
}
// stay open
}
public CPListElement[] getResult() {
return fResult;
}
}
private IClasspathEntry[] getRawClasspath() {
IClasspathEntry[] currEntries= new IClasspathEntry[fClassPathList.getSize()];
for (int i= 0; i < currEntries.length; i++) {
CPListElement curr= (CPListElement) fClassPathList.getElement(i);
currEntries[i]= curr.getClasspathEntry();
}
return currEntries;
}
// a dialog to set the source attachment properties
private static class SourceAttachmentDialog extends StatusDialog implements IStatusChangeListener {
private SourceAttachmentBlock fSourceAttachmentBlock;
public SourceAttachmentDialog(Shell parent, IWorkspaceRoot root, CPListElement element) {
super(parent);
setTitle(NewWizardMessages.getFormattedString("LibrariesWorkbookPage.SourceAttachmentDialog.title", element.getPath().toString())); //$NON-NLS-1$
fSourceAttachmentBlock= new SourceAttachmentBlock(root, this, element.getClasspathEntry());
}
/*
* @see Windows#configureShell
*/
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
WorkbenchHelp.setHelp(newShell, IJavaHelpContextIds.SOURCE_ATTACHMENT_DIALOG);
}
protected Control createDialogArea(Composite parent) {
Composite composite= (Composite)super.createDialogArea(parent);
Control inner= fSourceAttachmentBlock.createControl(composite);
inner.setLayoutData(new GridData(GridData.FILL_BOTH));
return composite;
}
public void statusChanged(IStatus status) {
updateStatus(status);
}
public IPath getSourceAttachmentPath() {
return fSourceAttachmentBlock.getSourceAttachmentPath();
}
public IPath getSourceAttachmentRootPath() {
return fSourceAttachmentBlock.getSourceAttachmentRootPath();
}
}
private class JavadocPropertyDialog extends StatusDialog implements IStatusChangeListener {
private JavadocConfigurationBlock fJavadocConfigurationBlock;
private CPListElement fElement;
public JavadocPropertyDialog(Shell parent, CPListElement element) {
super(parent);
setTitle(NewWizardMessages.getFormattedString("LibrariesWorkbookPage.JavadocPropertyDialog.title", element.getPath().toString())); //$NON-NLS-1$
fElement= element;
URL initialLocation= JavaUI.getLibraryJavadocLocation(element.getPath());
fJavadocConfigurationBlock= new JavadocConfigurationBlock(parent, this, initialLocation);
}
protected Control createDialogArea(Composite parent) {
Composite composite= (Composite) super.createDialogArea(parent);
Control inner= fJavadocConfigurationBlock.createContents(composite);
inner.setLayoutData(new GridData(GridData.FILL_BOTH));
return composite;
}
public void statusChanged(IStatus status) {
updateStatus(status);
}
public URL getJavaDocLocation() {
return fJavadocConfigurationBlock.getJavadocLocation();
}
/*
* @see org.eclipse.jface.window.Window#configureShell(Shell)
*/
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
WorkbenchHelp.setHelp(newShell, IJavaHelpContextIds.JAVADOC_PROPERTY_DIALOG);
}
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.wizards.buildpaths.BuildPathBasePage#isEntryKind(int)
*/
public boolean isEntryKind(int kind) {
return kind == IClasspathEntry.CPE_LIBRARY || kind == IClasspathEntry.CPE_VARIABLE || kind == IClasspathEntry.CPE_CONTAINER;
}
/*
* @see BuildPathBasePage#getSelection
*/
public List getSelection() {
return fLibrariesList.getSelectedElements();
}
/*
* @see BuildPathBasePage#setSelection
*/
public void setSelection(List selElements) {
fLibrariesList.selectElements(new StructuredSelection(selElements));
}
}
|
25,845 |
Bug 25845 Support for manually attaching source to a class path container
|
From Dejan: There is a work item on the ability to manually attach source to classpath entries managed by classpath container. We discussed it and we have workable options but we would like if we can have it by M3 because we want to start self-hosting using classpath containers ourselves.
|
resolved fixed
|
3eaf7d8
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-20T17:30:52Z | 2002-11-07T17:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/SourceAttachmentBlock.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.wizards.buildpaths;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.model.WorkbenchContentProvider;
import org.eclipse.ui.model.WorkbenchLabelProvider;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.dialogs.StatusUtil;
import org.eclipse.jdt.internal.ui.util.PixelConverter;
import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener;
import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages;
import org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField;
/**
* UI to set the source attachment archive and root.
* Same implementation for both setting attachments for libraries from
* variable entries and for normal (internal or external) jar.
*/
public class SourceAttachmentBlock {
private IStatusChangeListener fContext;
private StringButtonDialogField fFileNameField;
private SelectionButtonDialogField fInternalButtonField;
private boolean fIsVariableEntry;
private IStatus fNameStatus;
private IPath fJARPath;
/**
* The file to which the archive path points to.
* Only set when the file exists.
*/
private File fResolvedFile;
/**
* The path to which the archive variable points.
* Null if invalid path or not resolvable. Must not exist.
*/
private IPath fFileVariablePath;
private IWorkspaceRoot fRoot;
private Control fSWTWidget;
private CLabel fFullPathResolvedLabel;
private IClasspathEntry fOldEntry;
public SourceAttachmentBlock(IWorkspaceRoot root, IStatusChangeListener context, IClasspathEntry oldEntry) {
fContext= context;
fRoot= root;
fOldEntry= oldEntry;
// fIsVariableEntry specifies if the UI is for a variable entry
fIsVariableEntry= (oldEntry.getEntryKind() == IClasspathEntry.CPE_VARIABLE);
fNameStatus= new StatusInfo();
fJARPath= (oldEntry != null) ? oldEntry.getPath() : Path.EMPTY;
SourceAttachmentAdapter adapter= new SourceAttachmentAdapter();
// create the dialog fields (no widgets yet)
if (fIsVariableEntry) {
fFileNameField= new VariablePathDialogField(adapter);
fFileNameField.setDialogFieldListener(adapter);
fFileNameField.setLabelText(NewWizardMessages.getString("SourceAttachmentBlock.filename.varlabel")); //$NON-NLS-1$
fFileNameField.setButtonLabel(NewWizardMessages.getString("SourceAttachmentBlock.filename.external.varbutton")); //$NON-NLS-1$
((VariablePathDialogField)fFileNameField).setVariableButtonLabel(NewWizardMessages.getString("SourceAttachmentBlock.filename.variable.button")); //$NON-NLS-1$
} else {
fFileNameField= new StringButtonDialogField(adapter);
fFileNameField.setDialogFieldListener(adapter);
fFileNameField.setLabelText(NewWizardMessages.getString("SourceAttachmentBlock.filename.label")); //$NON-NLS-1$
fFileNameField.setButtonLabel(NewWizardMessages.getString("SourceAttachmentBlock.filename.external.button")); //$NON-NLS-1$
fInternalButtonField= new SelectionButtonDialogField(SWT.PUSH);
fInternalButtonField.setDialogFieldListener(adapter);
fInternalButtonField.setLabelText(NewWizardMessages.getString("SourceAttachmentBlock.filename.internal.button")); //$NON-NLS-1$
}
// set the old settings
setDefaults();
}
public void setDefaults() {
if (fOldEntry != null && fOldEntry.getSourceAttachmentPath() != null) {
fFileNameField.setText(fOldEntry.getSourceAttachmentPath().toString());
} else {
fFileNameField.setText(""); //$NON-NLS-1$
}
}
/**
* Gets the source attachment path chosen by the user
*/
public IPath getSourceAttachmentPath() {
if (fFileNameField.getText().length() == 0) {
return null;
}
return new Path(fFileNameField.getText());
}
/**
* Gets the source attachment root chosen by the user
*/
public IPath getSourceAttachmentRootPath() {
return null;
}
/**
* Creates the control
*/
public Control createControl(Composite parent) {
PixelConverter converter= new PixelConverter(parent);
fSWTWidget= parent;
Composite composite= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
layout.marginHeight= 0;
layout.marginWidth= 0;
layout.numColumns= 4;
composite.setLayout(layout);
int widthHint= converter.convertWidthInCharsToPixels(fIsVariableEntry ? 50 : 60);
GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= 4;
Label message= new Label(composite, SWT.LEFT);
message.setLayoutData(gd);
message.setText(NewWizardMessages.getFormattedString("SourceAttachmentBlock.message", fJARPath.lastSegment())); //$NON-NLS-1$
if (fIsVariableEntry) {
DialogField.createEmptySpace(composite, 1);
gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.widthHint= widthHint;
gd.horizontalSpan= 2;
Label desc= new Label(composite, SWT.LEFT + SWT.WRAP);
desc.setText(NewWizardMessages.getString("SourceAttachmentBlock.filename.description")); //$NON-NLS-1$
desc.setLayoutData(gd);
DialogField.createEmptySpace(composite, 1);
}
// archive name field
fFileNameField.doFillIntoGrid(composite, 4);
LayoutUtil.setWidthHint(fFileNameField.getTextControl(null), widthHint);
LayoutUtil.setHorizontalGrabbing(fFileNameField.getTextControl(null));
if (!fIsVariableEntry) {
// aditional 'browse workspace' button for normal jars
DialogField.createEmptySpace(composite, 3);
fInternalButtonField.doFillIntoGrid(composite, 1);
} else {
// label that shows the resolved path for variable jars
DialogField.createEmptySpace(composite, 1);
fFullPathResolvedLabel= new CLabel(composite, SWT.LEFT);
fFullPathResolvedLabel.setText(getResolvedLabelString(fFileNameField.getText(), true));
fFullPathResolvedLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
DialogField.createEmptySpace(composite, 2);
}
fFileNameField.postSetFocusOnDialogField(parent.getDisplay());
WorkbenchHelp.setHelp(composite, IJavaHelpContextIds.SOURCE_ATTACHMENT_BLOCK);
return composite;
}
private class SourceAttachmentAdapter implements IStringButtonAdapter, IDialogFieldListener {
// -------- IStringButtonAdapter --------
public void changeControlPressed(DialogField field) {
attachmentChangeControlPressed(field);
}
// ---------- IDialogFieldListener --------
public void dialogFieldChanged(DialogField field) {
attachmentDialogFieldChanged(field);
}
}
private void attachmentChangeControlPressed(DialogField field) {
if (field == fFileNameField) {
IPath jarFilePath= chooseExtJarFile();
if (jarFilePath != null) {
fFileNameField.setText(jarFilePath.toString());
}
}
}
// ---------- IDialogFieldListener --------
private void attachmentDialogFieldChanged(DialogField field) {
if (field == fFileNameField) {
fNameStatus= updateFileNameStatus();
} else if (field == fInternalButtonField) {
IPath jarFilePath= chooseInternalJarFile();
if (jarFilePath != null) {
fFileNameField.setText(jarFilePath.toString());
}
return;
}
doStatusLineUpdate();
}
private void doStatusLineUpdate() {
fFileNameField.enableButton(canBrowseFileName());
// set the resolved path for variable jars
if (fFullPathResolvedLabel != null) {
fFullPathResolvedLabel.setText(getResolvedLabelString(fFileNameField.getText(), true));
}
IStatus status= StatusUtil.getMostSevere(new IStatus[] { fNameStatus });
fContext.statusChanged(status);
}
private boolean canBrowseFileName() {
if (!fIsVariableEntry) {
return true;
}
// to browse with a variable JAR, the variable name must point to a directory
if (fFileVariablePath != null) {
return fFileVariablePath.toFile().isDirectory();
}
return false;
}
private String getResolvedLabelString(String path, boolean osPath) {
IPath resolvedPath= getResolvedPath(new Path(path));
if (resolvedPath != null) {
if (osPath) {
return resolvedPath.toOSString();
} else {
return resolvedPath.toString();
}
}
return ""; //$NON-NLS-1$
}
private IPath getResolvedPath(IPath path) {
if (path != null) {
String varName= path.segment(0);
if (varName != null) {
IPath varPath= JavaCore.getClasspathVariable(varName);
if (varPath != null) {
return varPath.append(path.removeFirstSegments(1));
}
}
}
return null;
}
private IStatus updateFileNameStatus() {
StatusInfo status= new StatusInfo();
fResolvedFile= null;
fFileVariablePath= null;
String fileName= fFileNameField.getText();
if (fileName.length() == 0) {
// no source attachment
return status;
} else {
if (!Path.EMPTY.isValidPath(fileName)) {
status.setError(NewWizardMessages.getString("SourceAttachmentBlock.filename.error.notvalid")); //$NON-NLS-1$
return status;
}
IPath filePath= new Path(fileName);
IPath resolvedPath;
if (fIsVariableEntry) {
if (filePath.getDevice() != null) {
status.setError(NewWizardMessages.getString("SourceAttachmentBlock.filename.error.deviceinpath")); //$NON-NLS-1$
return status;
}
String varName= filePath.segment(0);
if (varName == null) {
status.setError(NewWizardMessages.getString("SourceAttachmentBlock.filename.error.notvalid")); //$NON-NLS-1$
return status;
}
fFileVariablePath= JavaCore.getClasspathVariable(varName);
if (fFileVariablePath == null) {
status.setError(NewWizardMessages.getString("SourceAttachmentBlock.filename.error.varnotexists")); //$NON-NLS-1$
return status;
}
resolvedPath= fFileVariablePath.append(filePath.removeFirstSegments(1));
if (resolvedPath.isEmpty()) {
status.setWarning(NewWizardMessages.getString("SourceAttachmentBlock.filename.warning.varempty")); //$NON-NLS-1$
return status;
}
File file= resolvedPath.toFile();
if (!file.exists()) {
String message= NewWizardMessages.getFormattedString("SourceAttachmentBlock.filename.error.filenotexists", resolvedPath.toOSString()); //$NON-NLS-1$
status.setWarning(message);
return status;
}
fResolvedFile= file;
} else {
File file= filePath.toFile();
IResource res= fRoot.findMember(filePath);
if (res != null) {
file= res.getLocation().toFile();
}
if (!file.exists()) {
String message= NewWizardMessages.getFormattedString("SourceAttachmentBlock.filename.error.filenotexists", filePath.toString()); //$NON-NLS-1$
status.setError(message);
return status;
}
fResolvedFile= file;
}
}
return status;
}
/*
* Opens a dialog to choose a jar from the file system.
*/
private IPath chooseExtJarFile() {
IPath currPath= new Path(fFileNameField.getText());
if (currPath.isEmpty()) {
currPath= fJARPath;
}
if (fIsVariableEntry) {
IPath resolvedPath= getResolvedPath(currPath);
File initialSelection= resolvedPath != null ? resolvedPath.toFile() : null;
String currVariable= currPath.segment(0);
JARFileSelectionDialog dialog= new JARFileSelectionDialog(getShell(), false, true);
dialog.setTitle(NewWizardMessages.getString("SourceAttachmentBlock.extvardialog.title")); //$NON-NLS-1$
dialog.setMessage(NewWizardMessages.getString("SourceAttachmentBlock.extvardialog.description")); //$NON-NLS-1$
dialog.setInput(fFileVariablePath.toFile());
dialog.setInitialSelection(initialSelection);
if (dialog.open() == JARFileSelectionDialog.OK) {
File result= (File) dialog.getResult()[0];
IPath returnPath= new Path(result.getPath()).makeAbsolute();
return modifyPath(returnPath, currVariable);
}
} else {
if (ArchiveFileFilter.isArchivePath(currPath)) {
currPath= currPath.removeLastSegments(1);
}
FileDialog dialog= new FileDialog(getShell());
dialog.setText(NewWizardMessages.getString("SourceAttachmentBlock.extjardialog.text")); //$NON-NLS-1$
dialog.setFilterExtensions(new String[] {"*.jar;*.zip"}); //$NON-NLS-1$
dialog.setFilterPath(currPath.toOSString());
String res= dialog.open();
if (res != null) {
return new Path(res).makeAbsolute();
}
}
return null;
}
/*
* Opens a dialog to choose an internal jar.
*/
private IPath chooseInternalJarFile() {
String initSelection= fFileNameField.getText();
Class[] acceptedClasses= new Class[] { IFolder.class, IFile.class };
TypedElementSelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, false);
ViewerFilter filter= new ArchiveFileFilter(null, false);
ILabelProvider lp= new WorkbenchLabelProvider();
ITreeContentProvider cp= new WorkbenchContentProvider();
IResource initSel= null;
if (initSelection.length() > 0) {
initSel= fRoot.findMember(new Path(initSelection));
}
if (initSel == null) {
initSel= fRoot.findMember(fJARPath);
}
FolderSelectionDialog dialog= new FolderSelectionDialog(getShell(), lp, cp);
dialog.setAllowMultiple(false);
dialog.setValidator(validator);
dialog.addFilter(filter);
dialog.setTitle(NewWizardMessages.getString("SourceAttachmentBlock.intjardialog.title")); //$NON-NLS-1$
dialog.setMessage(NewWizardMessages.getString("SourceAttachmentBlock.intjardialog.message")); //$NON-NLS-1$
dialog.setInput(fRoot);
dialog.setInitialSelection(initSel);
if (dialog.open() == ElementTreeSelectionDialog.OK) {
IResource res= (IResource) dialog.getFirstResult();
return res.getFullPath();
}
return null;
}
private Shell getShell() {
if (fSWTWidget != null) {
return fSWTWidget.getShell();
}
return JavaPlugin.getActiveWorkbenchShell();
}
/**
* Takes a path and replaces the beginning with a variable name
* (if the beginning matches with the variables value)
*/
private IPath modifyPath(IPath path, String varName) {
if (varName == null || path == null) {
return null;
}
if (path.isEmpty()) {
return new Path(varName);
}
IPath varPath= JavaCore.getClasspathVariable(varName);
if (varPath != null) {
if (varPath.isPrefixOf(path)) {
path= path.removeFirstSegments(varPath.segmentCount());
} else {
path= new Path(path.lastSegment());
}
} else {
path= new Path(path.lastSegment());
}
return new Path(varName).append(path);
}
/**
* Creates a runnable that sets the source attachment by modifying the project's classpath.
*/
public IRunnableWithProgress getRunnable(final IJavaProject jproject, final Shell shell) {
return new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException {
try {
boolean isExported= fOldEntry != null ? fOldEntry.isExported() : false;
IClasspathEntry newEntry;
if (fIsVariableEntry) {
newEntry= JavaCore.newVariableEntry(fJARPath, getSourceAttachmentPath(), getSourceAttachmentRootPath(), isExported);
} else {
newEntry= JavaCore.newLibraryEntry(fJARPath, getSourceAttachmentPath(), getSourceAttachmentRootPath(), isExported);
}
IClasspathEntry[] entries= modifyClasspath(jproject, newEntry, shell);
if (entries != null) {
jproject.setRawClasspath(entries, monitor);
}
} catch (JavaModelException e) {
throw new InvocationTargetException(e);
}
}
};
}
private IClasspathEntry[] modifyClasspath(IJavaProject jproject, IClasspathEntry newEntry, Shell shell) throws JavaModelException{
IClasspathEntry[] oldClasspath= jproject.getRawClasspath();
int nEntries= oldClasspath.length;
ArrayList newEntries= new ArrayList(nEntries + 1);
int entryKind= newEntry.getEntryKind();
IPath jarPath= newEntry.getPath();
boolean found= false;
for (int i= 0; i < nEntries; i++) {
IClasspathEntry curr= oldClasspath[i];
if (curr.getEntryKind() == entryKind && curr.getPath().equals(jarPath)) {
// add modified entry
newEntries.add(newEntry);
found= true;
} else {
newEntries.add(curr);
}
}
if (!found) {
if (newEntry.getSourceAttachmentPath() == null || !putJarOnClasspathDialog(shell)) {
return null;
}
// add new
newEntries.add(newEntry);
}
return (IClasspathEntry[]) newEntries.toArray(new IClasspathEntry[newEntries.size()]);
}
private boolean putJarOnClasspathDialog(Shell shell) {
final boolean[] result= new boolean[1];
shell.getDisplay().syncExec(new Runnable() {
public void run() {
String title= NewWizardMessages.getString("SourceAttachmentBlock.putoncpdialog.title"); //$NON-NLS-1$
String message= NewWizardMessages.getString("SourceAttachmentBlock.putoncpdialog.message"); //$NON-NLS-1$
result[0]= MessageDialog.openQuestion(JavaPlugin.getActiveWorkbenchShell(), title, message);
}
});
return result[0];
}
}
|
25,845 |
Bug 25845 Support for manually attaching source to a class path container
|
From Dejan: There is a work item on the ability to manually attach source to classpath entries managed by classpath container. We discussed it and we have workable options but we would like if we can have it by M3 because we want to start self-hosting using classpath containers ourselves.
|
resolved fixed
|
3eaf7d8
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-20T17:30:52Z | 2002-11-07T17:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/SourceAttachmentDialog.java
| |
26,927 |
Bug 26927 JavaDoc generation is hard to find [javadoc]
|
Feedback on the mailing list and questions on the newsgroup indicate that the javadoc support is difficult to find. Proposal: Add a Generate Java Doc action to the Project menu. (we should also investigate whether we want to surface other actions in the Project menu, e.g. open the "Properties")
|
resolved fixed
|
7f099a8
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-20T18:00:55Z | 2002-11-22T10:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/actions/GenerateJavadocAction.java
| |
28,510 |
Bug 28510 java build path inconsistency [build path]
|
20021216 select rt.jar in the package explorer open properties it allows you to set the javadoc location but for source attachment you are sent somewhere else it's inconsistent - on the java build path they both look sort of the same (they sit under the same node in the tree)
|
resolved fixed
|
bcd21c9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-20T18:15:37Z | 2002-12-17T15:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/BuildPathsBlock.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.wizards.buildpaths;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.dialogs.ISelectionStatusValidator;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.model.WorkbenchContentProvider;
import org.eclipse.ui.model.WorkbenchLabelProvider;
import org.eclipse.ui.views.navigator.ResourceSorter;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaModelStatus;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaConventions;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.dialogs.StatusUtil;
import org.eclipse.jdt.internal.ui.util.CoreUtility;
import org.eclipse.jdt.internal.ui.util.PixelConverter;
import org.eclipse.jdt.internal.ui.util.TabFolderLayout;
import org.eclipse.jdt.internal.ui.viewsupport.ImageDisposer;
import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener;
import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages;
import org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator;
import org.eclipse.jdt.internal.ui.wizards.TypedViewerFilter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.CheckedListDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField;
public class BuildPathsBlock {
public static interface IRemoveOldBinariesQuery {
/**
* Do the callback. Returns <code>true</code> if .class files should be removed from the
* old output location.
*/
boolean doQuery(IPath oldOutputLocation) throws InterruptedException;
}
private IWorkspaceRoot fWorkspaceRoot;
private CheckedListDialogField fClassPathList;
private StringButtonDialogField fBuildPathDialogField;
private StatusInfo fClassPathStatus;
private StatusInfo fOutputFolderStatus;
private StatusInfo fBuildPathStatus;
private IJavaProject fCurrJProject;
private IPath fOutputLocationPath;
private IStatusChangeListener fContext;
private Control fSWTWidget;
private int fPageIndex;
private SourceContainerWorkbookPage fSourceContainerPage;
private ProjectsWorkbookPage fProjectsPage;
private LibrariesWorkbookPage fLibrariesPage;
private BuildPathBasePage fCurrPage;
public BuildPathsBlock(IStatusChangeListener context, int pageToShow) {
fWorkspaceRoot= JavaPlugin.getWorkspace().getRoot();
fContext= context;
fPageIndex= pageToShow;
fSourceContainerPage= null;
fLibrariesPage= null;
fProjectsPage= null;
fCurrPage= null;
BuildPathAdapter adapter= new BuildPathAdapter();
String[] buttonLabels= new String[] {
/* 0 */ NewWizardMessages.getString("BuildPathsBlock.classpath.up.button"), //$NON-NLS-1$
/* 1 */ NewWizardMessages.getString("BuildPathsBlock.classpath.down.button"), //$NON-NLS-1$
/* 2 */ null,
/* 3 */ NewWizardMessages.getString("BuildPathsBlock.classpath.checkall.button"), //$NON-NLS-1$
/* 4 */ NewWizardMessages.getString("BuildPathsBlock.classpath.uncheckall.button") //$NON-NLS-1$
};
fClassPathList= new CheckedListDialogField(null, buttonLabels, new CPListLabelProvider());
fClassPathList.setDialogFieldListener(adapter);
fClassPathList.setLabelText(NewWizardMessages.getString("BuildPathsBlock.classpath.label")); //$NON-NLS-1$
fClassPathList.setUpButtonIndex(0);
fClassPathList.setDownButtonIndex(1);
fClassPathList.setCheckAllButtonIndex(3);
fClassPathList.setUncheckAllButtonIndex(4);
fBuildPathDialogField= new StringButtonDialogField(adapter);
fBuildPathDialogField.setButtonLabel(NewWizardMessages.getString("BuildPathsBlock.buildpath.button")); //$NON-NLS-1$
fBuildPathDialogField.setDialogFieldListener(adapter);
fBuildPathDialogField.setLabelText(NewWizardMessages.getString("BuildPathsBlock.buildpath.label")); //$NON-NLS-1$
fBuildPathStatus= new StatusInfo();
fClassPathStatus= new StatusInfo();
fOutputFolderStatus= new StatusInfo();
fCurrJProject= null;
}
// -------- UI creation ---------
public Control createControl(Composite parent) {
fSWTWidget= parent;
PixelConverter converter= new PixelConverter(parent);
Composite composite= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
layout.marginWidth= 0;
layout.numColumns= 1;
composite.setLayout(layout);
TabFolder folder= new TabFolder(composite, SWT.NONE);
folder.setLayout(new TabFolderLayout());
folder.setLayoutData(new GridData(GridData.FILL_BOTH));
ImageRegistry imageRegistry= JavaPlugin.getDefault().getImageRegistry();
TabItem item;
fSourceContainerPage= new SourceContainerWorkbookPage(fWorkspaceRoot, fClassPathList, fBuildPathDialogField);
item= new TabItem(folder, SWT.NONE);
item.setText(NewWizardMessages.getString("BuildPathsBlock.tab.source")); //$NON-NLS-1$
item.setImage(imageRegistry.get(JavaPluginImages.IMG_OBJS_PACKFRAG_ROOT));
item.setData(fSourceContainerPage);
item.setControl(fSourceContainerPage.getControl(folder));
IWorkbench workbench= JavaPlugin.getDefault().getWorkbench();
Image projectImage= workbench.getSharedImages().getImage(ISharedImages.IMG_OBJ_PROJECT);
fProjectsPage= new ProjectsWorkbookPage(fClassPathList);
item= new TabItem(folder, SWT.NONE);
item.setText(NewWizardMessages.getString("BuildPathsBlock.tab.projects")); //$NON-NLS-1$
item.setImage(projectImage);
item.setData(fProjectsPage);
item.setControl(fProjectsPage.getControl(folder));
fLibrariesPage= new LibrariesWorkbookPage(fWorkspaceRoot, fClassPathList);
item= new TabItem(folder, SWT.NONE);
item.setText(NewWizardMessages.getString("BuildPathsBlock.tab.libraries")); //$NON-NLS-1$
item.setImage(imageRegistry.get(JavaPluginImages.IMG_OBJS_LIBRARY));
item.setData(fLibrariesPage);
item.setControl(fLibrariesPage.getControl(folder));
// a non shared image
Image cpoImage= JavaPluginImages.DESC_TOOL_CLASSPATH_ORDER.createImage();
composite.addDisposeListener(new ImageDisposer(cpoImage));
ClasspathOrderingWorkbookPage ordpage= new ClasspathOrderingWorkbookPage(fClassPathList);
item= new TabItem(folder, SWT.NONE);
item.setText(NewWizardMessages.getString("BuildPathsBlock.tab.order")); //$NON-NLS-1$
item.setImage(cpoImage);
item.setData(ordpage);
item.setControl(ordpage.getControl(folder));
if (fCurrJProject != null) {
fSourceContainerPage.init(fCurrJProject);
fLibrariesPage.init(fCurrJProject);
fProjectsPage.init(fCurrJProject);
}
Composite editorcomp= new Composite(composite, SWT.NONE);
DialogField[] editors= new DialogField[] { fBuildPathDialogField };
LayoutUtil.doDefaultLayout(editorcomp, editors, true, 0, 0);
int maxFieldWidth= converter.convertWidthInCharsToPixels(40);
LayoutUtil.setWidthHint(fBuildPathDialogField.getTextControl(null), maxFieldWidth);
LayoutUtil.setHorizontalGrabbing(fBuildPathDialogField.getTextControl(null));
editorcomp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
folder.setSelection(fPageIndex);
fCurrPage= (BuildPathBasePage) folder.getItem(fPageIndex).getData();
folder.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
tabChanged(e.item);
}
});
WorkbenchHelp.setHelp(composite, IJavaHelpContextIds.BUILD_PATH_BLOCK);
return composite;
}
private Shell getShell() {
if (fSWTWidget != null) {
return fSWTWidget.getShell();
}
return JavaPlugin.getActiveWorkbenchShell();
}
/**
* Initializes the classpath for the given project. Multiple calls to init are allowed,
* but all existing settings will be cleared and replace by the given or default paths.
* @param project The java project to configure. Does not have to exist.
* @param outputLocation The output location to be set in the page. If <code>null</code>
* is passed, jdt default settings are used, or - if the project is an existing Java project- the
* output location of the existing project
* @param classpathEntries The classpath entries to be set in the page. If <code>null</code>
* is passed, jdt default settings are used, or - if the project is an existing Java project - the
* classpath entries of the existing project
*/
public void init(IJavaProject jproject, IPath outputLocation, IClasspathEntry[] classpathEntries) {
fCurrJProject= jproject;
boolean projectExists= false;
List newClassPath= null;
try {
IProject project= fCurrJProject.getProject();
projectExists= (project.exists() && project.getFile(".classpath").exists()); //$NON-NLS-1$
if (projectExists) {
if (outputLocation == null) {
outputLocation= fCurrJProject.getOutputLocation();
}
if (classpathEntries == null) {
classpathEntries= fCurrJProject.getRawClasspath();
}
}
if (outputLocation == null) {
outputLocation= getDefaultBuildPath(jproject);
}
if (classpathEntries != null) {
newClassPath= getExistingEntries(classpathEntries);
}
} catch (CoreException e) {
JavaPlugin.log(e);
}
if (newClassPath == null) {
newClassPath= getDefaultClassPath(jproject);
}
List exportedEntries = new ArrayList();
for (int i= 0; i < newClassPath.size(); i++) {
CPListElement curr= (CPListElement) newClassPath.get(i);
if (curr.isExported() || curr.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
exportedEntries.add(curr);
}
}
// inits the dialog field
fBuildPathDialogField.setText(outputLocation.makeRelative().toString());
fBuildPathDialogField.enableButton(fCurrJProject.exists());
fClassPathList.setElements(newClassPath);
fClassPathList.setCheckedElements(exportedEntries);
if (fSourceContainerPage != null) {
fSourceContainerPage.init(fCurrJProject);
fProjectsPage.init(fCurrJProject);
fLibrariesPage.init(fCurrJProject);
}
doStatusLineUpdate();
}
private ArrayList getExistingEntries(IClasspathEntry[] classpathEntries) {
ArrayList newClassPath= new ArrayList();
for (int i= 0; i < classpathEntries.length; i++) {
IClasspathEntry curr= classpathEntries[i];
newClassPath.add(CPListElement.createFromExisting(curr, fCurrJProject));
}
return newClassPath;
}
// -------- public api --------
/**
* Returns the Java project. Can return <code>null<code> if the page has not
* been initialized.
*/
public IJavaProject getJavaProject() {
return fCurrJProject;
}
/**
* Returns the current output location. Note that the path returned must not be valid.
*/
public IPath getOutputLocation() {
return new Path(fBuildPathDialogField.getText()).makeAbsolute();
}
/**
* Returns the current class path (raw). Note that the entries returned must not be valid.
*/
public IClasspathEntry[] getRawClassPath() {
List elements= fClassPathList.getElements();
int nElements= elements.size();
IClasspathEntry[] entries= new IClasspathEntry[elements.size()];
for (int i= 0; i < nElements; i++) {
CPListElement currElement= (CPListElement) elements.get(i);
entries[i]= currElement.getClasspathEntry();
}
return entries;
}
public int getPageIndex() {
return fPageIndex;
}
// -------- evaluate default settings --------
private List getDefaultClassPath(IJavaProject jproj) {
List list= new ArrayList();
IResource srcFolder;
IPreferenceStore store= PreferenceConstants.getPreferenceStore();
String sourceFolderName= store.getString(PreferenceConstants.SRCBIN_SRCNAME);
if (store.getBoolean(PreferenceConstants.SRCBIN_FOLDERS_IN_NEWPROJ) && sourceFolderName.length() > 0) {
srcFolder= jproj.getProject().getFolder(sourceFolderName);
} else {
srcFolder= jproj.getProject();
}
list.add(new CPListElement(jproj, IClasspathEntry.CPE_SOURCE, srcFolder.getFullPath(), srcFolder));
IClasspathEntry[] jreEntries= PreferenceConstants.getDefaultJRELibrary();
list.addAll(getExistingEntries(jreEntries));
return list;
}
private IPath getDefaultBuildPath(IJavaProject jproj) {
IPreferenceStore store= PreferenceConstants.getPreferenceStore();
if (store.getBoolean(PreferenceConstants.SRCBIN_FOLDERS_IN_NEWPROJ)) {
String outputLocationName= store.getString(PreferenceConstants.SRCBIN_BINNAME);
return jproj.getProject().getFullPath().append(outputLocationName);
} else {
return jproj.getProject().getFullPath();
}
}
private class BuildPathAdapter implements IStringButtonAdapter, IDialogFieldListener {
// -------- IStringButtonAdapter --------
public void changeControlPressed(DialogField field) {
buildPathChangeControlPressed(field);
}
// ---------- IDialogFieldListener --------
public void dialogFieldChanged(DialogField field) {
buildPathDialogFieldChanged(field);
}
}
private void buildPathChangeControlPressed(DialogField field) {
if (field == fBuildPathDialogField) {
IContainer container= chooseContainer();
if (container != null) {
fBuildPathDialogField.setText(container.getFullPath().toString());
}
}
}
private void buildPathDialogFieldChanged(DialogField field) {
if (field == fClassPathList) {
updateClassPathStatus();
} else if (field == fBuildPathDialogField) {
updateOutputLocationStatus();
}
doStatusLineUpdate();
}
// -------- verification -------------------------------
private void doStatusLineUpdate() {
IStatus res= findMostSevereStatus();
fContext.statusChanged(res);
}
private IStatus findMostSevereStatus() {
return StatusUtil.getMostSevere(new IStatus[] { fClassPathStatus, fOutputFolderStatus, fBuildPathStatus });
}
/**
* Validates the build path.
*/
public void updateClassPathStatus() {
fClassPathStatus.setOK();
List elements= fClassPathList.getElements();
CPListElement entryMissing= null;
int nEntriesMissing= 0;
IClasspathEntry[] entries= new IClasspathEntry[elements.size()];
for (int i= elements.size()-1 ; i >= 0 ; i--) {
CPListElement currElement= (CPListElement)elements.get(i);
boolean isChecked= fClassPathList.isChecked(currElement);
if (currElement.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
if (!isChecked) {
fClassPathList.setCheckedWithoutUpdate(currElement, true);
}
} else {
currElement.setExported(isChecked);
}
entries[i]= currElement.getClasspathEntry();
if (currElement.isMissing()) {
nEntriesMissing++;
if (entryMissing == null) {
entryMissing= currElement;
}
}
}
if (nEntriesMissing > 0) {
if (nEntriesMissing == 1) {
fClassPathStatus.setWarning(NewWizardMessages.getFormattedString("BuildPathsBlock.warning.EntryMissing", entryMissing.getPath().toString())); //$NON-NLS-1$
} else {
fClassPathStatus.setWarning(NewWizardMessages.getFormattedString("BuildPathsBlock.warning.EntriesMissing", String.valueOf(nEntriesMissing))); //$NON-NLS-1$
}
}
/* if (fCurrJProject.hasClasspathCycle(entries)) {
fClassPathStatus.setWarning(NewWizardMessages.getString("BuildPathsBlock.warning.CycleInClassPath")); //$NON-NLS-1$
}
*/
updateBuildPathStatus();
}
/**
* Validates output location & build path.
*/
private void updateOutputLocationStatus() {
fOutputLocationPath= null;
String text= fBuildPathDialogField.getText();
if ("".equals(text)) { //$NON-NLS-1$
fOutputFolderStatus.setError(NewWizardMessages.getString("BuildPathsBlock.error.EnterBuildPath")); //$NON-NLS-1$
return;
}
IPath path= getOutputLocation();
fOutputLocationPath= path;
IResource res= fWorkspaceRoot.findMember(path);
if (res != null) {
// if exists, must be a folder or project
if (res.getType() == IResource.FILE) {
fOutputFolderStatus.setError(NewWizardMessages.getString("BuildPathsBlock.error.InvalidBuildPath")); //$NON-NLS-1$
return;
}
}
fOutputFolderStatus.setOK();
updateBuildPathStatus();
}
private void updateBuildPathStatus() {
List elements= fClassPathList.getElements();
IClasspathEntry[] entries= new IClasspathEntry[elements.size()];
for (int i= elements.size()-1 ; i >= 0 ; i--) {
CPListElement currElement= (CPListElement)elements.get(i);
entries[i]= currElement.getClasspathEntry();
}
IJavaModelStatus status= JavaConventions.validateClasspath(fCurrJProject, entries, fOutputLocationPath);
if (!status.isOK()) {
fBuildPathStatus.setError(status.getMessage());
return;
}
fBuildPathStatus.setOK();
}
// -------- creation -------------------------------
public static void createProject(IProject project, IPath locationPath, IProgressMonitor monitor) throws CoreException {
if (monitor == null) {
monitor= new NullProgressMonitor();
}
monitor.beginTask(NewWizardMessages.getString("BuildPathsBlock.operationdesc_project"), 10); //$NON-NLS-1$
// create the project
try {
if (!project.exists()) {
IProjectDescription desc= project.getWorkspace().newProjectDescription(project.getName());
if (Platform.getLocation().equals(locationPath)) {
locationPath= null;
}
desc.setLocation(locationPath);
project.create(desc, monitor);
monitor= null;
}
if (!project.isOpen()) {
project.open(monitor);
monitor= null;
}
} finally {
if (monitor != null) {
monitor.done();
}
}
}
public static void addJavaNature(IProject project, IProgressMonitor monitor) throws CoreException {
if (!project.hasNature(JavaCore.NATURE_ID)) {
IProjectDescription description = project.getDescription();
String[] prevNatures= description.getNatureIds();
String[] newNatures= new String[prevNatures.length + 1];
System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length);
newNatures[prevNatures.length]= JavaCore.NATURE_ID;
description.setNatureIds(newNatures);
project.setDescription(description, monitor);
} else {
monitor.worked(1);
}
}
public void configureJavaProject(IProgressMonitor monitor) throws CoreException, InterruptedException {
if (monitor == null) {
monitor= new NullProgressMonitor();
}
monitor.beginTask(NewWizardMessages.getString("BuildPathsBlock.operationdesc_java"), 10); //$NON-NLS-1$
try {
Shell shell= null;
if (fSWTWidget != null && !fSWTWidget.getShell().isDisposed()) {
shell= fSWTWidget.getShell();
}
internalConfigureJavaProject(fClassPathList.getElements(), getOutputLocation(), shell, monitor);
} finally {
monitor.done();
}
}
/**
* Creates the Java project and sets the configured build path and output location.
* If the project already exists only build paths are updated.
*/
private void internalConfigureJavaProject(List classPathEntries, IPath outputLocation, Shell shell, IProgressMonitor monitor) throws CoreException, InterruptedException {
// 10 monitor steps to go
IRemoveOldBinariesQuery reorgQuery= null;
if (shell != null) {
reorgQuery= getRemoveOldBinariesQuery(shell);
}
// remove old .class files
if (reorgQuery != null) {
IPath oldOutputLocation= fCurrJProject.getOutputLocation();
if (!outputLocation.equals(oldOutputLocation)) {
IResource res= fWorkspaceRoot.findMember(oldOutputLocation);
if (res instanceof IContainer && hasClassfiles(res)) {
if (reorgQuery.doQuery(oldOutputLocation)) {
removeOldClassfiles(res);
}
}
}
}
// create and set the output path first
if (!fWorkspaceRoot.exists(outputLocation)) {
IFolder folder= fWorkspaceRoot.getFolder(outputLocation);
CoreUtility.createFolder(folder, true, true, null);
}
monitor.worked(2);
int nEntries= classPathEntries.size();
IClasspathEntry[] classpath= new IClasspathEntry[nEntries];
// create and set the class path
for (int i= 0; i < nEntries; i++) {
CPListElement entry= ((CPListElement)classPathEntries.get(i));
IResource res= entry.getResource();
if ((res instanceof IFolder) && !res.exists()) {
CoreUtility.createFolder((IFolder)res, true, true, null);
}
if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
IPath folderOutput= (IPath) entry.getAttribute(CPListElement.OUTPUT);
if (folderOutput != null && folderOutput.segmentCount() > 1) {
IFolder folder= fWorkspaceRoot.getFolder(folderOutput);
CoreUtility.createFolder((IFolder)folder, true, true, null);
}
}
classpath[i]= entry.getClasspathEntry();
// set javadoc location
URL javadocLocation= (URL) entry.getAttribute(CPListElement.JAVADOC);
IPath path= entry.getPath();
if (entry.getEntryKind() == IClasspathEntry.CPE_VARIABLE) {
path= JavaCore.getResolvedVariablePath(path);
}
if (path != null) {
JavaUI.setLibraryJavadocLocation(path, javadocLocation);
}
}
monitor.worked(1);
fCurrJProject.setRawClasspath(classpath, outputLocation, new SubProgressMonitor(monitor, 7));
}
public static boolean hasClassfiles(IResource resource) throws CoreException {
if (resource.isDerived()) { //$NON-NLS-1$
return true;
}
if (resource instanceof IContainer) {
IResource[] members= ((IContainer) resource).members();
for (int i= 0; i < members.length; i++) {
if (hasClassfiles(members[i])) {
return true;
}
}
}
return false;
}
public static void removeOldClassfiles(IResource resource) throws CoreException {
if (resource.isDerived()) {
resource.delete(false, null);
} else if (resource instanceof IContainer) {
IResource[] members= ((IContainer) resource).members();
for (int i= 0; i < members.length; i++) {
removeOldClassfiles(members[i]);
}
}
}
public static IRemoveOldBinariesQuery getRemoveOldBinariesQuery(final Shell shell) {
return new IRemoveOldBinariesQuery() {
public boolean doQuery(final IPath oldOutputLocation) throws InterruptedException {
final int[] res= new int[] { 1 };
shell.getDisplay().syncExec(new Runnable() {
public void run() {
String title= NewWizardMessages.getString("BuildPathsBlock.RemoveBinariesDialog.title"); //$NON-NLS-1$
String message= NewWizardMessages.getFormattedString("BuildPathsBlock.RemoveBinariesDialog.description", oldOutputLocation.toString()); //$NON-NLS-1$
MessageDialog dialog= new MessageDialog(shell, title, null, message, MessageDialog.QUESTION, new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL }, 2);
res[0]= dialog.open();
}
});
if (res[0] == 0) {
return true;
} else if (res[0] == 1) {
return false;
}
throw new InterruptedException();
}
};
}
// ---------- util method ------------
private IContainer chooseContainer() {
Class[] acceptedClasses= new Class[] { IProject.class, IFolder.class };
ISelectionStatusValidator validator= new TypedElementSelectionValidator(acceptedClasses, false);
IProject[] allProjects= fWorkspaceRoot.getProjects();
ArrayList rejectedElements= new ArrayList(allProjects.length);
IProject currProject= fCurrJProject.getProject();
for (int i= 0; i < allProjects.length; i++) {
if (!allProjects[i].equals(currProject)) {
rejectedElements.add(allProjects[i]);
}
}
ViewerFilter filter= new TypedViewerFilter(acceptedClasses, rejectedElements.toArray());
ILabelProvider lp= new WorkbenchLabelProvider();
ITreeContentProvider cp= new WorkbenchContentProvider();
IResource initSelection= null;
if (fOutputLocationPath != null) {
initSelection= fWorkspaceRoot.findMember(fOutputLocationPath);
}
FolderSelectionDialog dialog= new FolderSelectionDialog(getShell(), lp, cp);
dialog.setTitle(NewWizardMessages.getString("BuildPathsBlock.ChooseOutputFolderDialog.title")); //$NON-NLS-1$
dialog.setValidator(validator);
dialog.setMessage(NewWizardMessages.getString("BuildPathsBlock.ChooseOutputFolderDialog.description")); //$NON-NLS-1$
dialog.addFilter(filter);
dialog.setInput(fWorkspaceRoot);
dialog.setInitialSelection(initSelection);
dialog.setSorter(new ResourceSorter(ResourceSorter.NAME));
if (dialog.open() == FolderSelectionDialog.OK) {
return (IContainer)dialog.getFirstResult();
}
return null;
}
// -------- tab switching ----------
private void tabChanged(Widget widget) {
if (widget instanceof TabItem) {
TabItem tabItem= (TabItem) widget;
BuildPathBasePage newPage= (BuildPathBasePage) tabItem.getData();
if (fCurrPage != null) {
List selection= fCurrPage.getSelection();
if (!selection.isEmpty()) {
newPage.setSelection(selection);
}
}
fCurrPage= newPage;
fPageIndex= tabItem.getParent().getSelectionIndex();
}
}
}
|
28,510 |
Bug 28510 java build path inconsistency [build path]
|
20021216 select rt.jar in the package explorer open properties it allows you to set the javadoc location but for source attachment you are sent somewhere else it's inconsistent - on the java build path they both look sort of the same (they sit under the same node in the tree)
|
resolved fixed
|
bcd21c9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-20T18:15:37Z | 2002-12-17T15:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/CPListElement.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.wizards.buildpaths;
import java.net.URL;
import java.util.HashMap;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.IClasspathContainer;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.JavaUI;
public class CPListElement {
public static final String SOURCEATTACHMENT= "sourcepath";
public static final String SOURCEATTACHMENTROOT= "rootpath";
public static final String JAVADOC= "javadoc";
public static final String OUTPUT= "output";
public static final String EXCLUSION= "exclusion";
private IJavaProject fProject;
private int fEntryKind;
private IPath fPath;
private IResource fResource;
private boolean fIsExported;
private boolean fIsMissing;
private CPListElement fParentContainer;
private IClasspathEntry fCachedEntry;
private HashMap fAttributes;
public CPListElement(IJavaProject project, int entryKind, IPath path, IResource res) {
fProject= project;
fEntryKind= entryKind;
fPath= path;
fAttributes= new HashMap();
fResource= res;
fIsExported= false;
fIsMissing= false;
fCachedEntry= null;
fParentContainer= null;
switch (entryKind) {
case IClasspathEntry.CPE_SOURCE:
createAttributeElement(OUTPUT, null);
createAttributeElement(EXCLUSION, new Path[0]);
break;
case IClasspathEntry.CPE_LIBRARY:
case IClasspathEntry.CPE_VARIABLE:
createAttributeElement(SOURCEATTACHMENT, null);
createAttributeElement(JAVADOC, null);
break;
case IClasspathEntry.CPE_PROJECT:
case IClasspathEntry.CPE_CONTAINER:
break;
default:
}
}
public IClasspathEntry getClasspathEntry() {
if (fCachedEntry == null) {
fCachedEntry= newClasspathEntry();
}
return fCachedEntry;
}
private IClasspathEntry newClasspathEntry() {
switch (fEntryKind) {
case IClasspathEntry.CPE_SOURCE:
IPath outputLocation= (IPath) getAttribute(OUTPUT);
IPath[] exclusionPattern= (IPath[]) getAttribute(EXCLUSION);
return JavaCore.newSourceEntry(fPath, exclusionPattern, outputLocation);
case IClasspathEntry.CPE_LIBRARY:
IPath attach= (IPath) getAttribute(SOURCEATTACHMENT);
return JavaCore.newLibraryEntry(fPath, attach, null, isExported());
case IClasspathEntry.CPE_PROJECT:
return JavaCore.newProjectEntry(fPath, isExported());
case IClasspathEntry.CPE_CONTAINER:
return JavaCore.newContainerEntry(fPath, isExported());
case IClasspathEntry.CPE_VARIABLE:
IPath varAttach= (IPath) getAttribute(SOURCEATTACHMENT);
return JavaCore.newVariableEntry(fPath, varAttach, null, isExported());
default:
return null;
}
}
/**
* Gets the classpath entry path.
* @see IClasspathEntry#getPath()
*/
public IPath getPath() {
return fPath;
}
/**
* Gets the classpath entry kind.
* @see IClasspathEntry#getEntryKind()
*/
public int getEntryKind() {
return fEntryKind;
}
/**
* Entries without resource are either non existing or a variable entry
* External jars do not have a resource
*/
public IResource getResource() {
return fResource;
}
public CPListElementAttribute setAttribute(String key, Object value) {
CPListElementAttribute attribute= (CPListElementAttribute) fAttributes.get(key);
if (attribute == null) {
return null;
}
attribute.setValue(value);
attributeChanged(key);
return attribute;
}
public Object getAttribute(String key) {
CPListElementAttribute attrib= (CPListElementAttribute) fAttributes.get(key);
if (attrib != null) {
return attrib.getValue();
}
return null;
}
private CPListElementAttribute createAttributeElement(String key, Object value) {
CPListElementAttribute attribute= (CPListElementAttribute) fAttributes.get(key);
if (attribute == null) {
attribute= new CPListElementAttribute(this, key, value);
fAttributes.put(key, attribute);
}
return attribute;
}
public Object[] getChildren(boolean hideOutputFolder) {
if (fEntryKind == IClasspathEntry.CPE_CONTAINER) {
try {
IClasspathContainer container= JavaCore.getClasspathContainer(fPath, fProject);
IClasspathEntry[] entries= container.getClasspathEntries();
CPListElement[] elements= new CPListElement[entries.length];
for (int i= 0; i < elements.length; i++) {
elements[i]= createFromExisting(entries[i], fProject);
elements[i].setParentContainer(this);
}
return elements;
} catch (JavaModelException e) {
return new Object[0];
}
}
if (hideOutputFolder && fEntryKind == IClasspathEntry.CPE_SOURCE) {
return new Object[] { fAttributes.get(EXCLUSION) };
}
return fAttributes.values().toArray();
}
private void setParentContainer(CPListElement element) {
fParentContainer= element;
}
public CPListElement getParentContainer() {
return fParentContainer;
}
private void attributeChanged(String key) {
fCachedEntry= null;
}
/*
* @see Object#equals(java.lang.Object)
*/
public boolean equals(Object other) {
if (other != null && other.getClass() == getClass()) {
CPListElement elem= (CPListElement)other;
return elem.fEntryKind == fEntryKind && elem.fPath.equals(fPath);
}
return false;
}
/*
* @see Object#hashCode()
*/
public int hashCode() {
return fPath.hashCode() + fEntryKind;
}
/**
* Returns if a entry is missing.
* @return Returns a boolean
*/
public boolean isMissing() {
return fIsMissing;
}
/**
* Sets the 'missing' state of the entry.
*/
public void setIsMissing(boolean isMissing) {
fIsMissing= isMissing;
}
/**
* Returns if a entry is exported (only applies to libraries)
* @return Returns a boolean
*/
public boolean isExported() {
return fIsExported;
}
/**
* Sets the export state of the entry.
*/
public void setExported(boolean isExported) {
if (isExported != fIsExported) {
fIsExported = isExported;
attributeChanged(null);
}
}
/**
* Gets the project.
* @return Returns a IJavaProject
*/
public IJavaProject getJavaProject() {
return fProject;
}
public static CPListElement createFromExisting(IClasspathEntry curr, IJavaProject project) {
IPath path= curr.getPath();
IWorkspaceRoot root= project.getProject().getWorkspace().getRoot();
// get the resource
IResource res= null;
boolean isMissing= false;
URL javaDocLocation= null;
switch (curr.getEntryKind()) {
case IClasspathEntry.CPE_CONTAINER:
res= null;
try {
isMissing= (JavaCore.getClasspathContainer(path, project) == null);
} catch (JavaModelException e) {
isMissing= true;
}
break;
case IClasspathEntry.CPE_VARIABLE:
IPath resolvedPath= JavaCore.getResolvedVariablePath(path);
res= null;
isMissing= root.findMember(resolvedPath) == null && !resolvedPath.toFile().isFile();
javaDocLocation= JavaUI.getLibraryJavadocLocation(resolvedPath);
break;
case IClasspathEntry.CPE_LIBRARY:
res= root.findMember(path);
if (res == null) {
if (!ArchiveFileFilter.isArchivePath(path)) {
if (root.getWorkspace().validatePath(path.toString(), IResource.FOLDER).isOK()) {
res= root.getFolder(path);
}
}
isMissing= !path.toFile().isFile(); // look for external JARs
}
javaDocLocation= JavaUI.getLibraryJavadocLocation(path);
break;
case IClasspathEntry.CPE_SOURCE:
res= root.findMember(path);
if (res == null) {
if (root.getWorkspace().validatePath(path.toString(), IResource.FOLDER).isOK()) {
res= root.getFolder(path);
}
isMissing= true;
}
break;
case IClasspathEntry.CPE_PROJECT:
res= root.findMember(path);
isMissing= (res == null);
break;
}
CPListElement elem= new CPListElement(project, curr.getEntryKind(), path, res);
elem.setExported(curr.isExported());
elem.setAttribute(SOURCEATTACHMENT, curr.getSourceAttachmentPath());
elem.setAttribute(JAVADOC, javaDocLocation);
elem.setAttribute(OUTPUT, curr.getOutputLocation());
elem.setAttribute(EXCLUSION, curr.getExclusionPatterns());
if (project.exists()) {
elem.setIsMissing(isMissing);
}
return elem;
}
}
|
28,510 |
Bug 28510 java build path inconsistency [build path]
|
20021216 select rt.jar in the package explorer open properties it allows you to set the javadoc location but for source attachment you are sent somewhere else it's inconsistent - on the java build path they both look sort of the same (they sit under the same node in the tree)
|
resolved fixed
|
bcd21c9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-20T18:15:37Z | 2002-12-17T15:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/LibrariesWorkbookPage.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.wizards.buildpaths;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
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.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.model.WorkbenchContentProvider;
import org.eclipse.ui.model.WorkbenchLabelProvider;
import org.eclipse.ui.views.navigator.ResourceSorter;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaModel;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.IUIConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.dialogs.StatusDialog;
import org.eclipse.jdt.internal.ui.preferences.JavadocConfigurationBlock;
import org.eclipse.jdt.internal.ui.util.PixelConverter;
import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener;
import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages;
import org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator;
import org.eclipse.jdt.internal.ui.wizards.TypedViewerFilter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.ComboDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.ITreeListAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.TreeListDialogField;
public class LibrariesWorkbookPage extends BuildPathBasePage {
private ListDialogField fClassPathList;
private IJavaProject fCurrJProject;
private TreeListDialogField fLibrariesList;
private IWorkspaceRoot fWorkspaceRoot;
private IDialogSettings fDialogSettings;
private Control fSWTControl;
private final int IDX_ADDJAR= 0;
private final int IDX_ADDEXT= 1;
private final int IDX_ADDVAR= 2;
private final int IDX_ADDLIB= 3;
private final int IDX_ADDFOL= 4;
private final int IDX_EDIT= 6;
private final int IDX_REMOVE= 7;
public LibrariesWorkbookPage(IWorkspaceRoot root, ListDialogField classPathList) {
fClassPathList= classPathList;
fWorkspaceRoot= root;
fSWTControl= null;
fDialogSettings= JavaPlugin.getDefault().getDialogSettings();
String[] buttonLabels= new String[] {
/* IDX_ADDJAR*/ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.addjar.button"), //$NON-NLS-1$
/* IDX_ADDEXT */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.addextjar.button"), //$NON-NLS-1$
/* IDX_ADDVAR */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.addvariable.button"), //$NON-NLS-1$
/* IDX_ADDLIB */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.addlibrary.button"), //$NON-NLS-1$
/* IDX_ADDFOL */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.addclassfolder.button"), //$NON-NLS-1$
/* */ null,
/* IDX_EDIT */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.edit.button"), //$NON-NLS-1$
/* IDX_REMOVE */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.remove.button") //$NON-NLS-1$
};
LibrariesAdapter adapter= new LibrariesAdapter();
fLibrariesList= new TreeListDialogField(adapter, buttonLabels, new CPListLabelProvider());
fLibrariesList.setDialogFieldListener(adapter);
fLibrariesList.setLabelText(NewWizardMessages.getString("LibrariesWorkbookPage.libraries.label")); //$NON-NLS-1$
fLibrariesList.setRemoveButtonIndex(IDX_REMOVE); //$NON-NLS-1$
fLibrariesList.enableButton(IDX_EDIT, false);
fLibrariesList.setViewerSorter(new CPListElementSorter());
}
public void init(IJavaProject jproject) {
fCurrJProject= jproject;
updateLibrariesList();
}
private void updateLibrariesList() {
List cpelements= fClassPathList.getElements();
List libelements= new ArrayList(cpelements.size());
int nElements= cpelements.size();
for (int i= 0; i < nElements; i++) {
CPListElement cpe= (CPListElement)cpelements.get(i);
if (isEntryKind(cpe.getEntryKind())) {
libelements.add(cpe);
}
}
fLibrariesList.setElements(libelements);
}
// -------- ui creation
public Control getControl(Composite parent) {
PixelConverter converter= new PixelConverter(parent);
Composite composite= new Composite(parent, SWT.NONE);
LayoutUtil.doDefaultLayout(composite, new DialogField[] { fLibrariesList }, true);
LayoutUtil.setHorizontalGrabbing(fLibrariesList.getTreeControl(null));
int buttonBarWidth= converter.convertWidthInCharsToPixels(24);
fLibrariesList.setButtonsMinWidth(buttonBarWidth);
fLibrariesList.getTreeViewer().setSorter(new CPListElementSorter());
fSWTControl= composite;
return composite;
}
private Shell getShell() {
if (fSWTControl != null) {
return fSWTControl.getShell();
}
return JavaPlugin.getActiveWorkbenchShell();
}
private class LibrariesAdapter implements IDialogFieldListener, ITreeListAdapter {
private final Object[] EMPTY_ARR= new Object[0];
// -------- IListAdapter --------
public void customButtonPressed(TreeListDialogField field, int index) {
libaryPageCustomButtonPressed(field, index);
}
public void selectionChanged(TreeListDialogField field) {
libaryPageSelectionChanged(field);
}
public void doubleClicked(TreeListDialogField field) {
libaryPageDoubleClicked(field);
}
public Object[] getChildren(TreeListDialogField field, Object element) {
if (element instanceof CPListElement) {
return ((CPListElement) element).getChildren(false);
}
return EMPTY_ARR;
}
public Object getParent(TreeListDialogField field, Object element) {
if (element instanceof CPListElementAttribute) {
return ((CPListElementAttribute) element).getParent();
}
return null;
}
public boolean hasChildren(TreeListDialogField field, Object element) {
return (element instanceof CPListElement);
}
// ---------- IDialogFieldListener --------
public void dialogFieldChanged(DialogField field) {
libaryPageDialogFieldChanged(field);
}
}
private void libaryPageCustomButtonPressed(DialogField field, int index) {
CPListElement[] libentries= null;
switch (index) {
case IDX_ADDJAR: /* add jar */
libentries= openJarFileDialog(null);
break;
case IDX_ADDEXT: /* add external jar */
libentries= openExtJarFileDialog(null);
break;
case IDX_ADDVAR: /* add variable */
libentries= openVariableSelectionDialog(null);
break;
case IDX_ADDLIB: /* addvanced */
libentries= openContainerSelectionDialog(null);
break;
case IDX_ADDFOL: /* addvanced */
libentries= openClassFolderDialog(null);
break;
case IDX_EDIT: /* edit */
editEntry();
return;
}
if (libentries != null) {
int nElementsChosen= libentries.length;
// remove duplicates
List cplist= fLibrariesList.getElements();
List elementsToAdd= new ArrayList(nElementsChosen);
for (int i= 0; i < nElementsChosen; i++) {
CPListElement curr= libentries[i];
if (!cplist.contains(curr) && !elementsToAdd.contains(curr)) {
elementsToAdd.add(curr);
addAttachmentsFromExistingLibs(curr);
}
}
fLibrariesList.addElements(elementsToAdd);
fLibrariesList.postSetSelection(new StructuredSelection(libentries));
}
}
protected void libaryPageDoubleClicked(TreeListDialogField field) {
List selection= fLibrariesList.getSelectedElements();
if (canEdit(selection)) {
editEntry();
}
}
/**
* Method editEntry.
*/
private void editEntry() {
List selElements= fLibrariesList.getSelectedElements();
if (selElements.size() != 1) {
return;
}
Object elem= selElements.get(0);
if (fLibrariesList.getIndexOfElement(elem) != -1) {
editElementEntry((CPListElement) elem);
} else if (elem instanceof CPListElementAttribute) {
editAttributeEntry((CPListElementAttribute) elem);
}
}
private void editAttributeEntry(CPListElementAttribute elem) {
String key= elem.getKey();
if (key.equals(CPListElement.SOURCEATTACHMENT)) {
CPListElement selElement= (CPListElement) elem.getParent();
IPath containerPath= null;
boolean applyChanges= false;
CPListElement parentContainer= selElement.getParentContainer();
if (parentContainer != null) {
containerPath= parentContainer.getPath();
applyChanges= true;
}
SourceAttachmentDialog dialog= new SourceAttachmentDialog(getShell(), selElement.getClasspathEntry(), containerPath, fCurrJProject, applyChanges);
if (dialog.open() == SourceAttachmentDialog.OK) {
selElement.setAttribute(CPListElement.SOURCEATTACHMENT, dialog.getSourceAttachmentPath());
fLibrariesList.refresh();
fClassPathList.refresh(); // images
}
} else if (key.equals(CPListElement.JAVADOC)) {
CPListElement selElement= (CPListElement) elem.getParent();
JavadocPropertyDialog dialog= new JavadocPropertyDialog(getShell(), selElement);
if (dialog.open() == JavadocPropertyDialog.OK) {
selElement.setAttribute(CPListElement.JAVADOC, dialog.getJavaDocLocation());
fLibrariesList.refresh();
}
}
}
private void editElementEntry(CPListElement elem) {
CPListElement[] res= null;
switch (elem.getEntryKind()) {
case IClasspathEntry.CPE_CONTAINER:
res= openContainerSelectionDialog(elem);
break;
case IClasspathEntry.CPE_LIBRARY:
IResource resource= elem.getResource();
if (resource == null) {
res= openExtJarFileDialog(elem);
} else if (resource.getType() == IResource.FOLDER) {
if (resource.exists()) {
res= openClassFolderDialog(elem);
} else {
res= openNewClassFolderDialog(elem);
}
} else if (resource.getType() == IResource.FILE) {
res= openJarFileDialog(elem);
}
break;
case IClasspathEntry.CPE_VARIABLE:
res= openVariableSelectionDialog(elem);
break;
}
if (res != null && res.length > 0) {
fLibrariesList.replaceElement(elem, res[0]);
}
}
private void libaryPageSelectionChanged(DialogField field) {
List selElements= fLibrariesList.getSelectedElements();
fLibrariesList.enableButton(IDX_EDIT, canEdit(selElements));
}
private boolean canEdit(List selElements) {
if (selElements.size() != 1) {
return false;
}
Object elem= selElements.get(0);
if (fLibrariesList.getIndexOfElement(elem) != -1) {
return true;
}
if (elem instanceof CPListElementAttribute) {
CPListElementAttribute attrib= (CPListElementAttribute) elem;
if (attrib.getKey().equals(CPListElement.SOURCEATTACHMENT)) {
return true;
}
return ((CPListElementAttribute) elem).getParent().getParentContainer() == null;
}
return false;
}
private void libaryPageDialogFieldChanged(DialogField field) {
if (fCurrJProject != null) {
// already initialized
updateClasspathList();
}
}
private void updateClasspathList() {
List projelements= fLibrariesList.getElements();
boolean remove= false;
List cpelements= fClassPathList.getElements();
// backwards, as entries will be deleted
for (int i= cpelements.size() - 1; i >= 0; i--) {
CPListElement cpe= (CPListElement)cpelements.get(i);
int kind= cpe.getEntryKind();
if (isEntryKind(kind)) {
if (!projelements.remove(cpe)) {
cpelements.remove(i);
remove= true;
}
}
}
for (int i= 0; i < projelements.size(); i++) {
cpelements.add(projelements.get(i));
}
if (remove || (projelements.size() > 0)) {
fClassPathList.setElements(cpelements);
}
}
private CPListElement[] openNewClassFolderDialog(CPListElement existing) {
String title= (existing == null) ? NewWizardMessages.getString("LibrariesWorkbookPage.NewClassFolderDialog.new.title") : NewWizardMessages.getString("LibrariesWorkbookPage.NewClassFolderDialog.edit.title"); //$NON-NLS-1$ //$NON-NLS-2$
IProject currProject= fCurrJProject.getProject();
NewContainerDialog dialog= new NewContainerDialog(getShell(), title, currProject, getUsedContainers(existing), existing);
IPath projpath= currProject.getFullPath();
dialog.setMessage(NewWizardMessages.getFormattedString("LibrariesWorkbookPage.NewClassFolderDialog.description", projpath.toString())); //$NON-NLS-1$
if (dialog.open() == NewContainerDialog.OK) {
IFolder folder= dialog.getFolder();
return new CPListElement[] { newCPLibraryElement(folder) };
}
return null;
}
private CPListElement[] openClassFolderDialog(CPListElement existing) {
Class[] acceptedClasses= new Class[] { IFolder.class };
TypedElementSelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, existing == null);
acceptedClasses= new Class[] { IProject.class, IFolder.class };
ViewerFilter filter= new TypedViewerFilter(acceptedClasses, getUsedContainers(existing));
ILabelProvider lp= new WorkbenchLabelProvider();
ITreeContentProvider cp= new WorkbenchContentProvider();
String title= (existing == null) ? NewWizardMessages.getString("LibrariesWorkbookPage.ExistingClassFolderDialog.new.title") : NewWizardMessages.getString("LibrariesWorkbookPage.ExistingClassFolderDialog.edit.title"); //$NON-NLS-1$ //$NON-NLS-2$
String message= (existing == null) ? NewWizardMessages.getString("LibrariesWorkbookPage.ExistingClassFolderDialog.new.description") : NewWizardMessages.getString("LibrariesWorkbookPage.ExistingClassFolderDialog.edit.description"); //$NON-NLS-1$ //$NON-NLS-2$
FolderSelectionDialog dialog= new FolderSelectionDialog(getShell(), lp, cp);
dialog.setValidator(validator);
dialog.setTitle(title);
dialog.setMessage(message);
dialog.addFilter(filter);
dialog.setInput(fWorkspaceRoot);
dialog.setSorter(new ResourceSorter(ResourceSorter.NAME));
if (existing == null) {
dialog.setInitialSelection(fCurrJProject.getProject());
} else {
dialog.setInitialSelection(existing.getResource());
}
if (dialog.open() == FolderSelectionDialog.OK) {
Object[] elements= dialog.getResult();
CPListElement[] res= new CPListElement[elements.length];
for (int i= 0; i < res.length; i++) {
IResource elem= (IResource) elements[i];
res[i]= newCPLibraryElement(elem);
}
return res;
}
return null;
}
private CPListElement[] openJarFileDialog(CPListElement existing) {
Class[] acceptedClasses= new Class[] { IFile.class };
TypedElementSelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, existing == null);
ViewerFilter filter= new ArchiveFileFilter(getUsedJARFiles(existing), true);
ILabelProvider lp= new WorkbenchLabelProvider();
ITreeContentProvider cp= new WorkbenchContentProvider();
String title= (existing == null) ? NewWizardMessages.getString("LibrariesWorkbookPage.JARArchiveDialog.new.title") : NewWizardMessages.getString("LibrariesWorkbookPage.JARArchiveDialog.edit.title"); //$NON-NLS-1$ //$NON-NLS-2$
String message= (existing == null) ? NewWizardMessages.getString("LibrariesWorkbookPage.JARArchiveDialog.new.description") : NewWizardMessages.getString("LibrariesWorkbookPage.JARArchiveDialog.edit.description"); //$NON-NLS-1$ //$NON-NLS-2$
ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), lp, cp);
dialog.setValidator(validator);
dialog.setTitle(title);
dialog.setMessage(message);
dialog.addFilter(filter);
dialog.setInput(fWorkspaceRoot);
dialog.setSorter(new ResourceSorter(ResourceSorter.NAME));
if (existing == null) {
dialog.setInitialSelection(fCurrJProject.getProject());
} else {
dialog.setInitialSelection(existing.getResource());
}
if (dialog.open() == ElementTreeSelectionDialog.OK) {
Object[] elements= dialog.getResult();
CPListElement[] res= new CPListElement[elements.length];
for (int i= 0; i < res.length; i++) {
IResource elem= (IResource)elements[i];
res[i]= newCPLibraryElement(elem);
}
return res;
}
return null;
}
private IContainer[] getUsedContainers(CPListElement existing) {
ArrayList res= new ArrayList();
if (fCurrJProject.exists()) {
try {
IPath outputLocation= fCurrJProject.getOutputLocation();
if (outputLocation != null) {
IResource resource= fWorkspaceRoot.findMember(outputLocation);
if (resource instanceof IFolder) { // != Project
res.add(resource);
}
}
} catch (JavaModelException e) {
// ignore it here, just log
JavaPlugin.log(e.getStatus());
}
}
List cplist= fLibrariesList.getElements();
for (int i= 0; i < cplist.size(); i++) {
CPListElement elem= (CPListElement)cplist.get(i);
if (elem.getEntryKind() == IClasspathEntry.CPE_LIBRARY && (elem != existing)) {
IResource resource= elem.getResource();
if (resource instanceof IContainer && !resource.equals(existing)) {
res.add(resource);
}
}
}
return (IContainer[]) res.toArray(new IContainer[res.size()]);
}
private IFile[] getUsedJARFiles(CPListElement existing) {
List res= new ArrayList();
List cplist= fLibrariesList.getElements();
for (int i= 0; i < cplist.size(); i++) {
CPListElement elem= (CPListElement)cplist.get(i);
if (elem.getEntryKind() == IClasspathEntry.CPE_LIBRARY && (elem != existing)) {
IResource resource= elem.getResource();
if (resource instanceof IFile) {
res.add(resource);
}
}
}
return (IFile[]) res.toArray(new IFile[res.size()]);
}
private CPListElement newCPLibraryElement(IResource res) {
return new CPListElement(fCurrJProject, IClasspathEntry.CPE_LIBRARY, res.getFullPath(), res);
};
private CPListElement[] openExtJarFileDialog(CPListElement existing) {
String lastUsedPath;
if (existing != null) {
lastUsedPath= existing.getPath().removeLastSegments(1).toOSString();
} else {
lastUsedPath= fDialogSettings.get(IUIConstants.DIALOGSTORE_LASTEXTJAR);
if (lastUsedPath == null) {
lastUsedPath= ""; //$NON-NLS-1$
}
}
String title= (existing == null) ? NewWizardMessages.getString("LibrariesWorkbookPage.ExtJARArchiveDialog.new.title") : NewWizardMessages.getString("LibrariesWorkbookPage.ExtJARArchiveDialog.edit.title"); //$NON-NLS-1$ //$NON-NLS-2$
FileDialog dialog= new FileDialog(getShell(), existing == null ? SWT.MULTI : SWT.SINGLE);
dialog.setText(title);
dialog.setFilterExtensions(new String[] {"*.jar;*.zip"}); //$NON-NLS-1$
dialog.setFilterPath(lastUsedPath);
if (existing != null) {
dialog.setFileName(existing.getPath().lastSegment());
}
String res= dialog.open();
if (res == null) {
return null;
}
String[] fileNames= dialog.getFileNames();
int nChosen= fileNames.length;
IPath filterPath= new Path(dialog.getFilterPath());
CPListElement[] elems= new CPListElement[nChosen];
for (int i= 0; i < nChosen; i++) {
IPath path= filterPath.append(fileNames[i]).makeAbsolute();
elems[i]= new CPListElement(fCurrJProject, IClasspathEntry.CPE_LIBRARY, path, null);
}
fDialogSettings.put(IUIConstants.DIALOGSTORE_LASTEXTJAR, filterPath.toOSString());
return elems;
}
private CPListElement[] openVariableSelectionDialog(CPListElement existing) {
if (existing == null) {
NewVariableEntryDialog dialog= new NewVariableEntryDialog(getShell());
dialog.setTitle(NewWizardMessages.getString("LibrariesWorkbookPage.VariableSelectionDialog.new.title"));
if (dialog.open() == NewVariableEntryDialog.OK) {
List existingElements= fLibrariesList.getElements();
IPath[] paths= dialog.getResult();
ArrayList result= new ArrayList();
for (int i = 0; i < paths.length; i++) {
CPListElement elem= new CPListElement(fCurrJProject, IClasspathEntry.CPE_VARIABLE, paths[i], null);
IPath resolvedPath= JavaCore.getResolvedVariablePath(paths[i]);
elem.setIsMissing((resolvedPath == null) || !resolvedPath.toFile().exists());
if (!existingElements.contains(elem)) {
result.add(elem);
}
}
return (CPListElement[]) result.toArray(new CPListElement[result.size()]);
}
} else {
List existingElements= fLibrariesList.getElements();
ArrayList existingPaths= new ArrayList(existingElements.size());
for (int i= 0; i < existingElements.size(); i++) {
CPListElement elem= (CPListElement) existingElements.get(i);
if (elem.getEntryKind() == IClasspathEntry.CPE_VARIABLE) {
existingPaths.add(elem.getPath());
}
}
EditVariableEntryDialog dialog= new EditVariableEntryDialog(getShell(), existing.getPath(), existingPaths);
dialog.setTitle(NewWizardMessages.getString("LibrariesWorkbookPage.VariableSelectionDialog.edit.title"));
if (dialog.open() == EditVariableEntryDialog.OK) {
CPListElement elem= new CPListElement(fCurrJProject, IClasspathEntry.CPE_VARIABLE, dialog.getPath(), null);
return new CPListElement[] { elem };
}
}
return null;
}
private CPListElement[] openContainerSelectionDialog(CPListElement existing) {
IClasspathEntry elem= null;
String title;
if (existing == null) {
title= NewWizardMessages.getString("LibrariesWorkbookPage.ContainerDialog.new.title"); //$NON-NLS-1$
} else {
title= NewWizardMessages.getString("LibrariesWorkbookPage.ContainerDialog.edit.title"); //$NON-NLS-1$
elem= existing.getClasspathEntry();
}
return openContainerDialog(title, new ClasspathContainerWizard(elem, fCurrJProject, getRawClasspath()));
}
private CPListElement[] openContainerDialog(String title, ClasspathContainerWizard wizard) {
WizardDialog dialog= new WizardDialog(getShell(), wizard);
PixelConverter converter= new PixelConverter(getShell());
dialog.setMinimumPageSize(converter.convertWidthInCharsToPixels(40), converter.convertHeightInCharsToPixels(20));
dialog.create();
dialog.getShell().setText(title);
if (dialog.open() == WizardDialog.OK) {
IClasspathEntry created= wizard.getNewEntry();
if (created != null) {
CPListElement elem= new CPListElement(fCurrJProject, IClasspathEntry.CPE_CONTAINER, created.getPath(), null);
if (elem != null) {
return new CPListElement[] { elem };
}
}
}
return null;
}
private void addAttachmentsFromExistingLibs(CPListElement elem) {
if (elem.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
return;
}
try {
IJavaModel jmodel= fCurrJProject.getJavaModel();
IJavaProject[] jprojects= jmodel.getJavaProjects();
for (int i= 0; i < jprojects.length; i++) {
IJavaProject curr= jprojects[i];
if (!curr.equals(fCurrJProject)) {
IClasspathEntry[] entries= curr.getRawClasspath();
for (int k= 0; k < entries.length; k++) {
IClasspathEntry entry= entries[k];
if (entry.getEntryKind() == elem.getEntryKind()
&& entry.getPath().equals(elem.getPath())) {
IPath attachPath= entry.getSourceAttachmentPath();
if (attachPath != null && !attachPath.isEmpty()) {
elem.setAttribute(CPListElement.SOURCEATTACHMENT, attachPath);
return;
}
}
}
}
}
elem.setAttribute(CPListElement.JAVADOC, JavaUI.getLibraryJavadocLocation(elem.getPath()));
} catch (JavaModelException e) {
JavaPlugin.log(e.getStatus());
}
}
private class AdvancedDialog extends Dialog {
private static final String DIALOGSTORE_ADV_SECTION= "LibrariesWorkbookPage.advanced"; //$NON-NLS-1$
private static final String DIALOGSTORE_SELECTED= "selected"; //$NON-NLS-1$
private static final String DIALOGSTORE_CONTAINER_IDX= "containerindex"; //$NON-NLS-1$
private DialogField fLabelField;
private SelectionButtonDialogField fCreateFolderField;
private SelectionButtonDialogField fAddFolderField;
private SelectionButtonDialogField fAddContainerField;
private ComboDialogField fCombo;
private CPListElement[] fResult;
private IDialogSettings fAdvSettings;
private ClasspathContainerDescriptor[] fDescriptors;
public AdvancedDialog(Shell parent) {
super(parent);
fAdvSettings= fDialogSettings.getSection(DIALOGSTORE_ADV_SECTION);
if (fAdvSettings == null) {
fAdvSettings= fDialogSettings.addNewSection(DIALOGSTORE_ADV_SECTION);
fAdvSettings.put(DIALOGSTORE_SELECTED, 2); // container
fAdvSettings.put(DIALOGSTORE_CONTAINER_IDX, 0);
}
fDescriptors= ClasspathContainerDescriptor.getDescriptors();
fLabelField= new DialogField();
fLabelField.setLabelText(NewWizardMessages.getString("LibrariesWorkbookPage.AdvancedDialog.description")); //$NON-NLS-1$
fCreateFolderField= new SelectionButtonDialogField(SWT.RADIO);
fCreateFolderField.setLabelText(NewWizardMessages.getString("LibrariesWorkbookPage.AdvancedDialog.createfolder")); //$NON-NLS-1$
fAddFolderField= new SelectionButtonDialogField(SWT.RADIO);
fAddFolderField.setLabelText(NewWizardMessages.getString("LibrariesWorkbookPage.AdvancedDialog.addfolder")); //$NON-NLS-1$
fAddContainerField= new SelectionButtonDialogField(SWT.RADIO);
fAddContainerField.setLabelText(NewWizardMessages.getString("LibrariesWorkbookPage.AdvancedDialog.addcontainer")); //$NON-NLS-1$
String[] names= new String[fDescriptors.length];
for (int i = 0; i < names.length; i++) {
names[i]= fDescriptors[i].getName();
}
fCombo= new ComboDialogField(SWT.READ_ONLY);
fCombo.setItems(names);
fAddContainerField.attachDialogField(fCombo);
int selected= fAdvSettings.getInt(DIALOGSTORE_SELECTED);
fCreateFolderField.setSelection(selected == 0);
fAddFolderField.setSelection(selected == 1);
fAddContainerField.setSelection(selected == 2);
fCombo.selectItem(fAdvSettings.getInt(DIALOGSTORE_CONTAINER_IDX));
}
/*
* @see Window#create(Shell)
*/
protected void configureShell(Shell shell) {
super.configureShell(shell);
shell.setText(NewWizardMessages.getString("LibrariesWorkbookPage.AdvancedDialog.title")); //$NON-NLS-1$
WorkbenchHelp.setHelp(shell, IJavaHelpContextIds.LIBRARIES_WORKBOOK_PAGE_ADVANCED_DIALOG);
}
protected Control createDialogArea(Composite parent) {
initializeDialogUnits(parent);
Composite composite= (Composite) super.createDialogArea(parent);
Composite inner= new Composite(composite, SWT.NONE);
GridLayout layout= new GridLayout();
layout.marginHeight= 0;
layout.marginWidth= 0;
inner.setLayout(layout);
fLabelField.doFillIntoGrid(inner, 1);
fCreateFolderField.doFillIntoGrid(inner, 1);
fAddFolderField.doFillIntoGrid(inner, 1);
fAddContainerField.doFillIntoGrid(inner, 1);
Control control= fCombo.getComboControl(inner);
GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalIndent= convertWidthInCharsToPixels(3);
control.setLayoutData(gd);
return composite;
}
/* (non-Javadoc)
* @see Dialog#okPressed()
*/
protected void okPressed() {
fResult= null;
if (fCreateFolderField.isSelected()) {
fResult= openNewClassFolderDialog(null);
fAdvSettings.put(DIALOGSTORE_SELECTED, 0);
} else if (fAddFolderField.isSelected()) {
fResult= openClassFolderDialog(null);
fAdvSettings.put(DIALOGSTORE_SELECTED, 1);
} else if (fAddContainerField.isSelected()) {
String selected= fCombo.getText();
for (int i = 0; i < fDescriptors.length; i++) {
if (fDescriptors[i].getName().equals(selected)) {
String title= NewWizardMessages.getString("LibrariesWorkbookPage.ContainerDialog.new.title"); //$NON-NLS-1$
fResult= openContainerDialog(title, new ClasspathContainerWizard(fDescriptors[i], fCurrJProject, getRawClasspath()));
fAdvSettings.put(DIALOGSTORE_CONTAINER_IDX, i);
break;
}
}
fAdvSettings.put(DIALOGSTORE_SELECTED, 2);
}
if (fResult != null) {
super.okPressed();
}
// stay open
}
public CPListElement[] getResult() {
return fResult;
}
}
private IClasspathEntry[] getRawClasspath() {
IClasspathEntry[] currEntries= new IClasspathEntry[fClassPathList.getSize()];
for (int i= 0; i < currEntries.length; i++) {
CPListElement curr= (CPListElement) fClassPathList.getElement(i);
currEntries[i]= curr.getClasspathEntry();
}
return currEntries;
}
private class JavadocPropertyDialog extends StatusDialog implements IStatusChangeListener {
private JavadocConfigurationBlock fJavadocConfigurationBlock;
private CPListElement fElement;
public JavadocPropertyDialog(Shell parent, CPListElement element) {
super(parent);
setTitle(NewWizardMessages.getFormattedString("LibrariesWorkbookPage.JavadocPropertyDialog.title", element.getPath().toString())); //$NON-NLS-1$
fElement= element;
URL initialLocation= JavaUI.getLibraryJavadocLocation(element.getPath());
fJavadocConfigurationBlock= new JavadocConfigurationBlock(parent, this, initialLocation);
}
protected Control createDialogArea(Composite parent) {
Composite composite= (Composite) super.createDialogArea(parent);
Control inner= fJavadocConfigurationBlock.createContents(composite);
inner.setLayoutData(new GridData(GridData.FILL_BOTH));
return composite;
}
public void statusChanged(IStatus status) {
updateStatus(status);
}
public URL getJavaDocLocation() {
return fJavadocConfigurationBlock.getJavadocLocation();
}
/*
* @see org.eclipse.jface.window.Window#configureShell(Shell)
*/
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
WorkbenchHelp.setHelp(newShell, IJavaHelpContextIds.JAVADOC_PROPERTY_DIALOG);
}
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.wizards.buildpaths.BuildPathBasePage#isEntryKind(int)
*/
public boolean isEntryKind(int kind) {
return kind == IClasspathEntry.CPE_LIBRARY || kind == IClasspathEntry.CPE_VARIABLE || kind == IClasspathEntry.CPE_CONTAINER;
}
/*
* @see BuildPathBasePage#getSelection
*/
public List getSelection() {
return fLibrariesList.getSelectedElements();
}
/*
* @see BuildPathBasePage#setSelection
*/
public void setSelection(List selElements) {
fLibrariesList.selectElements(new StructuredSelection(selElements));
}
}
|
28,510 |
Bug 28510 java build path inconsistency [build path]
|
20021216 select rt.jar in the package explorer open properties it allows you to set the javadoc location but for source attachment you are sent somewhere else it's inconsistent - on the java build path they both look sort of the same (they sit under the same node in the tree)
|
resolved fixed
|
bcd21c9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-20T18:15:37Z | 2002-12-17T15:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/SourceContainerWorkbookPage.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.wizards.buildpaths;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.ui.model.WorkbenchContentProvider;
import org.eclipse.ui.model.WorkbenchLabelProvider;
import org.eclipse.ui.views.navigator.ResourceSorter;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
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.util.PixelConverter;
import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages;
import org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator;
import org.eclipse.jdt.internal.ui.wizards.TypedViewerFilter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.ITreeListAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.TreeListDialogField;
public class SourceContainerWorkbookPage extends BuildPathBasePage {
private ListDialogField fClassPathList;
private IJavaProject fCurrJProject;
private IPath fProjPath;
private Control fSWTControl;
private IWorkspaceRoot fWorkspaceRoot;
private TreeListDialogField fFoldersList;
private StringDialogField fOutputLocationField;
private SelectionButtonDialogField fUseFolderOutputs;
private final int IDX_ADD= 0;
private final int IDX_EDIT= 2;
private final int IDX_REMOVE= 3;
public SourceContainerWorkbookPage(IWorkspaceRoot root, ListDialogField classPathList, StringDialogField outputLocationField) {
fWorkspaceRoot= root;
fClassPathList= classPathList;
fOutputLocationField= outputLocationField;
fSWTControl= null;
SourceContainerAdapter adapter= new SourceContainerAdapter();
String[] buttonLabels;
int removeIndex;
buttonLabels= new String[] {
/* 0 = IDX_ADDEXIST */ NewWizardMessages.getString("SourceContainerWorkbookPage.folders.add.button"), //$NON-NLS-1$
/* 1 */ null,
/* 2 = IDX_EDIT */ NewWizardMessages.getString("SourceContainerWorkbookPage.folders.edit.button"), //$NON-NLS-1$
/* 3 = IDX_REMOVE */ NewWizardMessages.getString("SourceContainerWorkbookPage.folders.remove.button") //$NON-NLS-1$
};
removeIndex= IDX_REMOVE;
fFoldersList= new TreeListDialogField(adapter, buttonLabels, new CPListLabelProvider());
fFoldersList.setDialogFieldListener(adapter);
fFoldersList.setLabelText(NewWizardMessages.getString("SourceContainerWorkbookPage.folders.label")); //$NON-NLS-1$
fFoldersList.setRemoveButtonIndex(removeIndex);
fFoldersList.setViewerSorter(new CPListElementSorter());
fFoldersList.enableButton(IDX_EDIT, false);
fUseFolderOutputs= new SelectionButtonDialogField(SWT.CHECK);
fUseFolderOutputs.setSelection(false);
fUseFolderOutputs.setLabelText(NewWizardMessages.getString("SourceContainerWorkbookPage.folders.check"));
fUseFolderOutputs.setDialogFieldListener(adapter);
}
public void init(IJavaProject jproject) {
fCurrJProject= jproject;
fProjPath= fCurrJProject.getProject().getFullPath();
updateFoldersList();
}
private void updateFoldersList() {
ArrayList folders= new ArrayList();
boolean useFolderOutputs= false;
List cpelements= fClassPathList.getElements();
for (int i= 0; i < cpelements.size(); i++) {
CPListElement cpe= (CPListElement)cpelements.get(i);
if (cpe.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
folders.add(cpe);
boolean hasOutputFolder= (cpe.getAttribute(CPListElement.OUTPUT) != null);
if (hasOutputFolder) {
useFolderOutputs= true;
}
}
}
fFoldersList.setElements(folders);
fUseFolderOutputs.setSelection(useFolderOutputs);
for (int i= 0; i < folders.size(); i++) {
CPListElement cpe= (CPListElement) folders.get(i);
IPath[] patterns= (IPath[]) cpe.getAttribute(CPListElement.EXCLUSION);
boolean hasOutputFolder= (cpe.getAttribute(CPListElement.OUTPUT) != null);
if (patterns.length > 0 || hasOutputFolder) {
fFoldersList.expandElement(cpe, 3);
}
}
}
public Control getControl(Composite parent) {
PixelConverter converter= new PixelConverter(parent);
Composite composite= new Composite(parent, SWT.NONE);
LayoutUtil.doDefaultLayout(composite, new DialogField[] { fFoldersList, fUseFolderOutputs }, true);
LayoutUtil.setHorizontalGrabbing(fFoldersList.getTreeControl(null));
int buttonBarWidth= converter.convertWidthInCharsToPixels(24);
fFoldersList.setButtonsMinWidth(buttonBarWidth);
fSWTControl= composite;
// expand
List elements= fFoldersList.getElements();
for (int i= 0; i < elements.size(); i++) {
CPListElement elem= (CPListElement) elements.get(i);
IPath[] patterns= (IPath[]) elem.getAttribute(CPListElement.EXCLUSION);
IPath output= (IPath) elem.getAttribute(CPListElement.OUTPUT);
if (patterns.length > 0 || output != null) {
fFoldersList.expandElement(elem, 3);
}
}
return composite;
}
private Shell getShell() {
if (fSWTControl != null) {
return fSWTControl.getShell();
}
return JavaPlugin.getActiveWorkbenchShell();
}
private class SourceContainerAdapter implements ITreeListAdapter, IDialogFieldListener {
private final Object[] EMPTY_ARR= new Object[0];
// -------- IListAdapter --------
public void customButtonPressed(TreeListDialogField field, int index) {
sourcePageCustomButtonPressed(field, index);
}
public void selectionChanged(TreeListDialogField field) {
sourcePageSelectionChanged(field);
}
public void doubleClicked(TreeListDialogField field) {
sourcePageDoubleClicked(field);
}
public Object[] getChildren(TreeListDialogField field, Object element) {
if (element instanceof CPListElement) {
return ((CPListElement) element).getChildren(!fUseFolderOutputs.isSelected());
}
return EMPTY_ARR;
}
public Object getParent(TreeListDialogField field, Object element) {
if (element instanceof CPListElementAttribute) {
return ((CPListElementAttribute) element).getParent();
}
return null;
}
public boolean hasChildren(TreeListDialogField field, Object element) {
return (element instanceof CPListElement);
}
// ---------- IDialogFieldListener --------
public void dialogFieldChanged(DialogField field) {
sourcePageDialogFieldChanged(field);
}
}
protected void sourcePageDoubleClicked(TreeListDialogField field) {
if (field == fFoldersList) {
List selection= fFoldersList.getSelectedElements();
if (canEdit(selection)) {
editEntry();
}
}
}
protected void sourcePageCustomButtonPressed(DialogField field, int index) {
if (field == fFoldersList) {
if (index == IDX_ADD) {
List elementsToAdd= new ArrayList(10);
if (fCurrJProject.exists()) {
CPListElement[] srcentries= openSourceContainerDialog(null);
if (srcentries != null) {
for (int i= 0; i < srcentries.length; i++) {
elementsToAdd.add(srcentries[i]);
}
}
} else {
CPListElement entry= openNewSourceContainerDialog(null);
if (entry != null) {
elementsToAdd.add(entry);
}
}
if (!elementsToAdd.isEmpty()) {
if (fFoldersList.getSize() == 1) {
CPListElement existing= (CPListElement) fFoldersList.getElement(0);
if (existing.getResource() instanceof IProject) {
askForChangingBuildPathDialog(existing);
}
}
HashSet modifiedElements= new HashSet();
askForAddingExclusionPatternsDialog(elementsToAdd, modifiedElements);
fFoldersList.addElements(elementsToAdd);
fFoldersList.postSetSelection(new StructuredSelection(elementsToAdd));
if (!modifiedElements.isEmpty()) {
for (Iterator iter= modifiedElements.iterator(); iter.hasNext();) {
Object elem= iter.next();
fFoldersList.refresh(elem);
fFoldersList.expandElement(elem, 3);
}
}
}
} else if (index == IDX_EDIT) {
editEntry();
}
}
}
private void editEntry() {
List selElements= fFoldersList.getSelectedElements();
if (selElements.size() != 1) {
return;
}
Object elem= selElements.get(0);
if (fFoldersList.getIndexOfElement(elem) != -1) {
editElementEntry((CPListElement) elem);
} else if (elem instanceof CPListElementAttribute) {
editAttributeEntry((CPListElementAttribute) elem);
}
}
private void editElementEntry(CPListElement elem) {
CPListElement res= null;
IResource resource= elem.getResource();
if (resource.exists()) {
CPListElement[] arr= openSourceContainerDialog(elem);
if (arr != null) {
res= arr[0];
}
} else {
res= openNewSourceContainerDialog(elem);
}
if (res != null) {
fFoldersList.replaceElement(elem, res);
}
}
private void editAttributeEntry(CPListElementAttribute elem) {
String key= elem.getKey();
if (key.equals(CPListElement.OUTPUT)) {
CPListElement selElement= (CPListElement) elem.getParent();
OutputLocationDialog dialog= new OutputLocationDialog(getShell(), selElement);
if (dialog.open() == OutputLocationDialog.OK) {
selElement.setAttribute(CPListElement.OUTPUT, dialog.getOutputLocation());
fFoldersList.refresh();
fClassPathList.dialogFieldChanged(); // validate
}
} else if (key.equals(CPListElement.EXCLUSION)) {
CPListElement selElement= (CPListElement) elem.getParent();
ExclusionPatternDialog dialog= new ExclusionPatternDialog(getShell(), selElement);
if (dialog.open() == OutputLocationDialog.OK) {
selElement.setAttribute(CPListElement.EXCLUSION, dialog.getExclusionPattern());
fFoldersList.refresh();
fClassPathList.dialogFieldChanged(); // validate
}
}
}
protected void sourcePageSelectionChanged(DialogField field) {
List selected= fFoldersList.getSelectedElements();
fFoldersList.enableButton(IDX_EDIT, canEdit(selected));
}
private boolean canEdit(List selElements) {
if (selElements.size() != 1) {
return false;
}
Object elem= selElements.get(0);
if (fFoldersList.getIndexOfElement(elem) != -1) {
return true;
}
if (elem instanceof CPListElementAttribute) {
return true;
}
return false;
}
private void sourcePageDialogFieldChanged(DialogField field) {
if (fCurrJProject == null) {
// not initialized
return;
}
if (field == fUseFolderOutputs) {
if (!fUseFolderOutputs.isSelected()) {
int nFolders= fFoldersList.getSize();
for (int i= 0; i < nFolders; i++) {
CPListElement cpe= (CPListElement) fFoldersList.getElement(i);
cpe.setAttribute(CPListElement.OUTPUT, null);
}
}
fFoldersList.refresh();
} else if (field == fFoldersList) {
updateClasspathList();
}
}
private void updateClasspathList() {
List cpelements= fClassPathList.getElements();
List srcelements= fFoldersList.getElements();
boolean changeDone= false;
CPListElement lastSourceFolder= null;
// backwards, as entries will be deleted
for (int i= cpelements.size() - 1; i >= 0 ; i--) {
CPListElement cpe= (CPListElement)cpelements.get(i);
if (isEntryKind(cpe.getEntryKind())) {
// if it is a source folder, but not one of the accepted entries, remove it
// at the same time, for the entries seen, remove them from the accepted list
if (!srcelements.remove(cpe)) {
cpelements.remove(i);
changeDone= true;
} else if (lastSourceFolder == null) {
lastSourceFolder= cpe;
}
}
}
if (!srcelements.isEmpty()) {
int insertIndex= (lastSourceFolder == null) ? 0 : cpelements.indexOf(lastSourceFolder) + 1;
cpelements.addAll(insertIndex, srcelements);
changeDone= true;
}
if (changeDone) {
fClassPathList.setElements(cpelements);
}
}
private CPListElement openNewSourceContainerDialog(CPListElement existing) {
String title= (existing == null) ? NewWizardMessages.getString("SourceContainerWorkbookPage.NewSourceFolderDialog.new.title") : NewWizardMessages.getString("SourceContainerWorkbookPage.NewSourceFolderDialog.edit.title"); //$NON-NLS-1$ //$NON-NLS-2$
IProject proj= fCurrJProject.getProject();
NewSourceFolderDialog dialog= new NewSourceFolderDialog(getShell(), title, proj, getExistingContainers(existing), existing);
dialog.setMessage(NewWizardMessages.getFormattedString("SourceContainerWorkbookPage.NewSourceFolderDialog.description", fProjPath.toString())); //$NON-NLS-1$
if (dialog.open() == NewContainerDialog.OK) {
IResource folder= dialog.getSourceFolder();
return newCPSourceElement(folder);
}
return null;
}
/**
* Asks to change the output folder to 'proj/bin' when no source folders were existing
*/
private void askForChangingBuildPathDialog(CPListElement existing) {
IPath outputFolder= new Path(fOutputLocationField.getText());
IPath newOutputFolder= null;
String message;
if (outputFolder.segmentCount() == 1) {
String outputFolderName= PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.SRCBIN_BINNAME);
newOutputFolder= outputFolder.append(outputFolderName);
message= NewWizardMessages.getFormattedString("SourceContainerWorkbookPage.ChangeOutputLocationDialog.project_and_output.message", newOutputFolder); //$NON-NLS-1$
} else {
message= NewWizardMessages.getString("SourceContainerWorkbookPage.ChangeOutputLocationDialog.project.message"); //$NON-NLS-1$
}
String title= NewWizardMessages.getString("SourceContainerWorkbookPage.ChangeOutputLocationDialog.title"); //$NON-NLS-1$
if (MessageDialog.openQuestion(getShell(), title, message)) {
fFoldersList.removeElement(existing);
if (newOutputFolder != null) {
fOutputLocationField.setText(newOutputFolder.toString());
}
}
}
private void askForAddingExclusionPatternsDialog(List newEntries, Set modifiedEntries) {
for (int i= 0; i < newEntries.size(); i++) {
CPListElement curr= (CPListElement) newEntries.get(i);
addExclusionPatterns(curr, modifiedEntries);
}
if (!modifiedEntries.isEmpty()) {
String title= NewWizardMessages.getString("SourceContainerWorkbookPage.exclusion_added.title"); //$NON-NLS-1$
String message= NewWizardMessages.getString("SourceContainerWorkbookPage.exclusion_added.message"); //$NON-NLS-1$
MessageDialog.openInformation(getShell(), title, message);
}
}
private void addExclusionPatterns(CPListElement newEntry, Set modifiedEntries) {
IPath entryPath= newEntry.getPath();
List existing= fFoldersList.getElements();
for (int i= 0; i < existing.size(); i++) {
CPListElement curr= (CPListElement) existing.get(i);
IPath currPath= curr.getPath();
if (currPath.isPrefixOf(entryPath)) {
IPath[] exclusionFilters= (IPath[]) curr.getAttribute(CPListElement.EXCLUSION);
if (!JavaModelUtil.isExcludedPath(entryPath, exclusionFilters)) {
IPath pathToExclude= entryPath.removeFirstSegments(currPath.segmentCount()).addTrailingSeparator();
IPath[] newExclusionFilters= new IPath[exclusionFilters.length + 1];
System.arraycopy(exclusionFilters, 0, newExclusionFilters, 0, exclusionFilters.length);
newExclusionFilters[exclusionFilters.length]= pathToExclude;
curr.setAttribute(CPListElement.EXCLUSION, newExclusionFilters);
modifiedEntries.add(curr);
}
}
}
}
private CPListElement[] openSourceContainerDialog(CPListElement existing) {
Class[] acceptedClasses= new Class[] { IProject.class, IFolder.class };
TypedElementSelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, existing == null, getExistingContainers(null));
IProject[] allProjects= fWorkspaceRoot.getProjects();
ArrayList rejectedElements= new ArrayList(allProjects.length);
IProject currProject= fCurrJProject.getProject();
for (int i= 0; i < allProjects.length; i++) {
if (!allProjects[i].equals(currProject)) {
rejectedElements.add(allProjects[i]);
}
}
ViewerFilter filter= new TypedViewerFilter(acceptedClasses, rejectedElements.toArray());
ILabelProvider lp= new WorkbenchLabelProvider();
ITreeContentProvider cp= new WorkbenchContentProvider();
String title= (existing == null) ? NewWizardMessages.getString("SourceContainerWorkbookPage.ExistingSourceFolderDialog.new.title") : NewWizardMessages.getString("SourceContainerWorkbookPage.ExistingSourceFolderDialog.edit.title"); //$NON-NLS-1$ //$NON-NLS-2$
String message= (existing == null) ? NewWizardMessages.getString("SourceContainerWorkbookPage.ExistingSourceFolderDialog.new.description") : NewWizardMessages.getString("SourceContainerWorkbookPage.ExistingSourceFolderDialog.edit.description"); //$NON-NLS-1$ //$NON-NLS-2$
FolderSelectionDialog dialog= new FolderSelectionDialog(getShell(), lp, cp);
dialog.setValidator(validator);
dialog.setTitle(title);
dialog.setMessage(message);
dialog.addFilter(filter);
dialog.setInput(fCurrJProject.getProject().getParent());
dialog.setSorter(new ResourceSorter(ResourceSorter.NAME));
if (existing == null) {
dialog.setInitialSelection(fCurrJProject.getProject());
} else {
dialog.setInitialSelection(existing.getResource());
}
if (dialog.open() == FolderSelectionDialog.OK) {
Object[] elements= dialog.getResult();
CPListElement[] res= new CPListElement[elements.length];
for (int i= 0; i < res.length; i++) {
IResource elem= (IResource)elements[i];
res[i]= newCPSourceElement(elem);
}
return res;
}
return null;
}
private List getExistingContainers(CPListElement existing) {
List res= new ArrayList();
List cplist= fFoldersList.getElements();
for (int i= 0; i < cplist.size(); i++) {
CPListElement elem= (CPListElement)cplist.get(i);
if (elem != existing) {
IResource resource= elem.getResource();
if (resource instanceof IContainer) { // defensive code
res.add(resource);
}
}
}
return res;
}
private CPListElement newCPSourceElement(IResource res) {
Assert.isNotNull(res);
return new CPListElement(fCurrJProject, IClasspathEntry.CPE_SOURCE, res.getFullPath(), res);
}
/*
* @see BuildPathBasePage#getSelection
*/
public List getSelection() {
return fFoldersList.getSelectedElements();
}
/*
* @see BuildPathBasePage#setSelection
*/
public void setSelection(List selElements) {
fFoldersList.selectElements(new StructuredSelection(selElements));
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.wizards.buildpaths.BuildPathBasePage#isEntryKind(int)
*/
public boolean isEntryKind(int kind) {
return kind == IClasspathEntry.CPE_SOURCE;
}
}
|
25,291 |
Bug 25291 Can't browse JRE_LIB jar file when working set selected
|
I found that when I was using a working set I couldn't expand the JRE_LIB jar file in the package explorer. When I deselected the working set, it worked fine.
|
resolved fixed
|
1791872
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-21T09:15:24Z | 2002-10-24T03:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/workingsets/WorkingSetFilter.java
| |
29,848 |
Bug 29848 Add Javadoc Comment creates incorrect declaration [javadoc]
|
Create a subclass of TransferHandler. Override canImport. The Javadoc comment generated is "@see javax.swing.TransferHandler#canImport (javax.swing.JComponent, java.awt.datatransfer.DataFlavor)", but it shuold be "@see javax.swing.TransferHandler#canImport(javax.swing.JComponent, java.awt.datatransfer.DataFlavor [])" - note the missing [] on the second parameter.
|
resolved fixed
|
cbac6e0
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-21T11:25:02Z | 2003-01-20T22:00:00Z |
org.eclipse.jdt.ui/core
| |
29,848 |
Bug 29848 Add Javadoc Comment creates incorrect declaration [javadoc]
|
Create a subclass of TransferHandler. Override canImport. The Javadoc comment generated is "@see javax.swing.TransferHandler#canImport (javax.swing.JComponent, java.awt.datatransfer.DataFlavor)", but it shuold be "@see javax.swing.TransferHandler#canImport(javax.swing.JComponent, java.awt.datatransfer.DataFlavor [])" - note the missing [] on the second parameter.
|
resolved fixed
|
cbac6e0
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-21T11:25:02Z | 2003-01-20T22:00:00Z |
extension/org/eclipse/jdt/internal/corext/codemanipulation/StubUtility.java
| |
18,568 |
Bug 18568 api: IType::getMethod - how to distinguish constructors in this case?
|
it is legal to have both a constructor and a method with the same signature however, IType::getMethod does lot let me distinguish between the 2 cases given this code: class A { public A() {} protected void A() {} } call to IType::getMethod("A", new String[0]) returns the constructor (and it does, as suspected, return the method if i revert them in the source file :-) ) i think a new method on IType IMethod getMethod(String name, String[] parameterTypeSignatures, boolean constructor); would solve this problem
|
resolved wontfix
|
fc625ee
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-22T15:42:37Z | 2002-06-01T08:26:40Z |
org.eclipse.jdt.ui/core
| |
18,568 |
Bug 18568 api: IType::getMethod - how to distinguish constructors in this case?
|
it is legal to have both a constructor and a method with the same signature however, IType::getMethod does lot let me distinguish between the 2 cases given this code: class A { public A() {} protected void A() {} } call to IType::getMethod("A", new String[0]) returns the constructor (and it does, as suspected, return the method if i revert them in the source file :-) ) i think a new method on IType IMethod getMethod(String name, String[] parameterTypeSignatures, boolean constructor); would solve this problem
|
resolved wontfix
|
fc625ee
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-22T15:42:37Z | 2002-06-01T08:26:40Z |
extension/org/eclipse/jdt/internal/corext/util/JavaModelUtil.java
| |
29,996 |
Bug 29996 Java Browsing perspective is missing the Resource Navigation action set
|
build I20030115 The Java Browsing perspective is missing the Resource Navigation action set, although the Java perspective uses it. Just wondering if this was by design.
|
resolved fixed
|
6ee1f2e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-23T08:32:44Z | 2003-01-22T15:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/browsing/JavaBrowsingPerspectiveFactory.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.browsing;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPerspectiveFactory;
import org.eclipse.ui.IPlaceholderFolderLayout;
import org.eclipse.debug.ui.IDebugUIConstants;
import org.eclipse.search.ui.SearchUI;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
public class JavaBrowsingPerspectiveFactory implements IPerspectiveFactory {
/*
* XXX: This is a workaround for: http://dev.eclipse.org/bugs/show_bug.cgi?id=13070
*/
static IJavaElement fgJavaElementFromAction;
/**
* Constructs a new Default layout engine.
*/
public JavaBrowsingPerspectiveFactory() {
super();
}
public void createInitialLayout(IPageLayout layout) {
if (stackBrowsingViewsVertically())
createVerticalLayout(layout);
else
createHorizontalLayout(layout);
// action sets
layout.addActionSet(IDebugUIConstants.LAUNCH_ACTION_SET);
layout.addActionSet(JavaUI.ID_ACTION_SET);
layout.addActionSet(JavaUI.ID_ELEMENT_CREATION_ACTION_SET);
// views - java
layout.addShowViewShortcut(JavaUI.ID_TYPE_HIERARCHY);
// views - search
layout.addShowViewShortcut(SearchUI.SEARCH_RESULT_VIEW_ID);
// views - debugging
layout.addShowViewShortcut(IDebugUIConstants.ID_CONSOLE_VIEW);
// views - standard workbench
layout.addShowViewShortcut(IPageLayout.ID_OUTLINE);
layout.addShowViewShortcut(IPageLayout.ID_TASK_LIST);
layout.addShowViewShortcut(IPageLayout.ID_RES_NAV);
// new actions - Java project creation wizard
layout.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewPackageCreationWizard"); //$NON-NLS-1$
layout.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewClassCreationWizard"); //$NON-NLS-1$
layout.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewInterfaceCreationWizard"); //$NON-NLS-1$
layout.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewSnippetCreationWizard"); //$NON-NLS-1$
}
private void createVerticalLayout(IPageLayout layout) {
String relativePartId= IPageLayout.ID_EDITOR_AREA;
int relativePos= IPageLayout.LEFT;
IPlaceholderFolderLayout placeHolderLeft= layout.createPlaceholderFolder("left", IPageLayout.LEFT, (float)0.25, IPageLayout.ID_EDITOR_AREA); //$NON-NLS-1$
placeHolderLeft.addPlaceholder(JavaUI.ID_TYPE_HIERARCHY);
placeHolderLeft.addPlaceholder(IPageLayout.ID_OUTLINE);
placeHolderLeft.addPlaceholder(JavaUI.ID_PACKAGES);
placeHolderLeft.addPlaceholder(IPageLayout.ID_RES_NAV);
if (shouldShowProjectsView()) {
layout.addView(JavaUI.ID_PROJECTS_VIEW, IPageLayout.LEFT, (float)0.25, IPageLayout.ID_EDITOR_AREA);
relativePartId= JavaUI.ID_PROJECTS_VIEW;
relativePos= IPageLayout.BOTTOM;
}
if (shouldShowPackagesView()) {
layout.addView(JavaUI.ID_PACKAGES_VIEW, relativePos, (float)0.25, relativePartId);
relativePartId= JavaUI.ID_PACKAGES_VIEW;
relativePos= IPageLayout.BOTTOM;
}
layout.addView(JavaUI.ID_TYPES_VIEW, relativePos, (float)0.33, relativePartId);
layout.addView(JavaUI.ID_MEMBERS_VIEW, IPageLayout.BOTTOM, (float)0.50, JavaUI.ID_TYPES_VIEW);
IPlaceholderFolderLayout placeHolderBottom= layout.createPlaceholderFolder("bottom", IPageLayout.BOTTOM, (float)0.75, IPageLayout.ID_EDITOR_AREA); //$NON-NLS-1$
placeHolderBottom.addPlaceholder(IPageLayout.ID_TASK_LIST);
placeHolderBottom.addPlaceholder(SearchUI.SEARCH_RESULT_VIEW_ID);
placeHolderBottom.addPlaceholder(IDebugUIConstants.ID_CONSOLE_VIEW);
placeHolderBottom.addPlaceholder(IPageLayout.ID_BOOKMARKS);
}
private void createHorizontalLayout(IPageLayout layout) {
String relativePartId= IPageLayout.ID_EDITOR_AREA;
int relativePos= IPageLayout.TOP;
if (shouldShowProjectsView()) {
layout.addView(JavaUI.ID_PROJECTS_VIEW, IPageLayout.TOP, (float)0.25, IPageLayout.ID_EDITOR_AREA);
relativePartId= JavaUI.ID_PROJECTS_VIEW;
relativePos= IPageLayout.RIGHT;
}
if (shouldShowPackagesView()) {
layout.addView(JavaUI.ID_PACKAGES_VIEW, relativePos, (float)0.25, relativePartId);
relativePartId= JavaUI.ID_PACKAGES_VIEW;
relativePos= IPageLayout.RIGHT;
}
layout.addView(JavaUI.ID_TYPES_VIEW, relativePos, (float)0.33, relativePartId);
layout.addView(JavaUI.ID_MEMBERS_VIEW, IPageLayout.RIGHT, (float)0.50, JavaUI.ID_TYPES_VIEW);
IPlaceholderFolderLayout placeHolderLeft= layout.createPlaceholderFolder("left", IPageLayout.LEFT, (float)0.25, IPageLayout.ID_EDITOR_AREA); //$NON-NLS-1$
placeHolderLeft.addPlaceholder(JavaUI.ID_TYPE_HIERARCHY);
placeHolderLeft.addPlaceholder(IPageLayout.ID_OUTLINE);
placeHolderLeft.addPlaceholder(JavaUI.ID_PACKAGES);
placeHolderLeft.addPlaceholder(IPageLayout.ID_RES_NAV);
IPlaceholderFolderLayout placeHolderBottom= layout.createPlaceholderFolder("bottom", IPageLayout.BOTTOM, (float)0.75, IPageLayout.ID_EDITOR_AREA); //$NON-NLS-1$
placeHolderBottom.addPlaceholder(IPageLayout.ID_TASK_LIST);
placeHolderBottom.addPlaceholder(SearchUI.SEARCH_RESULT_VIEW_ID);
placeHolderBottom.addPlaceholder(IDebugUIConstants.ID_CONSOLE_VIEW);
placeHolderBottom.addPlaceholder(IPageLayout.ID_BOOKMARKS);
}
private boolean shouldShowProjectsView() {
return fgJavaElementFromAction == null || fgJavaElementFromAction.getElementType() == IJavaElement.JAVA_MODEL;
}
private boolean shouldShowPackagesView() {
if (fgJavaElementFromAction == null)
return true;
int type= fgJavaElementFromAction.getElementType();
return type == IJavaElement.JAVA_MODEL || type == IJavaElement.JAVA_PROJECT || type == IJavaElement.PACKAGE_FRAGMENT_ROOT;
}
private boolean stackBrowsingViewsVertically() {
return PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.BROWSING_STACK_VERTICALLY);
}
/*
* XXX: This is a workaround for: http://dev.eclipse.org/bugs/show_bug.cgi?id=13070
*/
static void setInputFromAction(IAdaptable input) {
if (input instanceof IJavaElement)
fgJavaElementFromAction= (IJavaElement)input;
else
fgJavaElementFromAction= null;
}
}
|
30,005 |
Bug 30005 Can't create linked source folder in new java project wizard [build path]
|
Build: I20030122 1) Open the new java project wizard 2) Enter a name, hit next 3) Click "Add Folder" on the "Source" tab. -> dialog comes up that doesn't have an option to create a new folder 4) Click cancel. Click "Browse" next to the output folder field -> this dialog allows you to create a new folder (even a linked folder) 5) Click cancel. Finish the wizard. 6) Open the java build path property page 3) Click "Add Folder" on the "Source" tab. -> now the dialog allows you to create a new linked folder. It should allow you to do this from the wizard.
|
resolved fixed
|
844dc6a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-23T09:25:43Z | 2003-01-22T18:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/BuildPathsBlock.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.wizards.buildpaths;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.dialogs.ISelectionStatusValidator;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.model.WorkbenchContentProvider;
import org.eclipse.ui.model.WorkbenchLabelProvider;
import org.eclipse.ui.views.navigator.ResourceSorter;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaModelStatus;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaConventions;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.dialogs.StatusUtil;
import org.eclipse.jdt.internal.ui.util.CoreUtility;
import org.eclipse.jdt.internal.ui.util.PixelConverter;
import org.eclipse.jdt.internal.ui.util.TabFolderLayout;
import org.eclipse.jdt.internal.ui.viewsupport.ImageDisposer;
import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener;
import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages;
import org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator;
import org.eclipse.jdt.internal.ui.wizards.TypedViewerFilter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.CheckedListDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField;
public class BuildPathsBlock {
public static interface IRemoveOldBinariesQuery {
/**
* Do the callback. Returns <code>true</code> if .class files should be removed from the
* old output location.
*/
boolean doQuery(IPath oldOutputLocation) throws InterruptedException;
}
private IWorkspaceRoot fWorkspaceRoot;
private CheckedListDialogField fClassPathList;
private StringButtonDialogField fBuildPathDialogField;
private StatusInfo fClassPathStatus;
private StatusInfo fOutputFolderStatus;
private StatusInfo fBuildPathStatus;
private IJavaProject fCurrJProject;
private IPath fOutputLocationPath;
private IStatusChangeListener fContext;
private Control fSWTWidget;
private int fPageIndex;
private SourceContainerWorkbookPage fSourceContainerPage;
private ProjectsWorkbookPage fProjectsPage;
private LibrariesWorkbookPage fLibrariesPage;
private BuildPathBasePage fCurrPage;
public BuildPathsBlock(IStatusChangeListener context, int pageToShow) {
fWorkspaceRoot= JavaPlugin.getWorkspace().getRoot();
fContext= context;
fPageIndex= pageToShow;
fSourceContainerPage= null;
fLibrariesPage= null;
fProjectsPage= null;
fCurrPage= null;
BuildPathAdapter adapter= new BuildPathAdapter();
String[] buttonLabels= new String[] {
/* 0 */ NewWizardMessages.getString("BuildPathsBlock.classpath.up.button"), //$NON-NLS-1$
/* 1 */ NewWizardMessages.getString("BuildPathsBlock.classpath.down.button"), //$NON-NLS-1$
/* 2 */ null,
/* 3 */ NewWizardMessages.getString("BuildPathsBlock.classpath.checkall.button"), //$NON-NLS-1$
/* 4 */ NewWizardMessages.getString("BuildPathsBlock.classpath.uncheckall.button") //$NON-NLS-1$
};
fClassPathList= new CheckedListDialogField(null, buttonLabels, new CPListLabelProvider());
fClassPathList.setDialogFieldListener(adapter);
fClassPathList.setLabelText(NewWizardMessages.getString("BuildPathsBlock.classpath.label")); //$NON-NLS-1$
fClassPathList.setUpButtonIndex(0);
fClassPathList.setDownButtonIndex(1);
fClassPathList.setCheckAllButtonIndex(3);
fClassPathList.setUncheckAllButtonIndex(4);
fBuildPathDialogField= new StringButtonDialogField(adapter);
fBuildPathDialogField.setButtonLabel(NewWizardMessages.getString("BuildPathsBlock.buildpath.button")); //$NON-NLS-1$
fBuildPathDialogField.setDialogFieldListener(adapter);
fBuildPathDialogField.setLabelText(NewWizardMessages.getString("BuildPathsBlock.buildpath.label")); //$NON-NLS-1$
fBuildPathStatus= new StatusInfo();
fClassPathStatus= new StatusInfo();
fOutputFolderStatus= new StatusInfo();
fCurrJProject= null;
}
// -------- UI creation ---------
public Control createControl(Composite parent) {
fSWTWidget= parent;
PixelConverter converter= new PixelConverter(parent);
Composite composite= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
layout.marginWidth= 0;
layout.numColumns= 1;
composite.setLayout(layout);
TabFolder folder= new TabFolder(composite, SWT.NONE);
folder.setLayout(new TabFolderLayout());
folder.setLayoutData(new GridData(GridData.FILL_BOTH));
ImageRegistry imageRegistry= JavaPlugin.getDefault().getImageRegistry();
TabItem item;
fSourceContainerPage= new SourceContainerWorkbookPage(fWorkspaceRoot, fClassPathList, fBuildPathDialogField);
item= new TabItem(folder, SWT.NONE);
item.setText(NewWizardMessages.getString("BuildPathsBlock.tab.source")); //$NON-NLS-1$
item.setImage(imageRegistry.get(JavaPluginImages.IMG_OBJS_PACKFRAG_ROOT));
item.setData(fSourceContainerPage);
item.setControl(fSourceContainerPage.getControl(folder));
IWorkbench workbench= JavaPlugin.getDefault().getWorkbench();
Image projectImage= workbench.getSharedImages().getImage(ISharedImages.IMG_OBJ_PROJECT);
fProjectsPage= new ProjectsWorkbookPage(fClassPathList);
item= new TabItem(folder, SWT.NONE);
item.setText(NewWizardMessages.getString("BuildPathsBlock.tab.projects")); //$NON-NLS-1$
item.setImage(projectImage);
item.setData(fProjectsPage);
item.setControl(fProjectsPage.getControl(folder));
fLibrariesPage= new LibrariesWorkbookPage(fWorkspaceRoot, fClassPathList);
item= new TabItem(folder, SWT.NONE);
item.setText(NewWizardMessages.getString("BuildPathsBlock.tab.libraries")); //$NON-NLS-1$
item.setImage(imageRegistry.get(JavaPluginImages.IMG_OBJS_LIBRARY));
item.setData(fLibrariesPage);
item.setControl(fLibrariesPage.getControl(folder));
// a non shared image
Image cpoImage= JavaPluginImages.DESC_TOOL_CLASSPATH_ORDER.createImage();
composite.addDisposeListener(new ImageDisposer(cpoImage));
ClasspathOrderingWorkbookPage ordpage= new ClasspathOrderingWorkbookPage(fClassPathList);
item= new TabItem(folder, SWT.NONE);
item.setText(NewWizardMessages.getString("BuildPathsBlock.tab.order")); //$NON-NLS-1$
item.setImage(cpoImage);
item.setData(ordpage);
item.setControl(ordpage.getControl(folder));
if (fCurrJProject != null) {
fSourceContainerPage.init(fCurrJProject);
fLibrariesPage.init(fCurrJProject);
fProjectsPage.init(fCurrJProject);
}
Composite editorcomp= new Composite(composite, SWT.NONE);
DialogField[] editors= new DialogField[] { fBuildPathDialogField };
LayoutUtil.doDefaultLayout(editorcomp, editors, true, 0, 0);
int maxFieldWidth= converter.convertWidthInCharsToPixels(40);
LayoutUtil.setWidthHint(fBuildPathDialogField.getTextControl(null), maxFieldWidth);
LayoutUtil.setHorizontalGrabbing(fBuildPathDialogField.getTextControl(null));
editorcomp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
folder.setSelection(fPageIndex);
fCurrPage= (BuildPathBasePage) folder.getItem(fPageIndex).getData();
folder.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
tabChanged(e.item);
}
});
WorkbenchHelp.setHelp(composite, IJavaHelpContextIds.BUILD_PATH_BLOCK);
return composite;
}
private Shell getShell() {
if (fSWTWidget != null) {
return fSWTWidget.getShell();
}
return JavaPlugin.getActiveWorkbenchShell();
}
/**
* Initializes the classpath for the given project. Multiple calls to init are allowed,
* but all existing settings will be cleared and replace by the given or default paths.
* @param project The java project to configure. Does not have to exist.
* @param outputLocation The output location to be set in the page. If <code>null</code>
* is passed, jdt default settings are used, or - if the project is an existing Java project- the
* output location of the existing project
* @param classpathEntries The classpath entries to be set in the page. If <code>null</code>
* is passed, jdt default settings are used, or - if the project is an existing Java project - the
* classpath entries of the existing project
*/
public void init(IJavaProject jproject, IPath outputLocation, IClasspathEntry[] classpathEntries) {
fCurrJProject= jproject;
boolean projectExists= false;
List newClassPath= null;
try {
IProject project= fCurrJProject.getProject();
projectExists= (project.exists() && project.getFile(".classpath").exists()); //$NON-NLS-1$
if (projectExists) {
if (outputLocation == null) {
outputLocation= fCurrJProject.getOutputLocation();
}
if (classpathEntries == null) {
classpathEntries= fCurrJProject.getRawClasspath();
}
}
if (outputLocation == null) {
outputLocation= getDefaultBuildPath(jproject);
}
if (classpathEntries != null) {
newClassPath= getExistingEntries(classpathEntries);
}
} catch (CoreException e) {
JavaPlugin.log(e);
}
if (newClassPath == null) {
newClassPath= getDefaultClassPath(jproject);
}
List exportedEntries = new ArrayList();
for (int i= 0; i < newClassPath.size(); i++) {
CPListElement curr= (CPListElement) newClassPath.get(i);
if (curr.isExported() || curr.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
exportedEntries.add(curr);
}
}
// inits the dialog field
fBuildPathDialogField.setText(outputLocation.makeRelative().toString());
fBuildPathDialogField.enableButton(fCurrJProject.exists());
fClassPathList.setElements(newClassPath);
fClassPathList.setCheckedElements(exportedEntries);
if (fSourceContainerPage != null) {
fSourceContainerPage.init(fCurrJProject);
fProjectsPage.init(fCurrJProject);
fLibrariesPage.init(fCurrJProject);
}
doStatusLineUpdate();
}
private ArrayList getExistingEntries(IClasspathEntry[] classpathEntries) {
ArrayList newClassPath= new ArrayList();
for (int i= 0; i < classpathEntries.length; i++) {
IClasspathEntry curr= classpathEntries[i];
newClassPath.add(CPListElement.createFromExisting(curr, fCurrJProject));
}
return newClassPath;
}
// -------- public api --------
/**
* Returns the Java project. Can return <code>null<code> if the page has not
* been initialized.
*/
public IJavaProject getJavaProject() {
return fCurrJProject;
}
/**
* Returns the current output location. Note that the path returned must not be valid.
*/
public IPath getOutputLocation() {
return new Path(fBuildPathDialogField.getText()).makeAbsolute();
}
/**
* Returns the current class path (raw). Note that the entries returned must not be valid.
*/
public IClasspathEntry[] getRawClassPath() {
List elements= fClassPathList.getElements();
int nElements= elements.size();
IClasspathEntry[] entries= new IClasspathEntry[elements.size()];
for (int i= 0; i < nElements; i++) {
CPListElement currElement= (CPListElement) elements.get(i);
entries[i]= currElement.getClasspathEntry();
}
return entries;
}
public int getPageIndex() {
return fPageIndex;
}
// -------- evaluate default settings --------
private List getDefaultClassPath(IJavaProject jproj) {
List list= new ArrayList();
IResource srcFolder;
IPreferenceStore store= PreferenceConstants.getPreferenceStore();
String sourceFolderName= store.getString(PreferenceConstants.SRCBIN_SRCNAME);
if (store.getBoolean(PreferenceConstants.SRCBIN_FOLDERS_IN_NEWPROJ) && sourceFolderName.length() > 0) {
srcFolder= jproj.getProject().getFolder(sourceFolderName);
} else {
srcFolder= jproj.getProject();
}
list.add(new CPListElement(jproj, IClasspathEntry.CPE_SOURCE, srcFolder.getFullPath(), srcFolder));
IClasspathEntry[] jreEntries= PreferenceConstants.getDefaultJRELibrary();
list.addAll(getExistingEntries(jreEntries));
return list;
}
private IPath getDefaultBuildPath(IJavaProject jproj) {
IPreferenceStore store= PreferenceConstants.getPreferenceStore();
if (store.getBoolean(PreferenceConstants.SRCBIN_FOLDERS_IN_NEWPROJ)) {
String outputLocationName= store.getString(PreferenceConstants.SRCBIN_BINNAME);
return jproj.getProject().getFullPath().append(outputLocationName);
} else {
return jproj.getProject().getFullPath();
}
}
private class BuildPathAdapter implements IStringButtonAdapter, IDialogFieldListener {
// -------- IStringButtonAdapter --------
public void changeControlPressed(DialogField field) {
buildPathChangeControlPressed(field);
}
// ---------- IDialogFieldListener --------
public void dialogFieldChanged(DialogField field) {
buildPathDialogFieldChanged(field);
}
}
private void buildPathChangeControlPressed(DialogField field) {
if (field == fBuildPathDialogField) {
IContainer container= chooseContainer();
if (container != null) {
fBuildPathDialogField.setText(container.getFullPath().toString());
}
}
}
private void buildPathDialogFieldChanged(DialogField field) {
if (field == fClassPathList) {
updateClassPathStatus();
} else if (field == fBuildPathDialogField) {
updateOutputLocationStatus();
}
doStatusLineUpdate();
}
// -------- verification -------------------------------
private void doStatusLineUpdate() {
IStatus res= findMostSevereStatus();
fContext.statusChanged(res);
}
private IStatus findMostSevereStatus() {
return StatusUtil.getMostSevere(new IStatus[] { fClassPathStatus, fOutputFolderStatus, fBuildPathStatus });
}
/**
* Validates the build path.
*/
public void updateClassPathStatus() {
fClassPathStatus.setOK();
List elements= fClassPathList.getElements();
CPListElement entryMissing= null;
int nEntriesMissing= 0;
IClasspathEntry[] entries= new IClasspathEntry[elements.size()];
for (int i= elements.size()-1 ; i >= 0 ; i--) {
CPListElement currElement= (CPListElement)elements.get(i);
boolean isChecked= fClassPathList.isChecked(currElement);
if (currElement.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
if (!isChecked) {
fClassPathList.setCheckedWithoutUpdate(currElement, true);
}
} else {
currElement.setExported(isChecked);
}
entries[i]= currElement.getClasspathEntry();
if (currElement.isMissing()) {
nEntriesMissing++;
if (entryMissing == null) {
entryMissing= currElement;
}
}
}
if (nEntriesMissing > 0) {
if (nEntriesMissing == 1) {
fClassPathStatus.setWarning(NewWizardMessages.getFormattedString("BuildPathsBlock.warning.EntryMissing", entryMissing.getPath().toString())); //$NON-NLS-1$
} else {
fClassPathStatus.setWarning(NewWizardMessages.getFormattedString("BuildPathsBlock.warning.EntriesMissing", String.valueOf(nEntriesMissing))); //$NON-NLS-1$
}
}
/* if (fCurrJProject.hasClasspathCycle(entries)) {
fClassPathStatus.setWarning(NewWizardMessages.getString("BuildPathsBlock.warning.CycleInClassPath")); //$NON-NLS-1$
}
*/
updateBuildPathStatus();
}
/**
* Validates output location & build path.
*/
private void updateOutputLocationStatus() {
fOutputLocationPath= null;
String text= fBuildPathDialogField.getText();
if ("".equals(text)) { //$NON-NLS-1$
fOutputFolderStatus.setError(NewWizardMessages.getString("BuildPathsBlock.error.EnterBuildPath")); //$NON-NLS-1$
return;
}
IPath path= getOutputLocation();
fOutputLocationPath= path;
IResource res= fWorkspaceRoot.findMember(path);
if (res != null) {
// if exists, must be a folder or project
if (res.getType() == IResource.FILE) {
fOutputFolderStatus.setError(NewWizardMessages.getString("BuildPathsBlock.error.InvalidBuildPath")); //$NON-NLS-1$
return;
}
}
fOutputFolderStatus.setOK();
updateBuildPathStatus();
}
private void updateBuildPathStatus() {
List elements= fClassPathList.getElements();
IClasspathEntry[] entries= new IClasspathEntry[elements.size()];
for (int i= elements.size()-1 ; i >= 0 ; i--) {
CPListElement currElement= (CPListElement)elements.get(i);
entries[i]= currElement.getClasspathEntry();
}
IJavaModelStatus status= JavaConventions.validateClasspath(fCurrJProject, entries, fOutputLocationPath);
if (!status.isOK()) {
fBuildPathStatus.setError(status.getMessage());
return;
}
fBuildPathStatus.setOK();
}
// -------- creation -------------------------------
public static void createProject(IProject project, IPath locationPath, IProgressMonitor monitor) throws CoreException {
if (monitor == null) {
monitor= new NullProgressMonitor();
}
monitor.beginTask(NewWizardMessages.getString("BuildPathsBlock.operationdesc_project"), 10); //$NON-NLS-1$
// create the project
try {
if (!project.exists()) {
IProjectDescription desc= project.getWorkspace().newProjectDescription(project.getName());
if (Platform.getLocation().equals(locationPath)) {
locationPath= null;
}
desc.setLocation(locationPath);
project.create(desc, monitor);
monitor= null;
}
if (!project.isOpen()) {
project.open(monitor);
monitor= null;
}
} finally {
if (monitor != null) {
monitor.done();
}
}
}
public static void addJavaNature(IProject project, IProgressMonitor monitor) throws CoreException {
if (!project.hasNature(JavaCore.NATURE_ID)) {
IProjectDescription description = project.getDescription();
String[] prevNatures= description.getNatureIds();
String[] newNatures= new String[prevNatures.length + 1];
System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length);
newNatures[prevNatures.length]= JavaCore.NATURE_ID;
description.setNatureIds(newNatures);
project.setDescription(description, monitor);
} else {
monitor.worked(1);
}
}
public void configureJavaProject(IProgressMonitor monitor) throws CoreException, InterruptedException {
if (monitor == null) {
monitor= new NullProgressMonitor();
}
monitor.beginTask(NewWizardMessages.getString("BuildPathsBlock.operationdesc_java"), 10); //$NON-NLS-1$
try {
Shell shell= null;
if (fSWTWidget != null && !fSWTWidget.getShell().isDisposed()) {
shell= fSWTWidget.getShell();
}
internalConfigureJavaProject(fClassPathList.getElements(), getOutputLocation(), shell, monitor);
} finally {
monitor.done();
}
}
/**
* Creates the Java project and sets the configured build path and output location.
* If the project already exists only build paths are updated.
*/
private void internalConfigureJavaProject(List classPathEntries, IPath outputLocation, Shell shell, IProgressMonitor monitor) throws CoreException, InterruptedException {
// 10 monitor steps to go
IRemoveOldBinariesQuery reorgQuery= null;
if (shell != null) {
reorgQuery= getRemoveOldBinariesQuery(shell);
}
// remove old .class files
if (reorgQuery != null) {
IPath oldOutputLocation= fCurrJProject.getOutputLocation();
if (!outputLocation.equals(oldOutputLocation)) {
IResource res= fWorkspaceRoot.findMember(oldOutputLocation);
if (res instanceof IContainer && hasClassfiles(res)) {
if (reorgQuery.doQuery(oldOutputLocation)) {
removeOldClassfiles(res);
}
}
}
}
// create and set the output path first
if (!fWorkspaceRoot.exists(outputLocation)) {
IFolder folder= fWorkspaceRoot.getFolder(outputLocation);
CoreUtility.createFolder(folder, true, true, null);
}
monitor.worked(2);
int nEntries= classPathEntries.size();
IClasspathEntry[] classpath= new IClasspathEntry[nEntries];
// create and set the class path
for (int i= 0; i < nEntries; i++) {
CPListElement entry= ((CPListElement)classPathEntries.get(i));
IResource res= entry.getResource();
if ((res instanceof IFolder) && !res.exists()) {
CoreUtility.createFolder((IFolder)res, true, true, null);
}
if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
IPath folderOutput= (IPath) entry.getAttribute(CPListElement.OUTPUT);
if (folderOutput != null && folderOutput.segmentCount() > 1) {
IFolder folder= fWorkspaceRoot.getFolder(folderOutput);
CoreUtility.createFolder((IFolder)folder, true, true, null);
}
}
classpath[i]= entry.getClasspathEntry();
// set javadoc location
configureJavaDoc(entry);
}
monitor.worked(1);
fCurrJProject.setRawClasspath(classpath, outputLocation, new SubProgressMonitor(monitor, 7));
}
private void configureJavaDoc(CPListElement entry) {
if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
URL javadocLocation= (URL) entry.getAttribute(CPListElement.JAVADOC);
IPath path= entry.getPath();
if (entry.getEntryKind() == IClasspathEntry.CPE_VARIABLE) {
path= JavaCore.getResolvedVariablePath(path);
}
if (path != null) {
JavaUI.setLibraryJavadocLocation(path, javadocLocation);
}
} else if (entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
Object[] children= entry.getChildren(false);
for (int i= 0; i < children.length; i++) {
CPListElement curr= (CPListElement) children[i];
configureJavaDoc(curr);
}
}
}
public static boolean hasClassfiles(IResource resource) throws CoreException {
if (resource.isDerived()) { //$NON-NLS-1$
return true;
}
if (resource instanceof IContainer) {
IResource[] members= ((IContainer) resource).members();
for (int i= 0; i < members.length; i++) {
if (hasClassfiles(members[i])) {
return true;
}
}
}
return false;
}
public static void removeOldClassfiles(IResource resource) throws CoreException {
if (resource.isDerived()) {
resource.delete(false, null);
} else if (resource instanceof IContainer) {
IResource[] members= ((IContainer) resource).members();
for (int i= 0; i < members.length; i++) {
removeOldClassfiles(members[i]);
}
}
}
public static IRemoveOldBinariesQuery getRemoveOldBinariesQuery(final Shell shell) {
return new IRemoveOldBinariesQuery() {
public boolean doQuery(final IPath oldOutputLocation) throws InterruptedException {
final int[] res= new int[] { 1 };
shell.getDisplay().syncExec(new Runnable() {
public void run() {
String title= NewWizardMessages.getString("BuildPathsBlock.RemoveBinariesDialog.title"); //$NON-NLS-1$
String message= NewWizardMessages.getFormattedString("BuildPathsBlock.RemoveBinariesDialog.description", oldOutputLocation.toString()); //$NON-NLS-1$
MessageDialog dialog= new MessageDialog(shell, title, null, message, MessageDialog.QUESTION, new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL }, 2);
res[0]= dialog.open();
}
});
if (res[0] == 0) {
return true;
} else if (res[0] == 1) {
return false;
}
throw new InterruptedException();
}
};
}
// ---------- util method ------------
private IContainer chooseContainer() {
Class[] acceptedClasses= new Class[] { IProject.class, IFolder.class };
ISelectionStatusValidator validator= new TypedElementSelectionValidator(acceptedClasses, false);
IProject[] allProjects= fWorkspaceRoot.getProjects();
ArrayList rejectedElements= new ArrayList(allProjects.length);
IProject currProject= fCurrJProject.getProject();
for (int i= 0; i < allProjects.length; i++) {
if (!allProjects[i].equals(currProject)) {
rejectedElements.add(allProjects[i]);
}
}
ViewerFilter filter= new TypedViewerFilter(acceptedClasses, rejectedElements.toArray());
ILabelProvider lp= new WorkbenchLabelProvider();
ITreeContentProvider cp= new WorkbenchContentProvider();
IResource initSelection= null;
if (fOutputLocationPath != null) {
initSelection= fWorkspaceRoot.findMember(fOutputLocationPath);
}
FolderSelectionDialog dialog= new FolderSelectionDialog(getShell(), lp, cp);
dialog.setTitle(NewWizardMessages.getString("BuildPathsBlock.ChooseOutputFolderDialog.title")); //$NON-NLS-1$
dialog.setValidator(validator);
dialog.setMessage(NewWizardMessages.getString("BuildPathsBlock.ChooseOutputFolderDialog.description")); //$NON-NLS-1$
dialog.addFilter(filter);
dialog.setInput(fWorkspaceRoot);
dialog.setInitialSelection(initSelection);
dialog.setSorter(new ResourceSorter(ResourceSorter.NAME));
if (dialog.open() == FolderSelectionDialog.OK) {
return (IContainer)dialog.getFirstResult();
}
return null;
}
// -------- tab switching ----------
private void tabChanged(Widget widget) {
if (widget instanceof TabItem) {
TabItem tabItem= (TabItem) widget;
BuildPathBasePage newPage= (BuildPathBasePage) tabItem.getData();
if (fCurrPage != null) {
List selection= fCurrPage.getSelection();
if (!selection.isEmpty()) {
newPage.setSelection(selection);
}
}
fCurrPage= newPage;
fPageIndex= tabItem.getParent().getSelectionIndex();
}
}
}
|
30,005 |
Bug 30005 Can't create linked source folder in new java project wizard [build path]
|
Build: I20030122 1) Open the new java project wizard 2) Enter a name, hit next 3) Click "Add Folder" on the "Source" tab. -> dialog comes up that doesn't have an option to create a new folder 4) Click cancel. Click "Browse" next to the output folder field -> this dialog allows you to create a new folder (even a linked folder) 5) Click cancel. Finish the wizard. 6) Open the java build path property page 3) Click "Add Folder" on the "Source" tab. -> now the dialog allows you to create a new linked folder. It should allow you to do this from the wizard.
|
resolved fixed
|
844dc6a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-23T09:25:43Z | 2003-01-22T18:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/SourceContainerWorkbookPage.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.wizards.buildpaths;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.ui.model.WorkbenchContentProvider;
import org.eclipse.ui.model.WorkbenchLabelProvider;
import org.eclipse.ui.views.navigator.ResourceSorter;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
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.util.PixelConverter;
import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages;
import org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator;
import org.eclipse.jdt.internal.ui.wizards.TypedViewerFilter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.ITreeListAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.TreeListDialogField;
public class SourceContainerWorkbookPage extends BuildPathBasePage {
private ListDialogField fClassPathList;
private IJavaProject fCurrJProject;
private IPath fProjPath;
private Control fSWTControl;
private IWorkspaceRoot fWorkspaceRoot;
private TreeListDialogField fFoldersList;
private StringDialogField fOutputLocationField;
private SelectionButtonDialogField fUseFolderOutputs;
private final int IDX_ADD= 0;
private final int IDX_EDIT= 2;
private final int IDX_REMOVE= 3;
public SourceContainerWorkbookPage(IWorkspaceRoot root, ListDialogField classPathList, StringDialogField outputLocationField) {
fWorkspaceRoot= root;
fClassPathList= classPathList;
fOutputLocationField= outputLocationField;
fSWTControl= null;
SourceContainerAdapter adapter= new SourceContainerAdapter();
String[] buttonLabels;
buttonLabels= new String[] {
/* 0 = IDX_ADDEXIST */ NewWizardMessages.getString("SourceContainerWorkbookPage.folders.add.button"), //$NON-NLS-1$
/* 1 */ null,
/* 2 = IDX_EDIT */ NewWizardMessages.getString("SourceContainerWorkbookPage.folders.edit.button"), //$NON-NLS-1$
/* 3 = IDX_REMOVE */ NewWizardMessages.getString("SourceContainerWorkbookPage.folders.remove.button") //$NON-NLS-1$
};
fFoldersList= new TreeListDialogField(adapter, buttonLabels, new CPListLabelProvider());
fFoldersList.setDialogFieldListener(adapter);
fFoldersList.setLabelText(NewWizardMessages.getString("SourceContainerWorkbookPage.folders.label")); //$NON-NLS-1$
fFoldersList.setViewerSorter(new CPListElementSorter());
fFoldersList.enableButton(IDX_EDIT, false);
fUseFolderOutputs= new SelectionButtonDialogField(SWT.CHECK);
fUseFolderOutputs.setSelection(false);
fUseFolderOutputs.setLabelText(NewWizardMessages.getString("SourceContainerWorkbookPage.folders.check"));
fUseFolderOutputs.setDialogFieldListener(adapter);
}
public void init(IJavaProject jproject) {
fCurrJProject= jproject;
fProjPath= fCurrJProject.getProject().getFullPath();
updateFoldersList();
}
private void updateFoldersList() {
ArrayList folders= new ArrayList();
boolean useFolderOutputs= false;
List cpelements= fClassPathList.getElements();
for (int i= 0; i < cpelements.size(); i++) {
CPListElement cpe= (CPListElement)cpelements.get(i);
if (cpe.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
folders.add(cpe);
boolean hasOutputFolder= (cpe.getAttribute(CPListElement.OUTPUT) != null);
if (hasOutputFolder) {
useFolderOutputs= true;
}
}
}
fFoldersList.setElements(folders);
fUseFolderOutputs.setSelection(useFolderOutputs);
for (int i= 0; i < folders.size(); i++) {
CPListElement cpe= (CPListElement) folders.get(i);
IPath[] patterns= (IPath[]) cpe.getAttribute(CPListElement.EXCLUSION);
boolean hasOutputFolder= (cpe.getAttribute(CPListElement.OUTPUT) != null);
if (patterns.length > 0 || hasOutputFolder) {
fFoldersList.expandElement(cpe, 3);
}
}
}
public Control getControl(Composite parent) {
PixelConverter converter= new PixelConverter(parent);
Composite composite= new Composite(parent, SWT.NONE);
LayoutUtil.doDefaultLayout(composite, new DialogField[] { fFoldersList, fUseFolderOutputs }, true);
LayoutUtil.setHorizontalGrabbing(fFoldersList.getTreeControl(null));
int buttonBarWidth= converter.convertWidthInCharsToPixels(24);
fFoldersList.setButtonsMinWidth(buttonBarWidth);
fSWTControl= composite;
// expand
List elements= fFoldersList.getElements();
for (int i= 0; i < elements.size(); i++) {
CPListElement elem= (CPListElement) elements.get(i);
IPath[] patterns= (IPath[]) elem.getAttribute(CPListElement.EXCLUSION);
IPath output= (IPath) elem.getAttribute(CPListElement.OUTPUT);
if (patterns.length > 0 || output != null) {
fFoldersList.expandElement(elem, 3);
}
}
return composite;
}
private Shell getShell() {
if (fSWTControl != null) {
return fSWTControl.getShell();
}
return JavaPlugin.getActiveWorkbenchShell();
}
private class SourceContainerAdapter implements ITreeListAdapter, IDialogFieldListener {
private final Object[] EMPTY_ARR= new Object[0];
// -------- IListAdapter --------
public void customButtonPressed(TreeListDialogField field, int index) {
sourcePageCustomButtonPressed(field, index);
}
public void selectionChanged(TreeListDialogField field) {
sourcePageSelectionChanged(field);
}
public void doubleClicked(TreeListDialogField field) {
sourcePageDoubleClicked(field);
}
public Object[] getChildren(TreeListDialogField field, Object element) {
if (element instanceof CPListElement) {
return ((CPListElement) element).getChildren(!fUseFolderOutputs.isSelected());
}
return EMPTY_ARR;
}
public Object getParent(TreeListDialogField field, Object element) {
if (element instanceof CPListElementAttribute) {
return ((CPListElementAttribute) element).getParent();
}
return null;
}
public boolean hasChildren(TreeListDialogField field, Object element) {
return (element instanceof CPListElement);
}
// ---------- IDialogFieldListener --------
public void dialogFieldChanged(DialogField field) {
sourcePageDialogFieldChanged(field);
}
}
protected void sourcePageDoubleClicked(TreeListDialogField field) {
if (field == fFoldersList) {
List selection= fFoldersList.getSelectedElements();
if (canEdit(selection)) {
editEntry();
}
}
}
protected void sourcePageCustomButtonPressed(DialogField field, int index) {
if (field == fFoldersList) {
if (index == IDX_ADD) {
List elementsToAdd= new ArrayList(10);
if (fCurrJProject.exists()) {
CPListElement[] srcentries= openSourceContainerDialog(null);
if (srcentries != null) {
for (int i= 0; i < srcentries.length; i++) {
elementsToAdd.add(srcentries[i]);
}
}
} else {
CPListElement entry= openNewSourceContainerDialog(null);
if (entry != null) {
elementsToAdd.add(entry);
}
}
if (!elementsToAdd.isEmpty()) {
if (fFoldersList.getSize() == 1) {
CPListElement existing= (CPListElement) fFoldersList.getElement(0);
if (existing.getResource() instanceof IProject) {
askForChangingBuildPathDialog(existing);
}
}
HashSet modifiedElements= new HashSet();
askForAddingExclusionPatternsDialog(elementsToAdd, modifiedElements);
fFoldersList.addElements(elementsToAdd);
fFoldersList.postSetSelection(new StructuredSelection(elementsToAdd));
if (!modifiedElements.isEmpty()) {
for (Iterator iter= modifiedElements.iterator(); iter.hasNext();) {
Object elem= iter.next();
fFoldersList.refresh(elem);
fFoldersList.expandElement(elem, 3);
}
}
}
} else if (index == IDX_EDIT) {
editEntry();
} else if (index == IDX_REMOVE) {
removeEntry();
}
}
}
private void editEntry() {
List selElements= fFoldersList.getSelectedElements();
if (selElements.size() != 1) {
return;
}
Object elem= selElements.get(0);
if (fFoldersList.getIndexOfElement(elem) != -1) {
editElementEntry((CPListElement) elem);
} else if (elem instanceof CPListElementAttribute) {
editAttributeEntry((CPListElementAttribute) elem);
}
}
private void editElementEntry(CPListElement elem) {
CPListElement res= null;
IResource resource= elem.getResource();
if (resource.exists()) {
CPListElement[] arr= openSourceContainerDialog(elem);
if (arr != null) {
res= arr[0];
}
} else {
res= openNewSourceContainerDialog(elem);
}
if (res != null) {
fFoldersList.replaceElement(elem, res);
}
}
private void editAttributeEntry(CPListElementAttribute elem) {
String key= elem.getKey();
if (key.equals(CPListElement.OUTPUT)) {
CPListElement selElement= (CPListElement) elem.getParent();
OutputLocationDialog dialog= new OutputLocationDialog(getShell(), selElement);
if (dialog.open() == OutputLocationDialog.OK) {
selElement.setAttribute(CPListElement.OUTPUT, dialog.getOutputLocation());
fFoldersList.refresh();
fClassPathList.dialogFieldChanged(); // validate
}
} else if (key.equals(CPListElement.EXCLUSION)) {
CPListElement selElement= (CPListElement) elem.getParent();
ExclusionPatternDialog dialog= new ExclusionPatternDialog(getShell(), selElement);
if (dialog.open() == OutputLocationDialog.OK) {
selElement.setAttribute(CPListElement.EXCLUSION, dialog.getExclusionPattern());
fFoldersList.refresh();
fClassPathList.dialogFieldChanged(); // validate
}
}
}
protected void sourcePageSelectionChanged(DialogField field) {
List selected= fFoldersList.getSelectedElements();
fFoldersList.enableButton(IDX_EDIT, canEdit(selected));
fFoldersList.enableButton(IDX_REMOVE, canRemove(selected));
}
private void removeEntry() {
List selElements= fFoldersList.getSelectedElements();
for (int i= selElements.size() - 1; i >= 0 ; i--) {
Object elem= selElements.get(i);
if (elem instanceof CPListElementAttribute) {
CPListElementAttribute attrib= (CPListElementAttribute) elem;
if (attrib.getKey().equals(CPListElement.EXCLUSION)) {
attrib.setValue(new Path[0]);
} else {
attrib.setValue(null);
}
selElements.remove(i);
}
}
if (selElements.isEmpty()) {
fFoldersList.refresh();
} else {
fFoldersList.removeElements(selElements);
}
}
private boolean canRemove(List selElements) {
if (selElements.size() == 0) {
return false;
}
for (int i= 0; i < selElements.size(); i++) {
Object elem= (Object) selElements.get(i);
if (elem instanceof CPListElementAttribute) {
CPListElementAttribute attrib= (CPListElementAttribute) elem;
if (attrib.getKey().equals(CPListElement.EXCLUSION)) {
if (((IPath[]) attrib.getValue()).length == 0) {
return false;
}
} else if (attrib.getValue() == null) {
return false;
}
} else if (elem instanceof CPListElement) {
CPListElement curr= (CPListElement) elem;
if (curr.getParentContainer() != null) {
return false;
}
}
}
return true;
}
private boolean canEdit(List selElements) {
if (selElements.size() != 1) {
return false;
}
Object elem= selElements.get(0);
if (fFoldersList.getIndexOfElement(elem) != -1) {
return true;
}
if (elem instanceof CPListElementAttribute) {
return true;
}
return false;
}
private void sourcePageDialogFieldChanged(DialogField field) {
if (fCurrJProject == null) {
// not initialized
return;
}
if (field == fUseFolderOutputs) {
if (!fUseFolderOutputs.isSelected()) {
int nFolders= fFoldersList.getSize();
for (int i= 0; i < nFolders; i++) {
CPListElement cpe= (CPListElement) fFoldersList.getElement(i);
cpe.setAttribute(CPListElement.OUTPUT, null);
}
}
fFoldersList.refresh();
} else if (field == fFoldersList) {
updateClasspathList();
}
}
private void updateClasspathList() {
List cpelements= fClassPathList.getElements();
List srcelements= fFoldersList.getElements();
boolean changeDone= false;
CPListElement lastSourceFolder= null;
// backwards, as entries will be deleted
for (int i= cpelements.size() - 1; i >= 0 ; i--) {
CPListElement cpe= (CPListElement)cpelements.get(i);
if (isEntryKind(cpe.getEntryKind())) {
// if it is a source folder, but not one of the accepted entries, remove it
// at the same time, for the entries seen, remove them from the accepted list
if (!srcelements.remove(cpe)) {
cpelements.remove(i);
changeDone= true;
} else if (lastSourceFolder == null) {
lastSourceFolder= cpe;
}
}
}
if (!srcelements.isEmpty()) {
int insertIndex= (lastSourceFolder == null) ? 0 : cpelements.indexOf(lastSourceFolder) + 1;
cpelements.addAll(insertIndex, srcelements);
changeDone= true;
}
if (changeDone) {
fClassPathList.setElements(cpelements);
}
}
private CPListElement openNewSourceContainerDialog(CPListElement existing) {
String title= (existing == null) ? NewWizardMessages.getString("SourceContainerWorkbookPage.NewSourceFolderDialog.new.title") : NewWizardMessages.getString("SourceContainerWorkbookPage.NewSourceFolderDialog.edit.title"); //$NON-NLS-1$ //$NON-NLS-2$
IProject proj= fCurrJProject.getProject();
NewSourceFolderDialog dialog= new NewSourceFolderDialog(getShell(), title, proj, getExistingContainers(existing), existing);
dialog.setMessage(NewWizardMessages.getFormattedString("SourceContainerWorkbookPage.NewSourceFolderDialog.description", fProjPath.toString())); //$NON-NLS-1$
if (dialog.open() == NewContainerDialog.OK) {
IResource folder= dialog.getSourceFolder();
return newCPSourceElement(folder);
}
return null;
}
/**
* Asks to change the output folder to 'proj/bin' when no source folders were existing
*/
private void askForChangingBuildPathDialog(CPListElement existing) {
IPath outputFolder= new Path(fOutputLocationField.getText());
IPath newOutputFolder= null;
String message;
if (outputFolder.segmentCount() == 1) {
String outputFolderName= PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.SRCBIN_BINNAME);
newOutputFolder= outputFolder.append(outputFolderName);
message= NewWizardMessages.getFormattedString("SourceContainerWorkbookPage.ChangeOutputLocationDialog.project_and_output.message", newOutputFolder); //$NON-NLS-1$
} else {
message= NewWizardMessages.getString("SourceContainerWorkbookPage.ChangeOutputLocationDialog.project.message"); //$NON-NLS-1$
}
String title= NewWizardMessages.getString("SourceContainerWorkbookPage.ChangeOutputLocationDialog.title"); //$NON-NLS-1$
if (MessageDialog.openQuestion(getShell(), title, message)) {
fFoldersList.removeElement(existing);
if (newOutputFolder != null) {
fOutputLocationField.setText(newOutputFolder.toString());
}
}
}
private void askForAddingExclusionPatternsDialog(List newEntries, Set modifiedEntries) {
for (int i= 0; i < newEntries.size(); i++) {
CPListElement curr= (CPListElement) newEntries.get(i);
addExclusionPatterns(curr, modifiedEntries);
}
if (!modifiedEntries.isEmpty()) {
String title= NewWizardMessages.getString("SourceContainerWorkbookPage.exclusion_added.title"); //$NON-NLS-1$
String message= NewWizardMessages.getString("SourceContainerWorkbookPage.exclusion_added.message"); //$NON-NLS-1$
MessageDialog.openInformation(getShell(), title, message);
}
}
private void addExclusionPatterns(CPListElement newEntry, Set modifiedEntries) {
IPath entryPath= newEntry.getPath();
List existing= fFoldersList.getElements();
for (int i= 0; i < existing.size(); i++) {
CPListElement curr= (CPListElement) existing.get(i);
IPath currPath= curr.getPath();
if (currPath.isPrefixOf(entryPath)) {
IPath[] exclusionFilters= (IPath[]) curr.getAttribute(CPListElement.EXCLUSION);
if (!JavaModelUtil.isExcludedPath(entryPath, exclusionFilters)) {
IPath pathToExclude= entryPath.removeFirstSegments(currPath.segmentCount()).addTrailingSeparator();
IPath[] newExclusionFilters= new IPath[exclusionFilters.length + 1];
System.arraycopy(exclusionFilters, 0, newExclusionFilters, 0, exclusionFilters.length);
newExclusionFilters[exclusionFilters.length]= pathToExclude;
curr.setAttribute(CPListElement.EXCLUSION, newExclusionFilters);
modifiedEntries.add(curr);
}
}
}
}
private CPListElement[] openSourceContainerDialog(CPListElement existing) {
Class[] acceptedClasses= new Class[] { IProject.class, IFolder.class };
TypedElementSelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, existing == null, getExistingContainers(null));
IProject[] allProjects= fWorkspaceRoot.getProjects();
ArrayList rejectedElements= new ArrayList(allProjects.length);
IProject currProject= fCurrJProject.getProject();
for (int i= 0; i < allProjects.length; i++) {
if (!allProjects[i].equals(currProject)) {
rejectedElements.add(allProjects[i]);
}
}
ViewerFilter filter= new TypedViewerFilter(acceptedClasses, rejectedElements.toArray());
ILabelProvider lp= new WorkbenchLabelProvider();
ITreeContentProvider cp= new WorkbenchContentProvider();
String title= (existing == null) ? NewWizardMessages.getString("SourceContainerWorkbookPage.ExistingSourceFolderDialog.new.title") : NewWizardMessages.getString("SourceContainerWorkbookPage.ExistingSourceFolderDialog.edit.title"); //$NON-NLS-1$ //$NON-NLS-2$
String message= (existing == null) ? NewWizardMessages.getString("SourceContainerWorkbookPage.ExistingSourceFolderDialog.new.description") : NewWizardMessages.getString("SourceContainerWorkbookPage.ExistingSourceFolderDialog.edit.description"); //$NON-NLS-1$ //$NON-NLS-2$
FolderSelectionDialog dialog= new FolderSelectionDialog(getShell(), lp, cp);
dialog.setValidator(validator);
dialog.setTitle(title);
dialog.setMessage(message);
dialog.addFilter(filter);
dialog.setInput(fCurrJProject.getProject().getParent());
dialog.setSorter(new ResourceSorter(ResourceSorter.NAME));
if (existing == null) {
dialog.setInitialSelection(fCurrJProject.getProject());
} else {
dialog.setInitialSelection(existing.getResource());
}
if (dialog.open() == FolderSelectionDialog.OK) {
Object[] elements= dialog.getResult();
CPListElement[] res= new CPListElement[elements.length];
for (int i= 0; i < res.length; i++) {
IResource elem= (IResource)elements[i];
res[i]= newCPSourceElement(elem);
}
return res;
}
return null;
}
private List getExistingContainers(CPListElement existing) {
List res= new ArrayList();
List cplist= fFoldersList.getElements();
for (int i= 0; i < cplist.size(); i++) {
CPListElement elem= (CPListElement)cplist.get(i);
if (elem != existing) {
IResource resource= elem.getResource();
if (resource instanceof IContainer) { // defensive code
res.add(resource);
}
}
}
return res;
}
private CPListElement newCPSourceElement(IResource res) {
Assert.isNotNull(res);
return new CPListElement(fCurrJProject, IClasspathEntry.CPE_SOURCE, res.getFullPath(), res);
}
/*
* @see BuildPathBasePage#getSelection
*/
public List getSelection() {
return fFoldersList.getSelectedElements();
}
/*
* @see BuildPathBasePage#setSelection
*/
public void setSelection(List selElements) {
fFoldersList.selectElements(new StructuredSelection(selElements));
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.wizards.buildpaths.BuildPathBasePage#isEntryKind(int)
*/
public boolean isEntryKind(int kind) {
return kind == IClasspathEntry.CPE_SOURCE;
}
}
|
30,007 |
Bug 30007 Can't hit next in new java project wizard [build path] [code manipulation]
|
Build: I20020122 1) Open the new java project wizard 2) Enter a name, hit next 3) Hit the back button 4) Deselect the "Use default" check box 5) Type in a location -> It won't let me hit next, because it claims the project already exists. 6) Click cancel -> The project doesn't exist.
|
resolved fixed
|
17121d0
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-23T11:08:26Z | 2003-01-22T21:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/NewProjectCreationWizardPage.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.wizards;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.ui.dialogs.WizardNewProjectCreationPage;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.ui.wizards.JavaCapabilityConfigurationPage;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
/**
* As addition to the JavaCapabilityConfigurationPage, the wizard does an
* early project creation (so that linked folders can be defined) and, if an
* existing external location was specified, offers to do a classpath detection
*/
public class NewProjectCreationWizardPage extends JavaCapabilityConfigurationPage {
private WizardNewProjectCreationPage fMainPage;
private IPath fCurrProjectLocation;
private IProject fCurrProject;
/**
* Constructor for NewProjectCreationWizardPage.
*/
public NewProjectCreationWizardPage(WizardNewProjectCreationPage mainPage) {
super();
fMainPage= mainPage;
fCurrProjectLocation= null;
}
/* (non-Javadoc)
* @see org.eclipse.jface.dialogs.IDialogPage#setVisible(boolean)
*/
public void setVisible(boolean visible) {
if (visible) {
changeToNewProject();
}
super.setVisible(visible);
}
private void changeToNewProject() {
IProject newProjectHandle= fMainPage.getProjectHandle();
IPath newProjectLocation= fMainPage.getLocationPath();
if (newProjectHandle.equals(fCurrProject) && newProjectLocation.equals(fCurrProjectLocation)) {
return; // no changes
}
IRunnableWithProgress op= new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
try {
updateProject(monitor);
} catch (CoreException e) {
throw new InvocationTargetException(e);
}
}
};
try {
getContainer().run(false, true, op);
} catch (InvocationTargetException e) {
String title= NewWizardMessages.getString("NewProjectCreationWizardPage.EarlyCreationOperation.error.title"); //$NON-NLS-1$
String message= NewWizardMessages.getString("NewProjectCreationWizardPage.EarlyCreationOperation.error.desc"); //$NON-NLS-1$
ExceptionHandler.handle(e, getShell(), title, message);
} catch (InterruptedException e) {
// cancel pressed
}
}
protected void updateProject(IProgressMonitor monitor) throws CoreException, InterruptedException {
if (monitor == null) {
monitor= new NullProgressMonitor();
}
try {
monitor.beginTask(NewWizardMessages.getString("NewProjectCreationWizardPage.EarlyCreationOperation.desc"), 3); //$NON-NLS-1$
if (fCurrProject != null) { // remove existing project
fCurrProject.delete(false, false, new SubProgressMonitor(monitor, 1));
} else {
monitor.worked(1);
}
fCurrProject= fMainPage.getProjectHandle();
fCurrProjectLocation= fMainPage.getLocationPath();
createProject(fCurrProject, fCurrProjectLocation, new SubProgressMonitor(monitor, 1));
IClasspathEntry[] entries= null;
IPath outputLocation= null;
if (fCurrProjectLocation.toFile().exists() && !Platform.getLocation().equals(fCurrProjectLocation)) {
// detect classpath
if (!fCurrProject.getFile(".classpath").exists()) { //$NON-NLS-1$
// if .classpath exists noneed to look for files
ClassPathDetector detector= new ClassPathDetector(fCurrProject);
entries= detector.getClasspath();
outputLocation= detector.getOutputLocation();
}
}
init(JavaCore.create(fCurrProject), outputLocation, entries, false);
monitor.worked(1);
} finally {
monitor.done();
}
}
/**
* Called from the wizard on finish.
*/
public void performFinish(IProgressMonitor monitor) throws CoreException, InterruptedException {
try {
monitor.beginTask(NewWizardMessages.getString("NewProjectCreationWizardPage.createproject.desc"), 3); //$NON-NLS-1$
if (fCurrProject == null) {
updateProject(new SubProgressMonitor(monitor, 1));
}
configureJavaProject(new SubProgressMonitor(monitor, 2));
} finally {
monitor.done();
}
}
/**
* Called from the wizard on cancel.
*/
public void performCancel() {
if (fCurrProject != null) {
try {
fCurrProject.delete(false, false, null);
} catch (CoreException e) {
String title= NewWizardMessages.getString("NewProjectCreationWizardPage.op_error.title"); //$NON-NLS-1$
String message= NewWizardMessages.getString("NewProjectCreationWizardPage.op_error_remove.message"); //$NON-NLS-1$
ExceptionHandler.handle(e, getShell(), title, message);
}
}
}
}
|
30,102 |
Bug 30102 NamingConvention: Tests fail
|
20030122 I changed our tests to use NamingConvention. There are failuers, please check. NameProposerTest in jdt.ui.tests
|
verified fixed
|
91c5449
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-23T16:28:19Z | 2003-01-23T16:40:00Z |
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/CoreTests.java
|
package org.eclipse.jdt.ui.tests.core;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
*/
public class CoreTests extends TestCase {
public static Test suite() {
TestSuite suite= new TestSuite();
suite.addTest(new TestSuite(AddImportTest.class));
suite.addTest(new TestSuite(AddUnimplementedMethodsTest.class));
//suite.addTest(new TestSuite(AllTypesCacheTest.suite.class));
suite.addTest(new TestSuite(BindingsNameTest.class));
suite.addTest(new TestSuite(ClassPathDetectorTest.class));
suite.addTest(new TestSuite(HierarchicalASTVisitorTest.class));
suite.addTest(new TestSuite(ImportOrganizeTest.class));
suite.addTest(new TestSuite(JavaModelUtilTest.class));
suite.addTest(new TestSuite(NameProposerTest.class));
suite.addTest(new TestSuite(TextBufferTest.class));
suite.addTest(new TestSuite(TypeInfoTest.class));
return suite;
}
public CoreTests(String name) {
super(name);
}
}
|
30,092 |
Bug 30092 [browsing]Missing View Short cuts in the Java Browsing perspective
|
1) in the Java Browsing Perspective 2) execute Window>Show View ->notice that the Views shown in the Browsing Perspective do not show up in the menu. You have to go to the Other... dialog. This should be changed (the perspective factory can define the corresponding short cuts), e.g. layout.addShowViewShortcut(IPageLayout.ID_OUTLINE); layout.addShowViewShortcut(IPageLayout.ID_TASK_LIST); layout.addShowViewShortcut(IPageLayout.ID_RES_NAV); This is easy to fix and will be important once we add the Show In... support
|
resolved fixed
|
ecb31df
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-23T17:53:33Z | 2003-01-23T16:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/browsing/JavaBrowsingPerspectiveFactory.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.browsing;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPerspectiveFactory;
import org.eclipse.ui.IPlaceholderFolderLayout;
import org.eclipse.debug.ui.IDebugUIConstants;
import org.eclipse.search.ui.SearchUI;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
public class JavaBrowsingPerspectiveFactory implements IPerspectiveFactory {
/*
* XXX: This is a workaround for: http://dev.eclipse.org/bugs/show_bug.cgi?id=13070
*/
static IJavaElement fgJavaElementFromAction;
/**
* Constructs a new Default layout engine.
*/
public JavaBrowsingPerspectiveFactory() {
super();
}
public void createInitialLayout(IPageLayout layout) {
if (stackBrowsingViewsVertically())
createVerticalLayout(layout);
else
createHorizontalLayout(layout);
// action sets
layout.addActionSet(IDebugUIConstants.LAUNCH_ACTION_SET);
layout.addActionSet(JavaUI.ID_ACTION_SET);
layout.addActionSet(JavaUI.ID_ELEMENT_CREATION_ACTION_SET);
layout.addActionSet(IPageLayout.ID_NAVIGATE_ACTION_SET);
// views - java
layout.addShowViewShortcut(JavaUI.ID_TYPE_HIERARCHY);
// views - search
layout.addShowViewShortcut(SearchUI.SEARCH_RESULT_VIEW_ID);
// views - debugging
layout.addShowViewShortcut(IDebugUIConstants.ID_CONSOLE_VIEW);
// views - standard workbench
layout.addShowViewShortcut(IPageLayout.ID_OUTLINE);
layout.addShowViewShortcut(IPageLayout.ID_TASK_LIST);
layout.addShowViewShortcut(IPageLayout.ID_RES_NAV);
// new actions - Java project creation wizard
layout.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewPackageCreationWizard"); //$NON-NLS-1$
layout.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewClassCreationWizard"); //$NON-NLS-1$
layout.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewInterfaceCreationWizard"); //$NON-NLS-1$
layout.addNewWizardShortcut("org.eclipse.jdt.ui.wizards.NewSnippetCreationWizard"); //$NON-NLS-1$
}
private void createVerticalLayout(IPageLayout layout) {
String relativePartId= IPageLayout.ID_EDITOR_AREA;
int relativePos= IPageLayout.LEFT;
IPlaceholderFolderLayout placeHolderLeft= layout.createPlaceholderFolder("left", IPageLayout.LEFT, (float)0.25, IPageLayout.ID_EDITOR_AREA); //$NON-NLS-1$
placeHolderLeft.addPlaceholder(JavaUI.ID_TYPE_HIERARCHY);
placeHolderLeft.addPlaceholder(IPageLayout.ID_OUTLINE);
placeHolderLeft.addPlaceholder(JavaUI.ID_PACKAGES);
placeHolderLeft.addPlaceholder(IPageLayout.ID_RES_NAV);
if (shouldShowProjectsView()) {
layout.addView(JavaUI.ID_PROJECTS_VIEW, IPageLayout.LEFT, (float)0.25, IPageLayout.ID_EDITOR_AREA);
relativePartId= JavaUI.ID_PROJECTS_VIEW;
relativePos= IPageLayout.BOTTOM;
}
if (shouldShowPackagesView()) {
layout.addView(JavaUI.ID_PACKAGES_VIEW, relativePos, (float)0.25, relativePartId);
relativePartId= JavaUI.ID_PACKAGES_VIEW;
relativePos= IPageLayout.BOTTOM;
}
layout.addView(JavaUI.ID_TYPES_VIEW, relativePos, (float)0.33, relativePartId);
layout.addView(JavaUI.ID_MEMBERS_VIEW, IPageLayout.BOTTOM, (float)0.50, JavaUI.ID_TYPES_VIEW);
IPlaceholderFolderLayout placeHolderBottom= layout.createPlaceholderFolder("bottom", IPageLayout.BOTTOM, (float)0.75, IPageLayout.ID_EDITOR_AREA); //$NON-NLS-1$
placeHolderBottom.addPlaceholder(IPageLayout.ID_TASK_LIST);
placeHolderBottom.addPlaceholder(SearchUI.SEARCH_RESULT_VIEW_ID);
placeHolderBottom.addPlaceholder(IDebugUIConstants.ID_CONSOLE_VIEW);
placeHolderBottom.addPlaceholder(IPageLayout.ID_BOOKMARKS);
}
private void createHorizontalLayout(IPageLayout layout) {
String relativePartId= IPageLayout.ID_EDITOR_AREA;
int relativePos= IPageLayout.TOP;
if (shouldShowProjectsView()) {
layout.addView(JavaUI.ID_PROJECTS_VIEW, IPageLayout.TOP, (float)0.25, IPageLayout.ID_EDITOR_AREA);
relativePartId= JavaUI.ID_PROJECTS_VIEW;
relativePos= IPageLayout.RIGHT;
}
if (shouldShowPackagesView()) {
layout.addView(JavaUI.ID_PACKAGES_VIEW, relativePos, (float)0.25, relativePartId);
relativePartId= JavaUI.ID_PACKAGES_VIEW;
relativePos= IPageLayout.RIGHT;
}
layout.addView(JavaUI.ID_TYPES_VIEW, relativePos, (float)0.33, relativePartId);
layout.addView(JavaUI.ID_MEMBERS_VIEW, IPageLayout.RIGHT, (float)0.50, JavaUI.ID_TYPES_VIEW);
IPlaceholderFolderLayout placeHolderLeft= layout.createPlaceholderFolder("left", IPageLayout.LEFT, (float)0.25, IPageLayout.ID_EDITOR_AREA); //$NON-NLS-1$
placeHolderLeft.addPlaceholder(JavaUI.ID_TYPE_HIERARCHY);
placeHolderLeft.addPlaceholder(IPageLayout.ID_OUTLINE);
placeHolderLeft.addPlaceholder(JavaUI.ID_PACKAGES);
placeHolderLeft.addPlaceholder(IPageLayout.ID_RES_NAV);
IPlaceholderFolderLayout placeHolderBottom= layout.createPlaceholderFolder("bottom", IPageLayout.BOTTOM, (float)0.75, IPageLayout.ID_EDITOR_AREA); //$NON-NLS-1$
placeHolderBottom.addPlaceholder(IPageLayout.ID_TASK_LIST);
placeHolderBottom.addPlaceholder(SearchUI.SEARCH_RESULT_VIEW_ID);
placeHolderBottom.addPlaceholder(IDebugUIConstants.ID_CONSOLE_VIEW);
placeHolderBottom.addPlaceholder(IPageLayout.ID_BOOKMARKS);
}
private boolean shouldShowProjectsView() {
return fgJavaElementFromAction == null || fgJavaElementFromAction.getElementType() == IJavaElement.JAVA_MODEL;
}
private boolean shouldShowPackagesView() {
if (fgJavaElementFromAction == null)
return true;
int type= fgJavaElementFromAction.getElementType();
return type == IJavaElement.JAVA_MODEL || type == IJavaElement.JAVA_PROJECT || type == IJavaElement.PACKAGE_FRAGMENT_ROOT;
}
private boolean stackBrowsingViewsVertically() {
return PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.BROWSING_STACK_VERTICALLY);
}
/*
* XXX: This is a workaround for: http://dev.eclipse.org/bugs/show_bug.cgi?id=13070
*/
static void setInputFromAction(IAdaptable input) {
if (input instanceof IJavaElement)
fgJavaElementFromAction= (IJavaElement)input;
else
fgJavaElementFromAction= null;
}
}
|
30,235 |
Bug 30235 [refactoring] Exception in Move method refactoring
|
JUnit setup. 1) Select TestResult runTest in the source 2) accept the default settings 3) finish (without preview) !ENTRY org.eclipse.jdt.ui 4 10001 Jan 26, 2003 00:37:57.355 !MESSAGE Internal Error !STACK 0 java.lang.reflect.InvocationTargetException at org.eclipse.jface.operation.ModalContext.runInCurrentThread(ModalCont ext.java:307) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:246) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.run( RefactoringWizardDialog2.java:256) at org.eclipse.jdt.internal.ui.refactoring.PerformRefactoringUtil.perfor mRefactoring(PerformRefactoringUtil.java:43) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFini sh(RefactoringWizard.java:362) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.performFi nish(UserInputWizardPage.java:113) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFini sh(RefactoringWizard.java:425) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.okPr essed(RefactoringWizardDialog2.java:371) at org.eclipse.jface.dialogs.Dialog.buttonPressed(Dialog.java:240) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:398) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java: 87) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:836) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1692) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1410) at org.eclipse.jface.window.Window.runEventLoop(Window.java:561) at org.eclipse.jface.window.Window.open(Window.java:541) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.ac tivate(RefactoringStarter.java:60) at org.eclipse.jdt.internal.ui.refactoring.actions.MoveInstanceMethodAct ion.run(MoveInstanceMethodAction.java:131) at org.eclipse.jdt.internal.ui.refactoring.actions.MoveInstanceMethodAct ion.run(MoveInstanceMethodAction.java:115) at org.eclipse.jdt.ui.actions.MoveAction.tryMoveInstanceMethod(MoveActio n.java:172) at org.eclipse.jdt.ui.actions.MoveAction.run(MoveAction.java:135) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun(Select ionDispatchAction.java:193) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run(SelectionDispa tchAction.java:169) at org.eclipse.jface.action.Action.runWithEvent(Action.java:804) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:422) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent(Act ionContributionItem.java:374) at org.eclipse.jface.action.ActionContributionItem.access$0(ActionContri butionItem.java:368) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handle Event(ActionContributionItem.java:69) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:836) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1692) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1410) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1525) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1508) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoa der.java:845) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:462) 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:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539) Caused by: org.eclipse.jdt.internal.corext.Assert$AssertionFailedException: null argument;New receiver must be chosen before checkInput(..) is called. at org.eclipse.jdt.internal.corext.Assert.isNotNull(Assert.java:99) at org.eclipse.jdt.internal.corext.refactoring.structure.InstanceMethodM over.checkInput(InstanceMethodMover.java:1848) at org.eclipse.jdt.internal.corext.refactoring.structure.MoveInstanceMet hodRefactoring.checkInput(MoveInstanceMethodRefactoring.java:158) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run( CheckConditionsOperation.java:59) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run(Cre ateChangeOperation.java:94) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run(Pe rformChangeOperation.java:138) at org.eclipse.jface.operation.ModalContext.runInCurrentThread(ModalCont ext.java:296) ... 43 more
|
resolved fixed
|
df97c0f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-27T12:15:29Z | 2003-01-26T00:13:20Z |
org.eclipse.jdt.ui/ui
| |
30,235 |
Bug 30235 [refactoring] Exception in Move method refactoring
|
JUnit setup. 1) Select TestResult runTest in the source 2) accept the default settings 3) finish (without preview) !ENTRY org.eclipse.jdt.ui 4 10001 Jan 26, 2003 00:37:57.355 !MESSAGE Internal Error !STACK 0 java.lang.reflect.InvocationTargetException at org.eclipse.jface.operation.ModalContext.runInCurrentThread(ModalCont ext.java:307) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:246) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.run( RefactoringWizardDialog2.java:256) at org.eclipse.jdt.internal.ui.refactoring.PerformRefactoringUtil.perfor mRefactoring(PerformRefactoringUtil.java:43) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFini sh(RefactoringWizard.java:362) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.performFi nish(UserInputWizardPage.java:113) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFini sh(RefactoringWizard.java:425) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.okPr essed(RefactoringWizardDialog2.java:371) at org.eclipse.jface.dialogs.Dialog.buttonPressed(Dialog.java:240) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:398) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java: 87) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:836) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1692) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1410) at org.eclipse.jface.window.Window.runEventLoop(Window.java:561) at org.eclipse.jface.window.Window.open(Window.java:541) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.ac tivate(RefactoringStarter.java:60) at org.eclipse.jdt.internal.ui.refactoring.actions.MoveInstanceMethodAct ion.run(MoveInstanceMethodAction.java:131) at org.eclipse.jdt.internal.ui.refactoring.actions.MoveInstanceMethodAct ion.run(MoveInstanceMethodAction.java:115) at org.eclipse.jdt.ui.actions.MoveAction.tryMoveInstanceMethod(MoveActio n.java:172) at org.eclipse.jdt.ui.actions.MoveAction.run(MoveAction.java:135) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun(Select ionDispatchAction.java:193) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run(SelectionDispa tchAction.java:169) at org.eclipse.jface.action.Action.runWithEvent(Action.java:804) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:422) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent(Act ionContributionItem.java:374) at org.eclipse.jface.action.ActionContributionItem.access$0(ActionContri butionItem.java:368) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handle Event(ActionContributionItem.java:69) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:836) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1692) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1410) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1525) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1508) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoa der.java:845) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:462) 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:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539) Caused by: org.eclipse.jdt.internal.corext.Assert$AssertionFailedException: null argument;New receiver must be chosen before checkInput(..) is called. at org.eclipse.jdt.internal.corext.Assert.isNotNull(Assert.java:99) at org.eclipse.jdt.internal.corext.refactoring.structure.InstanceMethodM over.checkInput(InstanceMethodMover.java:1848) at org.eclipse.jdt.internal.corext.refactoring.structure.MoveInstanceMet hodRefactoring.checkInput(MoveInstanceMethodRefactoring.java:158) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run( CheckConditionsOperation.java:59) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run(Cre ateChangeOperation.java:94) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run(Pe rformChangeOperation.java:138) at org.eclipse.jface.operation.ModalContext.runInCurrentThread(ModalCont ext.java:296) ... 43 more
|
resolved fixed
|
df97c0f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-27T12:15:29Z | 2003-01-26T00:13:20Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/MoveInstanceMethodInputPage.java
| |
29,805 |
Bug 29805 Resolve end symbol problem in Open Type dialog
|
Build I20030115 Here is the proposal we want to implement (it is pretty much what Randy Hudson proposed): The user must explicitly disable the adding of the wildcard by using a special end symbol. But instead of using the '.' JDT proposes to use the % character. Here are the reasons: - '.' is used in fully qualified name as a separator. The open type dialog already supports entering qualified names (e.g. junit.framework.* shows all types in the framework package). So it will be confusing if we use it as the end symbol as well. - '$' is used by various Unix tools (grep, ...) to denote the end symbol, but it is as legal character inside a Java identifier. Some generated classes inside rt.jar contain a $ character. - so we have to use a character that is not a legal character for Java identifiers. We tried several operators and we decide to go for the % since it is easy to recognize and easy to type. I have opened the bug to further track this issue. Please add comments to this bug instead of replying to this post since bugs are easier trackable.
|
resolved fixed
|
914191c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-27T13:56:27Z | 2003-01-20T16:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/actions/OpenBuildPathDialogAction.java
| |
29,805 |
Bug 29805 Resolve end symbol problem in Open Type dialog
|
Build I20030115 Here is the proposal we want to implement (it is pretty much what Randy Hudson proposed): The user must explicitly disable the adding of the wildcard by using a special end symbol. But instead of using the '.' JDT proposes to use the % character. Here are the reasons: - '.' is used in fully qualified name as a separator. The open type dialog already supports entering qualified names (e.g. junit.framework.* shows all types in the framework package). So it will be confusing if we use it as the end symbol as well. - '$' is used by various Unix tools (grep, ...) to denote the end symbol, but it is as legal character inside a Java identifier. Some generated classes inside rt.jar contain a $ character. - so we have to use a character that is not a legal character for Java identifiers. We tried several operators and we decide to go for the % since it is easy to recognize and easy to type. I have opened the bug to further track this issue. Please add comments to this bug instead of replying to this post since bugs are easier trackable.
|
resolved fixed
|
914191c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-27T13:56:27Z | 2003-01-20T16:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/dialogs/BuildPathDialog.java
| |
29,805 |
Bug 29805 Resolve end symbol problem in Open Type dialog
|
Build I20030115 Here is the proposal we want to implement (it is pretty much what Randy Hudson proposed): The user must explicitly disable the adding of the wildcard by using a special end symbol. But instead of using the '.' JDT proposes to use the % character. Here are the reasons: - '.' is used in fully qualified name as a separator. The open type dialog already supports entering qualified names (e.g. junit.framework.* shows all types in the framework package). So it will be confusing if we use it as the end symbol as well. - '$' is used by various Unix tools (grep, ...) to denote the end symbol, but it is as legal character inside a Java identifier. Some generated classes inside rt.jar contain a $ character. - so we have to use a character that is not a legal character for Java identifiers. We tried several operators and we decide to go for the % since it is easy to recognize and easy to type. I have opened the bug to further track this issue. Please add comments to this bug instead of replying to this post since bugs are easier trackable.
|
resolved fixed
|
914191c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-27T13:56:27Z | 2003-01-20T16:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/dialogs/TypeSelectionDialog.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.dialogs;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableContext;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.util.Assert;
import org.eclipse.ui.dialogs.FilteredList;
import org.eclipse.ui.dialogs.TwoPaneElementSelector;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.internal.corext.util.AllTypesCache;
import org.eclipse.jdt.internal.corext.util.Strings;
import org.eclipse.jdt.internal.corext.util.TypeInfo;
import org.eclipse.jdt.internal.ui.JavaUIMessages;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.util.StringMatcher;
import org.eclipse.jdt.internal.ui.util.TypeInfoLabelProvider;
/**
* A dialog to select a type from a list of types.
*/
public class TypeSelectionDialog extends TwoPaneElementSelector {
private static class TypeFilterMatcher implements FilteredList.FilterMatcher {
private StringMatcher fMatcher;
private StringMatcher fQualifierMatcher;
/*
* @see FilteredList.FilterMatcher#setFilter(String, boolean)
*/
public void setFilter(String pattern, boolean ignoreCase, boolean igoreWildCards) {
int qualifierIndex= pattern.lastIndexOf("."); //$NON-NLS-1$
// type
if (qualifierIndex == -1) {
fQualifierMatcher= null;
fMatcher= new StringMatcher(adjustPattern(pattern), ignoreCase, igoreWildCards);
// qualified type
} else {
fQualifierMatcher= new StringMatcher(pattern.substring(0, qualifierIndex), ignoreCase, igoreWildCards);
fMatcher= new StringMatcher(adjustPattern(pattern.substring(qualifierIndex + 1)), ignoreCase, igoreWildCards);
}
}
/*
* @see FilteredList.FilterMatcher#match(Object)
*/
public boolean match(Object element) {
if (!(element instanceof TypeInfo))
return false;
TypeInfo type= (TypeInfo) element;
if (!fMatcher.match(type.getTypeName()))
return false;
if (fQualifierMatcher == null)
return true;
return fQualifierMatcher.match(type.getTypeContainerName());
}
private String adjustPattern(String pattern) {
if (pattern.length() != 0 && pattern.indexOf('*') == -1 && pattern.indexOf('?') == -1)
return pattern + '*';
else
return pattern;
}
}
/*
* A string comparator which is aware of obfuscated code
* (type names starting with lower case characters).
*/
private static class StringComparator implements Comparator {
public int compare(Object left, Object right) {
String leftString= (String) left;
String rightString= (String) right;
if (Strings.isLowerCase(leftString.charAt(0)) &&
!Strings.isLowerCase(rightString.charAt(0)))
return +1;
if (Strings.isLowerCase(rightString.charAt(0)) &&
!Strings.isLowerCase(leftString.charAt(0)))
return -1;
int result= leftString.compareToIgnoreCase(rightString);
if (result == 0)
result= leftString.compareTo(rightString);
return result;
}
}
private IRunnableContext fRunnableContext;
private IJavaSearchScope fScope;
private int fElementKinds;
/**
* Constructs a type selection dialog.
* @param parent the parent shell.
* @param context the runnable context.
* @param elementKinds <code>IJavaSearchConstants.CLASS</code>, <code>IJavaSearchConstants.INTERFACE</code>
* or <code>IJavaSearchConstants.TYPE</code>
* @param scope the java search scope.
*/
public TypeSelectionDialog(Shell parent, IRunnableContext context, int elementKinds, IJavaSearchScope scope) {
super(parent, new TypeInfoLabelProvider(TypeInfoLabelProvider.SHOW_TYPE_ONLY),
new TypeInfoLabelProvider(TypeInfoLabelProvider.SHOW_TYPE_CONTAINER_ONLY + TypeInfoLabelProvider.SHOW_ROOT_POSTFIX));
Assert.isNotNull(context);
Assert.isNotNull(scope);
fRunnableContext= context;
fScope= scope;
fElementKinds= elementKinds;
setUpperListLabel(JavaUIMessages.getString("TypeSelectionDialog.upperLabel")); //$NON-NLS-1$
setLowerListLabel(JavaUIMessages.getString("TypeSelectionDialog.lowerLabel")); //$NON-NLS-1$
}
/*
* @see AbstractElementListSelectionDialog#createFilteredList(Composite)
*/
protected FilteredList createFilteredList(Composite parent) {
FilteredList list= super.createFilteredList(parent);
fFilteredList.setFilterMatcher(new TypeFilterMatcher());
fFilteredList.setComparator(new StringComparator());
return list;
}
/*
* @see org.eclipse.jface.window.Window#open()
*/
public int open() {
final ArrayList typeList= new ArrayList();
if (AllTypesCache.isCacheUpToDate()) {
// run without progress monitor
try {
AllTypesCache.getTypes(fScope, fElementKinds, null, typeList);
} catch (JavaModelException e) {
ExceptionHandler.handle(e, JavaUIMessages.getString("TypeSelectionDialog.error2Title"), JavaUIMessages.getString("TypeSelectionDialog.error2Message")); //$NON-NLS-1$ //$NON-NLS-2$
return CANCEL;
}
} else {
IRunnableWithProgress runnable= new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
try {
AllTypesCache.getTypes(fScope, fElementKinds, monitor, typeList);
} catch (JavaModelException e) {
throw new InvocationTargetException(e);
}
if (monitor.isCanceled()) {
throw new InterruptedException();
}
}
};
try {
fRunnableContext.run(true, true, runnable);
} catch (InvocationTargetException e) {
ExceptionHandler.handle(e, JavaUIMessages.getString("TypeSelectionDialog.error3Title"), JavaUIMessages.getString("TypeSelectionDialog.error3Message")); //$NON-NLS-1$ //$NON-NLS-2$
return CANCEL;
} catch (InterruptedException e) {
// cancelled by user
return CANCEL;
}
}
if (typeList.isEmpty()) {
String title= JavaUIMessages.getString("TypeSelectionDialog.notypes.title"); //$NON-NLS-1$
String message= JavaUIMessages.getString("TypeSelectionDialog.notypes.message"); //$NON-NLS-1$
MessageDialog.openInformation(getShell(), title, message);
return CANCEL;
}
TypeInfo[] typeRefs= (TypeInfo[])typeList.toArray(new TypeInfo[typeList.size()]);
setElements(typeRefs);
return super.open();
}
/**
* @see SelectionStatusDialog#computeResult()
*/
protected void computeResult() {
TypeInfo ref= (TypeInfo) getLowerSelectedElement();
if (ref == null)
return;
try {
IType type= ref.resolveType(fScope);
if (type == null) {
// not a class file or compilation unit
String title= JavaUIMessages.getString("TypeSelectionDialog.errorTitle"); //$NON-NLS-1$
String message= JavaUIMessages.getFormattedString("TypeSelectionDialog.dialogMessage", ref.getPath()); //$NON-NLS-1$
MessageDialog.openError(getShell(), title, message);
setResult(null);
} else {
List result= new ArrayList(1);
result.add(type);
setResult(result);
}
} catch (JavaModelException e) {
String title= JavaUIMessages.getString("TypeSelectionDialog.errorTitle"); //$NON-NLS-1$
String message= JavaUIMessages.getString("TypeSelectionDialog.errorMessage"); //$NON-NLS-1$
ErrorDialog.openError(getShell(), title, message, e.getStatus());
setResult(null);
}
}
}
|
29,525 |
Bug 29525 moving source file from one source folder to the other caused NullPointerException
|
Not strictly reproducible, the source folders are in the same project, source and destination package have the same name. This is the complete stack trace, note the contained stack trace starting at: "Caused by: java.lang.NullPointerException" java.lang.reflect.InvocationTargetException at org.eclipse.jface.operation.ModalContext.runInCurrentThread(ModalContext.java:307) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:246) at org.eclipse.jface.window.ApplicationWindow$1.run(ApplicationWindow.java:432) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:65) at org.eclipse.jface.window.ApplicationWindow.run(ApplicationWindow.java:429) at org.eclipse.ui.internal.WorkbenchWindow.run(WorkbenchWindow.java:1174) at org.eclipse.jdt.internal.ui.reorg.JdtMoveAction.doReorg(JdtMoveAction.java:140) at org.eclipse.jdt.internal.ui.reorg.ReorgDestinationAction.run(ReorgDestinationAction.java:116) at org.eclipse.jdt.internal.ui.reorg.JdtMoveAction.run(JdtMoveAction.java:68) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun(SelectionDispatchAction.java:191) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run(SelectionDispatchAction.java:169) at org.eclipse.jdt.internal.ui.packageview.SelectionTransferDropAdapter.handleDropMove(SelectionTransferDropAdapter.java:238) at org.eclipse.jdt.internal.ui.packageview.SelectionTransferDropAdapter.drop(SelectionTransferDropAdapter.java:142) at org.eclipse.jdt.internal.ui.dnd.JdtViewerDropAdapter.drop(JdtViewerDropAdapter.java:106) at org.eclipse.jdt.internal.ui.dnd.DelegatingDropAdapter.drop(DelegatingDropAdapter.java:73) at org.eclipse.swt.dnd.DNDListener.handleEvent(DNDListener.java:61) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:836) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:861) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:845) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:652) at org.eclipse.swt.dnd.DropTarget.notifyListeners(DropTarget.java:558) at org.eclipse.swt.dnd.DropTarget.Drop(DropTarget.java:495) at org.eclipse.swt.dnd.DropTarget.access$7(DropTarget.java:423) at org.eclipse.swt.dnd.DropTarget$3.method6(DropTarget.java:214) at org.eclipse.swt.internal.ole.win32.COMObject.callback6(COMObject.java:111) at org.eclipse.swt.internal.ole.win32.COM.DoDragDrop(Native Method) at org.eclipse.swt.dnd.DragSource.drag(DragSource.java:298) at org.eclipse.swt.dnd.DragSource.access$0(DragSource.java:279) at org.eclipse.swt.dnd.DragSource$1.handleEvent(DragSource.java:146) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:836) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1692) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1410) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1467) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1450) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:845) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:462) 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:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539) Caused by: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.refactoring.reorg.MoveRefactoring.checkReferencesToNotPublicTypes(MoveRefactoring.java:108) at org.eclipse.jdt.internal.corext.refactoring.reorg.MoveRefactoring.checkInput(MoveRefactoring.java:82) at org.eclipse.jdt.internal.corext.refactoring.base.Refactoring.checkPreconditions(Refactoring.java:72) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run(CheckConditionsOperation.java:55) at org.eclipse.jface.operation.ModalContext.runInCurrentThread(ModalContext.java:296) ... 44 more
|
resolved fixed
|
bbae512
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-27T13:59:33Z | 2003-01-15T11:26:40Z |
org.eclipse.jdt.ui/core
| |
29,525 |
Bug 29525 moving source file from one source folder to the other caused NullPointerException
|
Not strictly reproducible, the source folders are in the same project, source and destination package have the same name. This is the complete stack trace, note the contained stack trace starting at: "Caused by: java.lang.NullPointerException" java.lang.reflect.InvocationTargetException at org.eclipse.jface.operation.ModalContext.runInCurrentThread(ModalContext.java:307) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:246) at org.eclipse.jface.window.ApplicationWindow$1.run(ApplicationWindow.java:432) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:65) at org.eclipse.jface.window.ApplicationWindow.run(ApplicationWindow.java:429) at org.eclipse.ui.internal.WorkbenchWindow.run(WorkbenchWindow.java:1174) at org.eclipse.jdt.internal.ui.reorg.JdtMoveAction.doReorg(JdtMoveAction.java:140) at org.eclipse.jdt.internal.ui.reorg.ReorgDestinationAction.run(ReorgDestinationAction.java:116) at org.eclipse.jdt.internal.ui.reorg.JdtMoveAction.run(JdtMoveAction.java:68) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun(SelectionDispatchAction.java:191) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run(SelectionDispatchAction.java:169) at org.eclipse.jdt.internal.ui.packageview.SelectionTransferDropAdapter.handleDropMove(SelectionTransferDropAdapter.java:238) at org.eclipse.jdt.internal.ui.packageview.SelectionTransferDropAdapter.drop(SelectionTransferDropAdapter.java:142) at org.eclipse.jdt.internal.ui.dnd.JdtViewerDropAdapter.drop(JdtViewerDropAdapter.java:106) at org.eclipse.jdt.internal.ui.dnd.DelegatingDropAdapter.drop(DelegatingDropAdapter.java:73) at org.eclipse.swt.dnd.DNDListener.handleEvent(DNDListener.java:61) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:836) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:861) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:845) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:652) at org.eclipse.swt.dnd.DropTarget.notifyListeners(DropTarget.java:558) at org.eclipse.swt.dnd.DropTarget.Drop(DropTarget.java:495) at org.eclipse.swt.dnd.DropTarget.access$7(DropTarget.java:423) at org.eclipse.swt.dnd.DropTarget$3.method6(DropTarget.java:214) at org.eclipse.swt.internal.ole.win32.COMObject.callback6(COMObject.java:111) at org.eclipse.swt.internal.ole.win32.COM.DoDragDrop(Native Method) at org.eclipse.swt.dnd.DragSource.drag(DragSource.java:298) at org.eclipse.swt.dnd.DragSource.access$0(DragSource.java:279) at org.eclipse.swt.dnd.DragSource$1.handleEvent(DragSource.java:146) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:836) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1692) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1410) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1467) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1450) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:845) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:462) 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:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539) Caused by: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.refactoring.reorg.MoveRefactoring.checkReferencesToNotPublicTypes(MoveRefactoring.java:108) at org.eclipse.jdt.internal.corext.refactoring.reorg.MoveRefactoring.checkInput(MoveRefactoring.java:82) at org.eclipse.jdt.internal.corext.refactoring.base.Refactoring.checkPreconditions(Refactoring.java:72) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run(CheckConditionsOperation.java:55) at org.eclipse.jface.operation.ModalContext.runInCurrentThread(ModalContext.java:296) ... 44 more
|
resolved fixed
|
bbae512
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-27T13:59:33Z | 2003-01-15T11:26:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/reorg/MoveRefactoring.java
| |
28,400 |
Bug 28400 JavaEditorPreferencePage and JavaColorManager leak Colors
|
20021216 everytime you do this: 1. open java editor pref page 2. close the pref page you end up having allocated and not disposed 8 colors 1 is allocated like this at org.eclipse.jdt.internal.ui.preferences.JavaEditorPreferencePage.createColor(JavaEditorPreferencePage.java:560) at org.eclipse.jdt.internal.ui.preferences.JavaEditorPreferencePage.initializeViewerColors(JavaEditorPreferencePage.java:534) at org.eclipse.jdt.internal.ui.preferences.JavaEditorPreferencePage.createPreviewer(JavaEditorPreferencePage.java:493) at org.eclipse.jdt.internal.ui.preferences.JavaEditorPreferencePage.createSyntaxPage(JavaEditorPreferencePage.java:433) at org.eclipse.jdt.internal.ui.preferences.JavaEditorPreferencePage.createContents(JavaEditorPreferencePage.java:942) at org.eclipse.jface.preference.PreferencePage.createControl(PreferencePage.java:209) and the other 7 are allocated like this: at org.eclipse.jdt.internal.ui.text.JavaColorManager.getColor(JavaColorManager.java:62) at org.eclipse.jdt.internal.ui.text.JavaColorManager.getColor(JavaColorManager.java:85) at org.eclipse.jdt.internal.ui.text.AbstractJavaScanner.addToken(AbstractJavaScanner.java:90) at org.eclipse.jdt.internal.ui.text.AbstractJavaScanner.initialize(AbstractJavaScanner.java:75) at org.eclipse.jdt.internal.ui.text.java.JavaCodeScanner.<init>(JavaCodeScanner.java:126) at org.eclipse.jdt.ui.text.JavaTextTools.<init>(JavaTextTools.java:80) at org.eclipse.jdt.internal.ui.preferences.JavaEditorPreferencePage.createPreviewer(JavaEditorPreferencePage.java:486) at org.eclipse.jdt.internal.ui.preferences.JavaEditorPreferencePage.createSyntaxPage(JavaEditorPreferencePage.java:433) at org.eclipse.jdt.internal.ui.preferences.JavaEditorPreferencePage.createContents(JavaEditorPreferencePage.java:942) at org.eclipse.jface.preference.PreferencePage.createControl(PreferencePage.java:209)
|
resolved fixed
|
64feff4
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-27T17:20:04Z | 2002-12-16T17:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/JavaEditorPreferencePage.java
|
/**********************************************************************
Copyright (c) 2000, 2002 IBM Corp. 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 implementation
**********************************************************************/
package org.eclipse.jdt.internal.ui.preferences;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowLayout;
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.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentPartitioner;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jdt.internal.ui.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.util.TabFolderLayout;
/*
* The page for setting the editor options.
*/
public class JavaEditorPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
private static final String BOLD= PreferenceConstants.EDITOR_BOLD_SUFFIX;
public final OverlayPreferenceStore.OverlayKey[] fKeys= new OverlayPreferenceStore.OverlayKey[] {
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_FOREGROUND_COLOR),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_FOREGROUND_DEFAULT_COLOR),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_BACKGROUND_COLOR),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.INT, PreferenceConstants.EDITOR_TAB_WIDTH),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_COLOR),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_BOLD),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_COLOR),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_BOLD),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_JAVA_KEYWORD_COLOR),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_JAVA_KEYWORD_BOLD),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_STRING_COLOR),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_STRING_BOLD),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_JAVA_DEFAULT_COLOR),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_JAVA_DEFAULT_BOLD),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_JAVADOC_KEYWORD_COLOR),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_JAVADOC_KEYWORD_BOLD),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_JAVADOC_TAG_BOLD),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_JAVADOC_TAG_BOLD),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_JAVADOC_LINKS_COLOR),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_JAVADOC_LINKS_BOLD),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_JAVADOC_DEFAULT_COLOR),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_JAVADOC_DEFAULT_BOLD),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_MATCHING_BRACKETS),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_CURRENT_LINE_COLOR),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_CURRENT_LINE),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.INT, PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_PRINT_MARGIN),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_FIND_SCOPE_COLOR),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_LINKED_POSITION_COLOR),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_LINK_COLOR),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_PROBLEM_INDICATION),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_WARNING_INDICATION_COLOR),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_WARNING_INDICATION),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_TASK_INDICATION_COLOR),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_TASK_INDICATION),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_BOOKMARK_INDICATION_COLOR),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_BOOKMARK_INDICATION),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_COLOR),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_UNKNOWN_INDICATION_COLOR),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_UNKNOWN_INDICATION),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_CORRECTION_INDICATION),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_OVERVIEW_RULER),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_LINE_NUMBER_RULER),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SPACES_FOR_TABS),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_AUTOACTIVATION),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.INT, PreferenceConstants.CODEASSIST_AUTOACTIVATION_DELAY),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_AUTOINSERT),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_PARAMETERS_BACKGROUND),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_PARAMETERS_FOREGROUND),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_REPLACEMENT_BACKGROUND),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_REPLACEMENT_FOREGROUND),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_SHOW_VISIBLE_PROPOSALS),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_ORDER_PROPOSALS),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_CASE_SENSITIVITY),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_ADDIMPORT),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_INSERT_COMPLETION),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.CODEASSIST_GUESS_METHOD_ARGUMENTS),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SMART_PASTE),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_CLOSE_STRINGS),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_CLOSE_BRACKETS),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_CLOSE_BRACES),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_CLOSE_JAVADOCS),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_WRAP_STRINGS),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_FORMAT_JAVADOCS),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, PreferenceConstants.EDITOR_SMART_HOME_END),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS)
};
private final String[][] fSyntaxColorListModel= new String[][] {
{ PreferencesMessages.getString("JavaEditorPreferencePage.multiLineComment"), PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_COLOR }, //$NON-NLS-1$
{ PreferencesMessages.getString("JavaEditorPreferencePage.singleLineComment"), PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_COLOR }, //$NON-NLS-1$
{ PreferencesMessages.getString("JavaEditorPreferencePage.keywords"), PreferenceConstants.EDITOR_JAVA_KEYWORD_COLOR }, //$NON-NLS-1$
{ PreferencesMessages.getString("JavaEditorPreferencePage.strings"), PreferenceConstants.EDITOR_STRING_COLOR }, //$NON-NLS-1$
{ PreferencesMessages.getString("JavaEditorPreferencePage.others"), PreferenceConstants.EDITOR_JAVA_DEFAULT_COLOR }, //$NON-NLS-1$
{ PreferencesMessages.getString("JavaEditorPreferencePage.javaDocKeywords"), PreferenceConstants.EDITOR_JAVADOC_KEYWORD_COLOR }, //$NON-NLS-1$
{ PreferencesMessages.getString("JavaEditorPreferencePage.javaDocHtmlTags"), PreferenceConstants.EDITOR_JAVADOC_TAG_BOLD }, //$NON-NLS-1$
{ PreferencesMessages.getString("JavaEditorPreferencePage.javaDocLinks"), PreferenceConstants.EDITOR_JAVADOC_LINKS_COLOR }, //$NON-NLS-1$
{ PreferencesMessages.getString("JavaEditorPreferencePage.javaDocOthers"), PreferenceConstants.EDITOR_JAVADOC_DEFAULT_COLOR } //$NON-NLS-1$
};
private final String[][] fAppearanceColorListModel= new String[][] {
{PreferencesMessages.getString("JavaEditorPreferencePage.lineNumberForegroundColor"), PreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR}, //$NON-NLS-1$
{PreferencesMessages.getString("JavaEditorPreferencePage.matchingBracketsHighlightColor2"), PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR}, //$NON-NLS-1$
{PreferencesMessages.getString("JavaEditorPreferencePage.currentLineHighlighColor"), PreferenceConstants.EDITOR_CURRENT_LINE_COLOR}, //$NON-NLS-1$
{PreferencesMessages.getString("JavaEditorPreferencePage.printMarginColor2"), PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR}, //$NON-NLS-1$
{PreferencesMessages.getString("JavaEditorPreferencePage.findScopeColor2"), PreferenceConstants.EDITOR_FIND_SCOPE_COLOR}, //$NON-NLS-1$
{PreferencesMessages.getString("JavaEditorPreferencePage.linkedPositionColor2"), PreferenceConstants.EDITOR_LINKED_POSITION_COLOR}, //$NON-NLS-1$
{PreferencesMessages.getString("JavaEditorPreferencePage.linkColor2"), PreferenceConstants.EDITOR_LINK_COLOR}, //$NON-NLS-1$
};
private final String[][] fAnnotationColorListModel= new String[][] {
{PreferencesMessages.getString("JavaEditorPreferencePage.annotations.errors"), PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR, PreferenceConstants.EDITOR_PROBLEM_INDICATION, PreferenceConstants.EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER }, //$NON-NLS-1$
{PreferencesMessages.getString("JavaEditorPreferencePage.annotations.warnings"), PreferenceConstants.EDITOR_WARNING_INDICATION_COLOR, PreferenceConstants.EDITOR_WARNING_INDICATION, PreferenceConstants.EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER }, //$NON-NLS-1$
{PreferencesMessages.getString("JavaEditorPreferencePage.annotations.tasks"), PreferenceConstants.EDITOR_TASK_INDICATION_COLOR, PreferenceConstants.EDITOR_TASK_INDICATION, PreferenceConstants.EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER }, //$NON-NLS-1$
{PreferencesMessages.getString("JavaEditorPreferencePage.annotations.searchResults"), PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_COLOR, PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION, PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER }, //$NON-NLS-1$
{PreferencesMessages.getString("JavaEditorPreferencePage.annotations.bookmarks"), PreferenceConstants.EDITOR_BOOKMARK_INDICATION_COLOR, PreferenceConstants.EDITOR_BOOKMARK_INDICATION, PreferenceConstants.EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER }, //$NON-NLS-1$
{PreferencesMessages.getString("JavaEditorPreferencePage.annotations.others"), PreferenceConstants.EDITOR_UNKNOWN_INDICATION_COLOR, PreferenceConstants.EDITOR_UNKNOWN_INDICATION, PreferenceConstants.EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER } //$NON-NLS-1$
};
private final String[][] fContentAssistColorListModel= new String[][] {
{PreferencesMessages.getString("JavaEditorPreferencePage.backgroundForCompletionProposals"), PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND }, //$NON-NLS-1$
{PreferencesMessages.getString("JavaEditorPreferencePage.foregroundForCompletionProposals"), PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND }, //$NON-NLS-1$
{PreferencesMessages.getString("JavaEditorPreferencePage.backgroundForMethodParameters"), PreferenceConstants.CODEASSIST_PARAMETERS_BACKGROUND }, //$NON-NLS-1$
{PreferencesMessages.getString("JavaEditorPreferencePage.foregroundForMethodParameters"), PreferenceConstants.CODEASSIST_PARAMETERS_FOREGROUND }, //$NON-NLS-1$
{PreferencesMessages.getString("JavaEditorPreferencePage.backgroundForCompletionReplacement"), PreferenceConstants.CODEASSIST_REPLACEMENT_BACKGROUND }, //$NON-NLS-1$
{PreferencesMessages.getString("JavaEditorPreferencePage.foregroundForCompletionReplacement"), PreferenceConstants.CODEASSIST_REPLACEMENT_FOREGROUND } //$NON-NLS-1$
};
private OverlayPreferenceStore fOverlayStore;
private JavaTextTools fJavaTextTools;
private JavaEditorHoverConfigurationBlock fJavaEditorHoverConfigurationBlock;
private Map fColorButtons= new HashMap();
private SelectionListener fColorButtonListener= new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
}
public void widgetSelected(SelectionEvent e) {
ColorEditor editor= (ColorEditor) e.widget.getData();
PreferenceConverter.setValue(fOverlayStore, (String) fColorButtons.get(editor), editor.getColorValue());
}
};
private Map fCheckBoxes= new HashMap();
private SelectionListener fCheckBoxListener= new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
}
public void widgetSelected(SelectionEvent e) {
Button button= (Button) e.widget;
fOverlayStore.setValue((String) fCheckBoxes.get(button), button.getSelection());
}
};
private Map fTextFields= new HashMap();
private ModifyListener fTextFieldListener= new ModifyListener() {
public void modifyText(ModifyEvent e) {
Text text= (Text) e.widget;
fOverlayStore.setValue((String) fTextFields.get(text), text.getText());
}
};
private ArrayList fNumberFields= new ArrayList();
private ModifyListener fNumberFieldListener= new ModifyListener() {
public void modifyText(ModifyEvent e) {
numberFieldChanged((Text) e.widget);
}
};
private List fSyntaxColorList;
private List fAppearanceColorList;
private List fContentAssistColorList;
private List fAnnotationList;
private ColorEditor fSyntaxForegroundColorEditor;
private ColorEditor fAppearanceColorEditor;
private ColorEditor fAnnotationForegroundColorEditor;
private ColorEditor fContentAssistColorEditor;
private ColorEditor fBackgroundColorEditor;
private Button fBackgroundDefaultRadioButton;
private Button fBackgroundCustomRadioButton;
private Button fBackgroundColorButton;
private Button fBoldCheckBox;
private Button fAddJavaDocTagsButton;
private Button fGuessMethodArgumentsButton;
private SourceViewer fPreviewViewer;
private Color fBackgroundColor;
private Control fAutoInsertDelayText;
private Control fAutoInsertJavaTriggerText;
private Control fAutoInsertJavaDocTriggerText;
private Button fShowInTextCheckBox;
private Button fShowInOverviewRulerCheckBox;
public JavaEditorPreferencePage() {
setDescription(PreferencesMessages.getString("JavaEditorPreferencePage.description")); //$NON-NLS-1$
setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore());
fOverlayStore= new OverlayPreferenceStore(getPreferenceStore(), fKeys);
}
/*
* @see IWorkbenchPreferencePage#init()
*/
public void init(IWorkbench workbench) {
}
/*
* @see PreferencePage#createControl(Composite)
*/
public void createControl(Composite parent) {
super.createControl(parent);
WorkbenchHelp.setHelp(getControl(), IJavaHelpContextIds.JAVA_EDITOR_PREFERENCE_PAGE);
}
private void handleSyntaxColorListSelection() {
int i= fSyntaxColorList.getSelectionIndex();
String key= fSyntaxColorListModel[i][1];
RGB rgb= PreferenceConverter.getColor(fOverlayStore, key);
fSyntaxForegroundColorEditor.setColorValue(rgb);
fBoldCheckBox.setSelection(fOverlayStore.getBoolean(key + BOLD));
}
private void handleAppearanceColorListSelection() {
int i= fAppearanceColorList.getSelectionIndex();
String key= fAppearanceColorListModel[i][1];
RGB rgb= PreferenceConverter.getColor(fOverlayStore, key);
fAppearanceColorEditor.setColorValue(rgb);
}
private void handleContentAssistColorListSelection() {
int i= fContentAssistColorList.getSelectionIndex();
String key= fContentAssistColorListModel[i][1];
RGB rgb= PreferenceConverter.getColor(fOverlayStore, key);
fContentAssistColorEditor.setColorValue(rgb);
}
private void handleAnnotationListSelection() {
int i= fAnnotationList.getSelectionIndex();
String key= fAnnotationColorListModel[i][1];
RGB rgb= PreferenceConverter.getColor(fOverlayStore, key);
fAnnotationForegroundColorEditor.setColorValue(rgb);
key= fAnnotationColorListModel[i][2];
fShowInTextCheckBox.setSelection(fOverlayStore.getBoolean(key));
key= fAnnotationColorListModel[i][3];
fShowInOverviewRulerCheckBox.setSelection(fOverlayStore.getBoolean(key));
}
private Control createSyntaxPage(Composite parent) {
Composite colorComposite= new Composite(parent, SWT.NULL);
colorComposite.setLayout(new GridLayout());
Group backgroundComposite= new Group(colorComposite, SWT.SHADOW_ETCHED_IN);
backgroundComposite.setLayout(new RowLayout());
backgroundComposite.setText(PreferencesMessages.getString("JavaEditorPreferencePage.backgroundColor"));//$NON-NLS-1$
SelectionListener backgroundSelectionListener= new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
boolean custom= fBackgroundCustomRadioButton.getSelection();
fBackgroundColorButton.setEnabled(custom);
fOverlayStore.setValue(PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR, !custom);
}
public void widgetDefaultSelected(SelectionEvent e) {}
};
fBackgroundDefaultRadioButton= new Button(backgroundComposite, SWT.RADIO | SWT.LEFT);
fBackgroundDefaultRadioButton.setText(PreferencesMessages.getString("JavaEditorPreferencePage.systemDefault")); //$NON-NLS-1$
fBackgroundDefaultRadioButton.addSelectionListener(backgroundSelectionListener);
fBackgroundCustomRadioButton= new Button(backgroundComposite, SWT.RADIO | SWT.LEFT);
fBackgroundCustomRadioButton.setText(PreferencesMessages.getString("JavaEditorPreferencePage.custom")); //$NON-NLS-1$
fBackgroundCustomRadioButton.addSelectionListener(backgroundSelectionListener);
fBackgroundColorEditor= new ColorEditor(backgroundComposite);
fBackgroundColorButton= fBackgroundColorEditor.getButton();
Label label= new Label(colorComposite, SWT.LEFT);
label.setText(PreferencesMessages.getString("JavaEditorPreferencePage.foreground")); //$NON-NLS-1$
label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Composite editorComposite= new Composite(colorComposite, SWT.NONE);
GridLayout layout= new GridLayout();
layout.numColumns= 2;
layout.marginHeight= 0;
layout.marginWidth= 0;
editorComposite.setLayout(layout);
GridData gd= new GridData(GridData.FILL_BOTH);
editorComposite.setLayoutData(gd);
fSyntaxColorList= new List(editorComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER);
gd= new GridData(GridData.FILL_BOTH);
gd.heightHint= convertHeightInCharsToPixels(5);
fSyntaxColorList.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));
label= new Label(stylesComposite, SWT.LEFT);
label.setText(PreferencesMessages.getString("JavaEditorPreferencePage.color")); //$NON-NLS-1$
gd= new GridData();
gd.horizontalAlignment= GridData.BEGINNING;
label.setLayoutData(gd);
fSyntaxForegroundColorEditor= new ColorEditor(stylesComposite);
Button foregroundColorButton= fSyntaxForegroundColorEditor.getButton();
gd= new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalAlignment= GridData.BEGINNING;
foregroundColorButton.setLayoutData(gd);
fBoldCheckBox= new Button(stylesComposite, SWT.CHECK);
fBoldCheckBox.setText(PreferencesMessages.getString("JavaEditorPreferencePage.bold")); //$NON-NLS-1$
gd= new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalAlignment= GridData.BEGINNING;
gd.horizontalSpan= 2;
fBoldCheckBox.setLayoutData(gd);
label= new Label(colorComposite, SWT.LEFT);
label.setText(PreferencesMessages.getString("JavaEditorPreferencePage.preview")); //$NON-NLS-1$
label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Control previewer= createPreviewer(colorComposite);
gd= new GridData(GridData.FILL_BOTH);
gd.widthHint= convertWidthInCharsToPixels(20);
gd.heightHint= convertHeightInCharsToPixels(5);
previewer.setLayoutData(gd);
fSyntaxColorList.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
// do nothing
}
public void widgetSelected(SelectionEvent e) {
handleSyntaxColorListSelection();
}
});
foregroundColorButton.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
// do nothing
}
public void widgetSelected(SelectionEvent e) {
int i= fSyntaxColorList.getSelectionIndex();
String key= fSyntaxColorListModel[i][1];
PreferenceConverter.setValue(fOverlayStore, key, fSyntaxForegroundColorEditor.getColorValue());
}
});
fBackgroundColorButton.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
// do nothing
}
public void widgetSelected(SelectionEvent e) {
PreferenceConverter.setValue(fOverlayStore, PreferenceConstants.EDITOR_BACKGROUND_COLOR, fBackgroundColorEditor.getColorValue());
}
});
fBoldCheckBox.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
// do nothing
}
public void widgetSelected(SelectionEvent e) {
int i= fSyntaxColorList.getSelectionIndex();
String key= fSyntaxColorListModel[i][1];
fOverlayStore.setValue(key + BOLD, fBoldCheckBox.getSelection());
}
});
return colorComposite;
}
private Control createPreviewer(Composite parent) {
fJavaTextTools= new JavaTextTools(fOverlayStore);
fPreviewViewer= new SourceViewer(parent, null, SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER);
fPreviewViewer.configure(new JavaSourceViewerConfiguration(fJavaTextTools, null));
fPreviewViewer.getTextWidget().setFont(JFaceResources.getFontRegistry().get(JFaceResources.TEXT_FONT));
fPreviewViewer.setEditable(false);
initializeViewerColors(fPreviewViewer);
String content= loadPreviewContentFromFile("ColorSettingPreviewCode.txt"); //$NON-NLS-1$
IDocument document= new Document(content);
IDocumentPartitioner partitioner= fJavaTextTools.createDocumentPartitioner();
partitioner.connect(document);
document.setDocumentPartitioner(partitioner);
fPreviewViewer.setDocument(document);
fOverlayStore.addPropertyChangeListener(new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
String p= event.getProperty();
if (p.equals(PreferenceConstants.EDITOR_BACKGROUND_COLOR) ||
p.equals(PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR))
{
initializeViewerColors(fPreviewViewer);
}
fPreviewViewer.invalidateTextPresentation();
}
});
return fPreviewViewer.getControl();
}
/**
* Initializes the given viewer's colors.
*
* @param viewer the viewer to be initialized
*/
private void initializeViewerColors(ISourceViewer viewer) {
IPreferenceStore store= fOverlayStore;
if (store != null) {
StyledText styledText= viewer.getTextWidget();
// ---------- background color ----------------------
Color color= store.getBoolean(PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR)
? null
: createColor(store, PreferenceConstants.EDITOR_BACKGROUND_COLOR, styledText.getDisplay());
styledText.setBackground(color);
if (fBackgroundColor != null)
fBackgroundColor.dispose();
fBackgroundColor= color;
}
}
/**
* Creates a color from the information stored in the given preference store.
* Returns <code>null</code> if there is no such information available.
*/
private Color createColor(IPreferenceStore store, String key, Display display) {
RGB rgb= null;
if (store.contains(key)) {
if (store.isDefault(key))
rgb= PreferenceConverter.getDefaultColor(store, key);
else
rgb= PreferenceConverter.getColor(store, key);
if (rgb != null)
return new Color(display, rgb);
}
return null;
}
// sets enabled flag for a control and all its sub-tree
private static void setEnabled(Control control, boolean enable) {
control.setEnabled(enable);
if (control instanceof Composite) {
Composite composite= (Composite) control;
Control[] children= composite.getChildren();
for (int i= 0; i < children.length; i++)
setEnabled(children[i], enable);
}
}
private Control createAppearancePage(Composite parent) {
Composite appearanceComposite= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout(); layout.numColumns= 2;
appearanceComposite.setLayout(layout);
String label= PreferencesMessages.getString("JavaEditorPreferencePage.displayedTabWidth"); //$NON-NLS-1$
addTextField(appearanceComposite, label, PreferenceConstants.EDITOR_TAB_WIDTH, 3, 0, true);
label= PreferencesMessages.getString("JavaEditorPreferencePage.printMarginColumn"); //$NON-NLS-1$
addTextField(appearanceComposite, label, PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN, 3, 0, true);
label= PreferencesMessages.getString("JavaEditorPreferencePage.synchronizeOnCursor"); //$NON-NLS-1$
addCheckBox(appearanceComposite, label, PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE, 0);
label= PreferencesMessages.getString("JavaEditorPreferencePage.showOverviewRuler"); //$NON-NLS-1$
addCheckBox(appearanceComposite, label, PreferenceConstants.EDITOR_OVERVIEW_RULER, 0);
label= PreferencesMessages.getString("JavaEditorPreferencePage.showLineNumbers"); //$NON-NLS-1$
addCheckBox(appearanceComposite, label, PreferenceConstants.EDITOR_LINE_NUMBER_RULER, 0);
label= PreferencesMessages.getString("JavaEditorPreferencePage.highlightMatchingBrackets"); //$NON-NLS-1$
addCheckBox(appearanceComposite, label, PreferenceConstants.EDITOR_MATCHING_BRACKETS, 0);
label= PreferencesMessages.getString("JavaEditorPreferencePage.highlightCurrentLine"); //$NON-NLS-1$
addCheckBox(appearanceComposite, label, PreferenceConstants.EDITOR_CURRENT_LINE, 0);
label= PreferencesMessages.getString("JavaEditorPreferencePage.showPrintMargin"); //$NON-NLS-1$
addCheckBox(appearanceComposite, label, PreferenceConstants.EDITOR_PRINT_MARGIN, 0);
Label l= new Label(appearanceComposite, SWT.LEFT );
GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= 2;
gd.heightHint= convertHeightInCharsToPixels(1) / 2;
l.setLayoutData(gd);
l= new Label(appearanceComposite, SWT.LEFT);
l.setText(PreferencesMessages.getString("JavaEditorPreferencePage.appearanceOptions")); //$NON-NLS-1$
gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= 2;
l.setLayoutData(gd);
Composite editorComposite= new Composite(appearanceComposite, 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);
fAppearanceColorList= new List(editorComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER);
gd= new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL);
gd.heightHint= convertHeightInCharsToPixels(8);
fAppearanceColorList.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));
l= new Label(stylesComposite, SWT.LEFT);
l.setText(PreferencesMessages.getString("JavaEditorPreferencePage.color")); //$NON-NLS-1$
gd= new GridData();
gd.horizontalAlignment= GridData.BEGINNING;
l.setLayoutData(gd);
fAppearanceColorEditor= new ColorEditor(stylesComposite);
Button foregroundColorButton= fAppearanceColorEditor.getButton();
gd= new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalAlignment= GridData.BEGINNING;
foregroundColorButton.setLayoutData(gd);
fAppearanceColorList.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
// do nothing
}
public void widgetSelected(SelectionEvent e) {
handleAppearanceColorListSelection();
}
});
foregroundColorButton.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
// do nothing
}
public void widgetSelected(SelectionEvent e) {
int i= fAppearanceColorList.getSelectionIndex();
String key= fAppearanceColorListModel[i][1];
PreferenceConverter.setValue(fOverlayStore, key, fAppearanceColorEditor.getColorValue());
}
});
return appearanceComposite;
}
private Control createAnnotationsPage(Composite parent) {
Composite composite= new Composite(parent, SWT.NULL);
GridLayout layout= new GridLayout(); layout.numColumns= 2;
composite.setLayout(layout);
String text= PreferencesMessages.getString("JavaEditorPreferencePage.analyseAnnotationsWhileTyping"); //$NON-NLS-1$
addCheckBox(composite, text, PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS, 0);
text= PreferencesMessages.getString("JavaEditorPreferencePage.showQuickFixables"); //$NON-NLS-1$
addCheckBox(composite, text, PreferenceConstants.EDITOR_CORRECTION_INDICATION, 0);
addFiller(composite);
Label label= new Label(composite, SWT.LEFT);
label.setText(PreferencesMessages.getString("JavaEditorPreferencePage.annotationPresentationOptions")); //$NON-NLS-1$
GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= 2;
label.setLayoutData(gd);
Composite editorComposite= new Composite(composite, 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);
fAnnotationList= new List(editorComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER);
gd= new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL);
gd.heightHint= convertHeightInCharsToPixels(8);
fAnnotationList.setLayoutData(gd);
Composite optionsComposite= new Composite(editorComposite, SWT.NONE);
layout= new GridLayout();
layout.marginHeight= 0;
layout.marginWidth= 0;
layout.numColumns= 2;
optionsComposite.setLayout(layout);
optionsComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
fShowInTextCheckBox= new Button(optionsComposite, SWT.CHECK);
fShowInTextCheckBox.setText(PreferencesMessages.getString("JavaEditorPreferencePage.annotations.showInText")); //$NON-NLS-1$
gd= new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalAlignment= GridData.BEGINNING;
gd.horizontalSpan= 2;
fShowInTextCheckBox.setLayoutData(gd);
fShowInOverviewRulerCheckBox= new Button(optionsComposite, SWT.CHECK);
fShowInOverviewRulerCheckBox.setText(PreferencesMessages.getString("JavaEditorPreferencePage.annotations.showInOverviewRuler")); //$NON-NLS-1$
gd= new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalAlignment= GridData.BEGINNING;
gd.horizontalSpan= 2;
fShowInOverviewRulerCheckBox.setLayoutData(gd);
label= new Label(optionsComposite, SWT.LEFT);
label.setText(PreferencesMessages.getString("JavaEditorPreferencePage.annotations.color")); //$NON-NLS-1$
gd= new GridData();
gd.horizontalAlignment= GridData.BEGINNING;
label.setLayoutData(gd);
fAnnotationForegroundColorEditor= new ColorEditor(optionsComposite);
Button foregroundColorButton= fAnnotationForegroundColorEditor.getButton();
gd= new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalAlignment= GridData.BEGINNING;
foregroundColorButton.setLayoutData(gd);
fAnnotationList.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
// do nothing
}
public void widgetSelected(SelectionEvent e) {
handleAnnotationListSelection();
}
});
fShowInTextCheckBox.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
// do nothing
}
public void widgetSelected(SelectionEvent e) {
int i= fAnnotationList.getSelectionIndex();
String key= fAnnotationColorListModel[i][2];
fOverlayStore.setValue(key, fShowInTextCheckBox.getSelection());
}
});
fShowInOverviewRulerCheckBox.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
// do nothing
}
public void widgetSelected(SelectionEvent e) {
int i= fAnnotationList.getSelectionIndex();
String key= fAnnotationColorListModel[i][3];
fOverlayStore.setValue(key, fShowInOverviewRulerCheckBox.getSelection());
}
});
foregroundColorButton.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
// do nothing
}
public void widgetSelected(SelectionEvent e) {
int i= fAnnotationList.getSelectionIndex();
String key= fAnnotationColorListModel[i][1];
PreferenceConverter.setValue(fOverlayStore, key, fAnnotationForegroundColorEditor.getColorValue());
}
});
return composite;
}
private Control createTypingPage(Composite parent) {
Composite composite= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
layout.numColumns= 1;
composite.setLayout(layout);
String label= PreferencesMessages.getString("JavaEditorPreferencePage.smartHomeEnd"); //$NON-NLS-1$
addCheckBox(composite, label, PreferenceConstants.EDITOR_SMART_HOME_END, 1);
addFiller(composite);
Group group= new Group(composite, SWT.NONE);
layout= new GridLayout();
layout.numColumns= 2;
group.setLayout(layout);
group.setText(PreferencesMessages.getString("JavaEditorPreferencePage.typing.description")); //$NON-NLS-1$
label= PreferencesMessages.getString("JavaEditorPreferencePage.wrapStrings"); //$NON-NLS-1$
addCheckBox(group, label, PreferenceConstants.EDITOR_WRAP_STRINGS, 1);
label= PreferencesMessages.getString("JavaEditorPreferencePage.smartPaste"); //$NON-NLS-1$
addCheckBox(group, label, PreferenceConstants.EDITOR_SMART_PASTE, 1);
label= PreferencesMessages.getString("JavaEditorPreferencePage.insertSpaceForTabs"); //$NON-NLS-1$
addCheckBox(group, label, PreferenceConstants.EDITOR_SPACES_FOR_TABS, 1);
label= PreferencesMessages.getString("JavaEditorPreferencePage.closeStrings"); //$NON-NLS-1$
addCheckBox(group, label, PreferenceConstants.EDITOR_CLOSE_STRINGS, 1);
label= PreferencesMessages.getString("JavaEditorPreferencePage.closeBrackets"); //$NON-NLS-1$
addCheckBox(group, label, PreferenceConstants.EDITOR_CLOSE_BRACKETS, 1);
label= PreferencesMessages.getString("JavaEditorPreferencePage.closeBraces"); //$NON-NLS-1$
addCheckBox(group, label, PreferenceConstants.EDITOR_CLOSE_BRACES, 1);
label= PreferencesMessages.getString("JavaEditorPreferencePage.closeJavaDocs"); //$NON-NLS-1$
Button button= addCheckBox(group, label, PreferenceConstants.EDITOR_CLOSE_JAVADOCS, 1);
label= PreferencesMessages.getString("JavaEditorPreferencePage.addJavaDocTags"); //$NON-NLS-1$
fAddJavaDocTagsButton= addCheckBox(group, label, PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS, 1);
createDependency(button, fAddJavaDocTagsButton);
label= PreferencesMessages.getString("JavaEditorPreferencePage.formatJavaDocs"); //$NON-NLS-1$
addCheckBox(group, label, PreferenceConstants.EDITOR_FORMAT_JAVADOCS, 1);
return composite;
}
private void addFiller(Composite composite) {
Label filler= new Label(composite, SWT.LEFT );
GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= 2;
gd.heightHint= convertHeightInCharsToPixels(1) / 2;
filler.setLayoutData(gd);
}
private static void indent(Control control) {
GridData gridData= new GridData();
gridData.horizontalIndent= 20;
control.setLayoutData(gridData);
}
private static void createDependency(final Button master, final Control slave) {
indent(slave);
master.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
slave.setEnabled(master.getSelection());
}
public void widgetDefaultSelected(SelectionEvent e) {}
});
}
private Control createContentAssistPage(Composite parent) {
Composite contentAssistComposite= new Composite(parent, SWT.NULL);
GridLayout layout= new GridLayout(); layout.numColumns= 2;
contentAssistComposite.setLayout(layout);
String label= PreferencesMessages.getString("JavaEditorPreferencePage.insertSingleProposalsAutomatically"); //$NON-NLS-1$
addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_AUTOINSERT, 0);
label= PreferencesMessages.getString("JavaEditorPreferencePage.showOnlyProposalsVisibleInTheInvocationContext"); //$NON-NLS-1$
addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_SHOW_VISIBLE_PROPOSALS, 0);
label= PreferencesMessages.getString("JavaEditorPreferencePage.presentProposalsInAlphabeticalOrder"); //$NON-NLS-1$
addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_ORDER_PROPOSALS, 0);
label= PreferencesMessages.getString("JavaEditorPreferencePage.automaticallyAddImportInsteadOfQualifiedName"); //$NON-NLS-1$
addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_ADDIMPORT, 0);
label= PreferencesMessages.getString("JavaEditorPreferencePage.insertCompletion"); //$NON-NLS-1$
addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_INSERT_COMPLETION, 0);
label= PreferencesMessages.getString("JavaEditorPreferencePage.fillArgumentNamesOnMethodCompletion"); //$NON-NLS-1$
Button button= addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES, 0);
label= PreferencesMessages.getString("JavaEditorPreferencePage.guessArgumentNamesOnMethodCompletion"); //$NON-NLS-1$
fGuessMethodArgumentsButton= addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_GUESS_METHOD_ARGUMENTS, 0);
createDependency(button, fGuessMethodArgumentsButton);
label= PreferencesMessages.getString("JavaEditorPreferencePage.enableAutoActivation"); //$NON-NLS-1$
final Button autoactivation= addCheckBox(contentAssistComposite, label, PreferenceConstants.CODEASSIST_AUTOACTIVATION, 0);
autoactivation.addSelectionListener(new SelectionAdapter(){
public void widgetSelected(SelectionEvent e) {
updateAutoactivationControls();
}
});
label= PreferencesMessages.getString("JavaEditorPreferencePage.autoActivationDelay"); //$NON-NLS-1$
fAutoInsertDelayText= addTextField(contentAssistComposite, label, PreferenceConstants.CODEASSIST_AUTOACTIVATION_DELAY, 4, 0, true);
label= PreferencesMessages.getString("JavaEditorPreferencePage.autoActivationTriggersForJava"); //$NON-NLS-1$
fAutoInsertJavaTriggerText= addTextField(contentAssistComposite, label, PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA, 4, 0, false);
label= PreferencesMessages.getString("JavaEditorPreferencePage.autoActivationTriggersForJavaDoc"); //$NON-NLS-1$
fAutoInsertJavaDocTriggerText= addTextField(contentAssistComposite, label, PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC, 4, 0, false);
Label l= new Label(contentAssistComposite, SWT.LEFT);
l.setText(PreferencesMessages.getString("JavaEditorPreferencePage.codeAssist.colorOptions")); //$NON-NLS-1$
GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= 2;
l.setLayoutData(gd);
Composite editorComposite= new Composite(contentAssistComposite, 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);
fContentAssistColorList= new List(editorComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER);
gd= new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL);
gd.heightHint= convertHeightInCharsToPixels(8);
fContentAssistColorList.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));
l= new Label(stylesComposite, SWT.LEFT);
l.setText(PreferencesMessages.getString("JavaEditorPreferencePage.codeAssist.color")); //$NON-NLS-1$
gd= new GridData();
gd.horizontalAlignment= GridData.BEGINNING;
l.setLayoutData(gd);
fContentAssistColorEditor= new ColorEditor(stylesComposite);
Button colorButton= fContentAssistColorEditor.getButton();
gd= new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalAlignment= GridData.BEGINNING;
colorButton.setLayoutData(gd);
fContentAssistColorList.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
// do nothing
}
public void widgetSelected(SelectionEvent e) {
handleContentAssistColorListSelection();
}
});
colorButton.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
// do nothing
}
public void widgetSelected(SelectionEvent e) {
int i= fContentAssistColorList.getSelectionIndex();
String key= fContentAssistColorListModel[i][1];
PreferenceConverter.setValue(fOverlayStore, key, fContentAssistColorEditor.getColorValue());
}
});
return contentAssistComposite;
}
/*
* @see PreferencePage#createContents(Composite)
*/
protected Control createContents(Composite parent) {
fOverlayStore.load();
fOverlayStore.start();
TabFolder folder= new TabFolder(parent, SWT.NONE);
folder.setLayout(new TabFolderLayout());
folder.setLayoutData(new GridData(GridData.FILL_BOTH));
TabItem item= new TabItem(folder, SWT.NONE);
item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.general")); //$NON-NLS-1$
item.setControl(createAppearancePage(folder));
item= new TabItem(folder, SWT.NONE);
item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.colors")); //$NON-NLS-1$
item.setControl(createSyntaxPage(folder));
item= new TabItem(folder, SWT.NONE);
item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.codeAssist")); //$NON-NLS-1$
item.setControl(createContentAssistPage(folder));
item= new TabItem(folder, SWT.NONE);
item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.annotationsTab.title")); //$NON-NLS-1$
item.setControl(createAnnotationsPage(folder));
item= new TabItem(folder, SWT.NONE);
item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.typing.tabTitle")); //$NON-NLS-1$
item.setControl(createTypingPage(folder));
item= new TabItem(folder, SWT.NONE);
item.setText(PreferencesMessages.getString("JavaEditorPreferencePage.hoverTab.title")); //$NON-NLS-1$
fJavaEditorHoverConfigurationBlock= new JavaEditorHoverConfigurationBlock(this, fOverlayStore);
item.setControl(fJavaEditorHoverConfigurationBlock.createControl(folder));
initialize();
return folder;
}
private void initialize() {
initializeFields();
for (int i= 0; i < fSyntaxColorListModel.length; i++)
fSyntaxColorList.add(fSyntaxColorListModel[i][0]);
fSyntaxColorList.getDisplay().asyncExec(new Runnable() {
public void run() {
if (fSyntaxColorList != null && !fSyntaxColorList.isDisposed()) {
fSyntaxColorList.select(0);
handleSyntaxColorListSelection();
}
}
});
for (int i= 0; i < fAppearanceColorListModel.length; i++)
fAppearanceColorList.add(fAppearanceColorListModel[i][0]);
fAppearanceColorList.getDisplay().asyncExec(new Runnable() {
public void run() {
if (fAppearanceColorList != null && !fAppearanceColorList.isDisposed()) {
fAppearanceColorList.select(0);
handleAppearanceColorListSelection();
}
}
});
for (int i= 0; i < fAnnotationColorListModel.length; i++)
fAnnotationList.add(fAnnotationColorListModel[i][0]);
fAnnotationList.getDisplay().asyncExec(new Runnable() {
public void run() {
if (fAnnotationList != null && !fAnnotationList.isDisposed()) {
fAnnotationList.select(0);
handleAnnotationListSelection();
}
}
});
for (int i= 0; i < fContentAssistColorListModel.length; i++)
fContentAssistColorList.add(fContentAssistColorListModel[i][0]);
fContentAssistColorList.getDisplay().asyncExec(new Runnable() {
public void run() {
if (fContentAssistColorList != null && !fContentAssistColorList.isDisposed()) {
fContentAssistColorList.select(0);
handleContentAssistColorListSelection();
}
}
});
}
private void initializeFields() {
Iterator e= fColorButtons.keySet().iterator();
while (e.hasNext()) {
ColorEditor c= (ColorEditor) e.next();
String key= (String) fColorButtons.get(c);
RGB rgb= PreferenceConverter.getColor(fOverlayStore, key);
c.setColorValue(rgb);
}
e= fCheckBoxes.keySet().iterator();
while (e.hasNext()) {
Button b= (Button) e.next();
String key= (String) fCheckBoxes.get(b);
b.setSelection(fOverlayStore.getBoolean(key));
}
e= fTextFields.keySet().iterator();
while (e.hasNext()) {
Text t= (Text) e.next();
String key= (String) fTextFields.get(t);
t.setText(fOverlayStore.getString(key));
}
RGB rgb= PreferenceConverter.getColor(fOverlayStore, PreferenceConstants.EDITOR_BACKGROUND_COLOR);
fBackgroundColorEditor.setColorValue(rgb);
boolean default_= fOverlayStore.getBoolean(PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR);
fBackgroundDefaultRadioButton.setSelection(default_);
fBackgroundCustomRadioButton.setSelection(!default_);
fBackgroundColorButton.setEnabled(!default_);
boolean closeJavaDocs= fOverlayStore.getBoolean(PreferenceConstants.EDITOR_CLOSE_JAVADOCS);
fAddJavaDocTagsButton.setEnabled(closeJavaDocs);
boolean fillMethodArguments= fOverlayStore.getBoolean(PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES);
fGuessMethodArgumentsButton.setEnabled(fillMethodArguments);
updateAutoactivationControls();
}
private void updateAutoactivationControls() {
boolean autoactivation= fOverlayStore.getBoolean(PreferenceConstants.CODEASSIST_AUTOACTIVATION);
fAutoInsertDelayText.setEnabled(autoactivation);
fAutoInsertJavaTriggerText.setEnabled(autoactivation);
fAutoInsertJavaDocTriggerText.setEnabled(autoactivation);
}
/*
* @see PreferencePage#performOk()
*/
public boolean performOk() {
fJavaEditorHoverConfigurationBlock.performOk();
fOverlayStore.propagate();
JavaPlugin.getDefault().savePluginPreferences();
return true;
}
/*
* @see PreferencePage#performDefaults()
*/
protected void performDefaults() {
fOverlayStore.loadDefaults();
initializeFields();
handleSyntaxColorListSelection();
handleAppearanceColorListSelection();
handleAnnotationListSelection();
handleContentAssistColorListSelection();
fJavaEditorHoverConfigurationBlock.performDefaults();
super.performDefaults();
fPreviewViewer.invalidateTextPresentation();
}
/*
* @see DialogPage#dispose()
*/
public void dispose() {
if (fJavaTextTools != null) {
fJavaTextTools= null;
}
if (fOverlayStore != null) {
fOverlayStore.stop();
fOverlayStore= null;
}
super.dispose();
}
private Control addColorButton(Composite composite, String label, String key, int indentation) {
Label labelControl= new Label(composite, SWT.NONE);
labelControl.setText(label);
GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
gd.horizontalIndent= indentation;
labelControl.setLayoutData(gd);
ColorEditor editor= new ColorEditor(composite);
Button button= editor.getButton();
button.setData(editor);
gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
button.setLayoutData(gd);
button.addSelectionListener(fColorButtonListener);
fColorButtons.put(editor, key);
return composite;
}
private Button addCheckBox(Composite parent, String label, String key, int indentation) {
Button checkBox= new Button(parent, SWT.CHECK);
checkBox.setText(label);
GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
gd.horizontalIndent= indentation;
gd.horizontalSpan= 2;
checkBox.setLayoutData(gd);
checkBox.addSelectionListener(fCheckBoxListener);
fCheckBoxes.put(checkBox, key);
return checkBox;
}
private Control addTextField(Composite composite, String label, String key, int textLimit, int indentation, boolean isNumber) {
Label labelControl= new Label(composite, SWT.NONE);
labelControl.setText(label);
GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
gd.horizontalIndent= indentation;
labelControl.setLayoutData(gd);
Text textControl= new Text(composite, SWT.BORDER | SWT.SINGLE);
gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
gd.widthHint= convertWidthInCharsToPixels(textLimit + 1);
textControl.setLayoutData(gd);
textControl.setTextLimit(textLimit);
fTextFields.put(textControl, key);
if (isNumber) {
fNumberFields.add(textControl);
textControl.addModifyListener(fNumberFieldListener);
} else {
textControl.addModifyListener(fTextFieldListener);
}
return textControl;
}
private void addTextFontEditor(Composite parent, String label, String key) {
Composite editorComposite= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
layout.numColumns= 3;
editorComposite.setLayout(layout);
GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= 2;
editorComposite.setLayoutData(gd);
}
private String loadPreviewContentFromFile(String filename) {
String line;
String separator= System.getProperty("line.separator"); //$NON-NLS-1$
StringBuffer buffer= new StringBuffer(512);
BufferedReader reader= null;
try {
reader= new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(filename)));
while ((line= reader.readLine()) != null) {
buffer.append(line);
buffer.append(separator);
}
} catch (IOException io) {
JavaPlugin.log(io);
} finally {
if (reader != null) {
try { reader.close(); } catch (IOException e) {}
}
}
return buffer.toString();
}
private void numberFieldChanged(Text textControl) {
String number= textControl.getText();
IStatus status= validatePositiveNumber(number);
if (!status.matches(IStatus.ERROR))
fOverlayStore.setValue((String) fTextFields.get(textControl), number);
updateStatus(status);
}
private IStatus validatePositiveNumber(String number) {
StatusInfo status= new StatusInfo();
if (number.length() == 0) {
status.setError(PreferencesMessages.getString("JavaEditorPreferencePage.empty_input")); //$NON-NLS-1$
} else {
try {
int value= Integer.parseInt(number);
if (value < 0)
status.setError(PreferencesMessages.getFormattedString("JavaEditorPreferencePage.invalid_input", number)); //$NON-NLS-1$
} catch (NumberFormatException e) {
status.setError(PreferencesMessages.getFormattedString("JavaEditorPreferencePage.invalid_input", number)); //$NON-NLS-1$
}
}
return status;
}
void updateStatus(IStatus status) {
if (!status.matches(IStatus.ERROR)) {
for (int i= 0; i < fNumberFields.size(); i++) {
Text text= (Text) fNumberFields.get(i);
IStatus s= validatePositiveNumber(text.getText());
status= StatusUtil.getMoreSevere(s, status);
}
}
status= StatusUtil.getMoreSevere(fJavaEditorHoverConfigurationBlock.getStatus(), status);
setValid(!status.matches(IStatus.ERROR));
StatusUtil.applyToStatusLine(this, status);
}
/**
* @deprecated Inline to avoid reference to preference page
*/
public static boolean indicateQuixFixableProblems() {
return PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_CORRECTION_INDICATION);
}
/**
* @deprecated Inline to avoid reference to preference page
*/
static public boolean synchronizeOutlineOnCursorMove() {
return PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE);
}
}
|
28,400 |
Bug 28400 JavaEditorPreferencePage and JavaColorManager leak Colors
|
20021216 everytime you do this: 1. open java editor pref page 2. close the pref page you end up having allocated and not disposed 8 colors 1 is allocated like this at org.eclipse.jdt.internal.ui.preferences.JavaEditorPreferencePage.createColor(JavaEditorPreferencePage.java:560) at org.eclipse.jdt.internal.ui.preferences.JavaEditorPreferencePage.initializeViewerColors(JavaEditorPreferencePage.java:534) at org.eclipse.jdt.internal.ui.preferences.JavaEditorPreferencePage.createPreviewer(JavaEditorPreferencePage.java:493) at org.eclipse.jdt.internal.ui.preferences.JavaEditorPreferencePage.createSyntaxPage(JavaEditorPreferencePage.java:433) at org.eclipse.jdt.internal.ui.preferences.JavaEditorPreferencePage.createContents(JavaEditorPreferencePage.java:942) at org.eclipse.jface.preference.PreferencePage.createControl(PreferencePage.java:209) and the other 7 are allocated like this: at org.eclipse.jdt.internal.ui.text.JavaColorManager.getColor(JavaColorManager.java:62) at org.eclipse.jdt.internal.ui.text.JavaColorManager.getColor(JavaColorManager.java:85) at org.eclipse.jdt.internal.ui.text.AbstractJavaScanner.addToken(AbstractJavaScanner.java:90) at org.eclipse.jdt.internal.ui.text.AbstractJavaScanner.initialize(AbstractJavaScanner.java:75) at org.eclipse.jdt.internal.ui.text.java.JavaCodeScanner.<init>(JavaCodeScanner.java:126) at org.eclipse.jdt.ui.text.JavaTextTools.<init>(JavaTextTools.java:80) at org.eclipse.jdt.internal.ui.preferences.JavaEditorPreferencePage.createPreviewer(JavaEditorPreferencePage.java:486) at org.eclipse.jdt.internal.ui.preferences.JavaEditorPreferencePage.createSyntaxPage(JavaEditorPreferencePage.java:433) at org.eclipse.jdt.internal.ui.preferences.JavaEditorPreferencePage.createContents(JavaEditorPreferencePage.java:942) at org.eclipse.jface.preference.PreferencePage.createControl(PreferencePage.java:209)
|
resolved fixed
|
64feff4
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-27T17:20:04Z | 2002-12-16T17:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/JavaColorManager.java
|
package org.eclipse.jdt.internal.ui.text;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Display;
import org.eclipse.jdt.ui.text.IColorManager;
import org.eclipse.jdt.ui.text.IColorManagerExtension;
/**
* Java color manager.
*/
public class JavaColorManager implements IColorManager, IColorManagerExtension {
protected Map fKeyTable= new HashMap(10);
protected Map fDisplayTable= new HashMap(2);
public JavaColorManager() {
}
private void dispose(Display display) {
Map colorTable= (Map) fDisplayTable.get(display);
if (colorTable != null) {
Iterator e= colorTable.values().iterator();
while (e.hasNext())
((Color) e.next()).dispose();
}
}
/*
* @see IColorManager#getColor(RGB)
*/
public Color getColor(RGB rgb) {
if (rgb == null)
return null;
final Display display= Display.getCurrent();
Map colorTable= (Map) fDisplayTable.get(display);
if (colorTable == null) {
colorTable= new HashMap(10);
fDisplayTable.put(display, colorTable);
display.disposeExec(new Runnable() {
public void run() {
dispose(display);
}
});
}
Color color= (Color) colorTable.get(rgb);
if (color == null) {
color= new Color(Display.getCurrent(), rgb);
colorTable.put(rgb, color);
}
return color;
}
/*
* @see IColorManager#dispose
*/
public void dispose() {
// nothing to dispose
}
/*
* @see IColorManager#getColor(String)
*/
public Color getColor(String key) {
if (key == null)
return null;
RGB rgb= (RGB) fKeyTable.get(key);
return getColor(rgb);
}
/*
* @see IColorManagerExtension#bindColor(String, RGB)
*/
public void bindColor(String key, RGB rgb) {
Object value= fKeyTable.get(key);
if (value != null)
throw new UnsupportedOperationException();
fKeyTable.put(key, rgb);
}
/*
* @see IColorManagerExtension#unbindColor(String)
*/
public void unbindColor(String key) {
fKeyTable.remove(key);
}
}
|
28,400 |
Bug 28400 JavaEditorPreferencePage and JavaColorManager leak Colors
|
20021216 everytime you do this: 1. open java editor pref page 2. close the pref page you end up having allocated and not disposed 8 colors 1 is allocated like this at org.eclipse.jdt.internal.ui.preferences.JavaEditorPreferencePage.createColor(JavaEditorPreferencePage.java:560) at org.eclipse.jdt.internal.ui.preferences.JavaEditorPreferencePage.initializeViewerColors(JavaEditorPreferencePage.java:534) at org.eclipse.jdt.internal.ui.preferences.JavaEditorPreferencePage.createPreviewer(JavaEditorPreferencePage.java:493) at org.eclipse.jdt.internal.ui.preferences.JavaEditorPreferencePage.createSyntaxPage(JavaEditorPreferencePage.java:433) at org.eclipse.jdt.internal.ui.preferences.JavaEditorPreferencePage.createContents(JavaEditorPreferencePage.java:942) at org.eclipse.jface.preference.PreferencePage.createControl(PreferencePage.java:209) and the other 7 are allocated like this: at org.eclipse.jdt.internal.ui.text.JavaColorManager.getColor(JavaColorManager.java:62) at org.eclipse.jdt.internal.ui.text.JavaColorManager.getColor(JavaColorManager.java:85) at org.eclipse.jdt.internal.ui.text.AbstractJavaScanner.addToken(AbstractJavaScanner.java:90) at org.eclipse.jdt.internal.ui.text.AbstractJavaScanner.initialize(AbstractJavaScanner.java:75) at org.eclipse.jdt.internal.ui.text.java.JavaCodeScanner.<init>(JavaCodeScanner.java:126) at org.eclipse.jdt.ui.text.JavaTextTools.<init>(JavaTextTools.java:80) at org.eclipse.jdt.internal.ui.preferences.JavaEditorPreferencePage.createPreviewer(JavaEditorPreferencePage.java:486) at org.eclipse.jdt.internal.ui.preferences.JavaEditorPreferencePage.createSyntaxPage(JavaEditorPreferencePage.java:433) at org.eclipse.jdt.internal.ui.preferences.JavaEditorPreferencePage.createContents(JavaEditorPreferencePage.java:942) at org.eclipse.jface.preference.PreferencePage.createControl(PreferencePage.java:209)
|
resolved fixed
|
64feff4
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-01-27T17:20:04Z | 2002-12-16T17:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/text/JavaTextTools.java
|
package org.eclipse.jdt.ui.text;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.IDocumentPartitioner;
import org.eclipse.jface.text.rules.DefaultPartitioner;
import org.eclipse.jface.text.rules.IPartitionTokenScanner;
//import org.eclipse.jface.text.rules.RuleBasedPartitionScanner;
//import org.eclipse.jface.text.rules.RuleBasedPartitioner;
import org.eclipse.jface.text.rules.RuleBasedScanner;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jdt.internal.ui.text.FastJavaPartitionScanner;
import org.eclipse.jdt.internal.ui.text.JavaColorManager;
import org.eclipse.jdt.internal.ui.text.JavaPartitionScanner;
import org.eclipse.jdt.internal.ui.text.SingleTokenJavaScanner;
import org.eclipse.jdt.internal.ui.text.java.JavaCodeScanner;
import org.eclipse.jdt.internal.ui.text.javadoc.JavaDocScanner;
/**
* Tools required to configure a Java text viewer.
* The color manager and all scanner exist only one time, i.e.
* the same instances are returned to all clients. Thus, clients
* share those tools.
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*/
public class JavaTextTools {
private class PreferenceListener implements IPropertyChangeListener {
public void propertyChange(PropertyChangeEvent event) {
adaptToPreferenceChange(event);
}
};
/** The color manager */
private JavaColorManager fColorManager;
/** The Java source code scanner */
private JavaCodeScanner fCodeScanner;
/** The Java multiline comment scanner */
private SingleTokenJavaScanner fMultilineCommentScanner;
/** The Java singleline comment scanner */
private SingleTokenJavaScanner fSinglelineCommentScanner;
/** The Java string scanner */
private SingleTokenJavaScanner fStringScanner;
/** The JavaDoc scanner */
private JavaDocScanner fJavaDocScanner;
/** The Java partitions scanner */
private FastJavaPartitionScanner fPartitionScanner;
/** The preference store */
private IPreferenceStore fPreferenceStore;
/** The preference change listener */
private PreferenceListener fPreferenceListener= new PreferenceListener();
/**
* Creates a new Java text tools collection.
*
* @param store the preference store to initialize the text tools. The text tool
* instance installs a listener on the passed preference store to adapt itself to
* changes in the preference store. In general <code>PreferenceConstants.
* getPreferenceStore()</code> shoould be used to initialize the text tools.
*
* @see org.eclipse.jdt.ui.PreferenceConstants#getPreferenceStore()
* @since 2.0
*/
public JavaTextTools(IPreferenceStore store) {
fPreferenceStore= store;
fPreferenceStore.addPropertyChangeListener(fPreferenceListener);
fColorManager= new JavaColorManager();
fCodeScanner= new JavaCodeScanner(fColorManager, store);
fMultilineCommentScanner= new SingleTokenJavaScanner(fColorManager, store, IJavaColorConstants.JAVA_MULTI_LINE_COMMENT);
fSinglelineCommentScanner= new SingleTokenJavaScanner(fColorManager, store, IJavaColorConstants.JAVA_SINGLE_LINE_COMMENT);
fStringScanner= new SingleTokenJavaScanner(fColorManager, store, IJavaColorConstants.JAVA_STRING);
fJavaDocScanner= new JavaDocScanner(fColorManager, store);
fPartitionScanner= new FastJavaPartitionScanner();
}
/**
* Disposes all the individual tools of this tools collection.
*/
public void dispose() {
fCodeScanner= null;
fMultilineCommentScanner= null;
fSinglelineCommentScanner= null;
fStringScanner= null;
fJavaDocScanner= null;
fPartitionScanner= null;
if (fColorManager != null) {
fColorManager.dispose();
fColorManager= null;
}
if (fPreferenceStore != null) {
fPreferenceStore.removePropertyChangeListener(fPreferenceListener);
fPreferenceStore= null;
fPreferenceListener= null;
}
}
/**
* Returns the color manager which is used to manage
* any Java-specific colors needed for such things like syntax highlighting.
*
* @return the color manager to be used for Java text viewers
*/
public IColorManager getColorManager() {
return fColorManager;
}
/**
* Returns a scanner which is configured to scan Java source code.
*
* @return a Java source code scanner
*/
public RuleBasedScanner getCodeScanner() {
return fCodeScanner;
}
/**
* Returns a scanner which is configured to scan Java multiline comments.
*
* @return a Java multiline comment scanner
*
* @since 2.0
*/
public RuleBasedScanner getMultilineCommentScanner() {
return fMultilineCommentScanner;
}
/**
* Returns a scanner which is configured to scan Java singleline comments.
*
* @return a Java singleline comment scanner
*
* @since 2.0
*/
public RuleBasedScanner getSinglelineCommentScanner() {
return fSinglelineCommentScanner;
}
/**
* Returns a scanner which is configured to scan Java strings.
*
* @return a Java string scanner
*
* @since 2.0
*/
public RuleBasedScanner getStringScanner() {
return fStringScanner;
}
/**
* Returns a scanner which is configured to scan JavaDoc compliant comments.
* Notes that the start sequence "/**" and the corresponding end sequence
* are part of the JavaDoc comment.
*
* @return a JavaDoc scanner
*/
public RuleBasedScanner getJavaDocScanner() {
return fJavaDocScanner;
}
/**
* Returns a scanner which is configured to scan
* Java-specific partitions, which are multi-line comments,
* JavaDoc comments, and regular Java source code.
*
* @return a Java partition scanner
*/
public IPartitionTokenScanner getPartitionScanner() {
return fPartitionScanner;
}
/**
* Factory method for creating a Java-specific document partitioner
* using this object's partitions scanner. This method is a
* convenience method.
*
* @return a newly created Java document partitioner
*/
public IDocumentPartitioner createDocumentPartitioner() {
String[] types= new String[] {
JavaPartitionScanner.JAVA_DOC,
JavaPartitionScanner.JAVA_MULTI_LINE_COMMENT,
JavaPartitionScanner.JAVA_SINGLE_LINE_COMMENT,
JavaPartitionScanner.JAVA_STRING
};
return new DefaultPartitioner(getPartitionScanner(), types);
}
/**
* Returns the names of the document position categories used by the document
* partitioners created by this object to manage their partition information.
* If the partitioners don't use document position categories, the returned
* result is <code>null</code>.
*
* @return the partition managing position categories or <code>null</code>
* if there is none
*/
public String[] getPartitionManagingPositionCategories() {
return new String[] { DefaultPartitioner.CONTENT_TYPES_CATEGORY };
}
/**
* Determines whether the preference change encoded by the given event
* changes the behavior of one its contained components.
*
* @param event the event to be investigated
* @return <code>true</code> if event causes a behavioral change
*
* @since 2.0
*/
public boolean affectsBehavior(PropertyChangeEvent event) {
return fCodeScanner.affectsBehavior(event) ||
fMultilineCommentScanner.affectsBehavior(event) ||
fSinglelineCommentScanner.affectsBehavior(event) ||
fStringScanner.affectsBehavior(event) ||
fJavaDocScanner.affectsBehavior(event);
}
/**
* Adapts the behavior of the contained components to the change
* encoded in the given event.
*
* @param event the event to which to adapt
* @since 2.0
*/
protected void adaptToPreferenceChange(PropertyChangeEvent event) {
if (fCodeScanner.affectsBehavior(event))
fCodeScanner.adaptToPreferenceChange(event);
if (fMultilineCommentScanner.affectsBehavior(event))
fMultilineCommentScanner.adaptToPreferenceChange(event);
if (fSinglelineCommentScanner.affectsBehavior(event))
fSinglelineCommentScanner.adaptToPreferenceChange(event);
if (fStringScanner.affectsBehavior(event))
fStringScanner.adaptToPreferenceChange(event);
if (fJavaDocScanner.affectsBehavior(event))
fJavaDocScanner.adaptToPreferenceChange(event);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.