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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
14,429 |
Bug 14429 Smoke 20020423: replace from local history wrong indentation
|
- load TestCase.java - edit method runTest - save - replace method with latest from local histroy observe: the method is wrong indented IMO the culprit is a change DB did at MemberEdit.
|
resolved fixed
|
f7c1350
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-24T10:48:02Z | 2002-04-23T16:40:00Z |
extension/org/eclipse/jdt/internal/corext/util/CodeFormatterUtil.java
| |
14,429 |
Bug 14429 Smoke 20020423: replace from local history wrong indentation
|
- load TestCase.java - edit method runTest - save - replace method with latest from local histroy observe: the method is wrong indented IMO the culprit is a change DB did at MemberEdit.
|
resolved fixed
|
f7c1350
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-24T10:48:02Z | 2002-04-23T16:40:00Z |
org.eclipse.jdt.ui/core
| |
14,429 |
Bug 14429 Smoke 20020423: replace from local history wrong indentation
|
- load TestCase.java - edit method runTest - save - replace method with latest from local histroy observe: the method is wrong indented IMO the culprit is a change DB did at MemberEdit.
|
resolved fixed
|
f7c1350
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-24T10:48:02Z | 2002-04-23T16:40:00Z |
extension/org/eclipse/jdt/internal/corext/util/Strings.java
| |
14,429 |
Bug 14429 Smoke 20020423: replace from local history wrong indentation
|
- load TestCase.java - edit method runTest - save - replace method with latest from local histroy observe: the method is wrong indented IMO the culprit is a change DB did at MemberEdit.
|
resolved fixed
|
f7c1350
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-24T10:48:02Z | 2002-04-23T16:40:00Z |
org.eclipse.jdt.ui/core
| |
14,429 |
Bug 14429 Smoke 20020423: replace from local history wrong indentation
|
- load TestCase.java - edit method runTest - save - replace method with latest from local histroy observe: the method is wrong indented IMO the culprit is a change DB did at MemberEdit.
|
resolved fixed
|
f7c1350
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-24T10:48:02Z | 2002-04-23T16:40:00Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/ExtractMethodRefactoring.java
| |
11,902 |
Bug 11902 Delete key does nothing on default package
|
Select a default package Press Delete key ==> no user feedback
|
resolved fixed
|
2dcbab7
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-24T11:00:47Z | 2002-03-20T16:00:00Z |
org.eclipse.jdt.ui/core
| |
11,902 |
Bug 11902 Delete key does nothing on default package
|
Select a default package Press Delete key ==> no user feedback
|
resolved fixed
|
2dcbab7
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-24T11:00:47Z | 2002-03-20T16:00:00Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/reorg/DeleteRefactoring.java
| |
18,483 |
Bug 18483 IE6 causes conflict with SWT.APPLICATION_MODAL on Windows 98
|
Build 20020531 When IE 6 is installed on Windows 98 it replaces the task bar with one of its own (according to Dave Thomson). When this occurs the focus behaviour of shells with modality set to SWT.APPLICATION_MODAL changes. STEPS 1) Start Windows 98 on a machine with IE 5 or earlier 2) Select a file 3) Hit delete - a prompter comes up 4) Select an non Eclipse window and drag it over the dialog 5) Select the Eclipse parent window in the tasks list - the dialog and window are given focus 6) Start Windows 98 on a machine with IE 62) Select a file 3) Hit delete - a prompter comes up 4) Select an non Eclipse window and drag it over the dialog 5) Select the Eclipse parent window in the tasks list - the dialog only is given focus and the window stays in the backgroud. I don't have a good pure SWT example of this yet as I am still trying to find the condition that makes this happen.
|
resolved fixed
|
208c64c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-24T16:05:56Z | 2002-05-31T18: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.RuleBasedPartitionScanner;
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.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 JavaPartitionScanner fPartitionScanner;
/** The preference store */
private IPreferenceStore fPreferenceStore;
/** The preference change listener */
private PreferenceListener fPreferenceListener= new PreferenceListener();
/**
* Creates a new Java text tools collection.
*/
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 JavaPartitionScanner();
}
/**
* 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
*/
public RuleBasedScanner getMultilineCommentScanner() {
return fMultilineCommentScanner;
}
/**
* Returns a scanner which is configured to scan Java singleline comments.
*
* @return a Java singleline comment scanner
*/
public RuleBasedScanner getSinglelineCommentScanner() {
return fSinglelineCommentScanner;
}
/**
* Returns a scanner which is configured to scan Java strings.
*
* @return a Java string scanner
*/
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 RuleBasedPartitionScanner 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
*/
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 whch to adapt
*/
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);
}
}
|
14,135 |
Bug 14135 Renaming a CU->have to enter .java
|
The refactoring knows that I'm renaming .java. If the user doesn't enter then it should be added automatically. Rename CU should behave the same as Create Class.
|
resolved fixed
|
eafbaa3
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-24T16:34:52Z | 2002-04-18T17:13:20Z |
org.eclipse.jdt.ui/core
| |
14,135 |
Bug 14135 Renaming a CU->have to enter .java
|
The refactoring knows that I'm renaming .java. If the user doesn't enter then it should be added automatically. Rename CU should behave the same as Create Class.
|
resolved fixed
|
eafbaa3
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-24T16:34:52Z | 2002-04-18T17:13:20Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/rename/RenameCompilationUnitRefactoring.java
| |
12,428 |
Bug 12428 Pull Up: Confusing message
|
Run Pull up on TestCase.setUp (copies the method to Assert) Go to 2nd page of wizard. In tree of changes, under Assert, we get the message "copy method 'void setUp()' to type 'TestCase'". Shouldn't it be 'Copy method 'void setUp()' FROM type 'TestCase'" (also with upper-case C in Copy). Another thing: if I select to delete setUp from TestCase, I get under TestCase the message "Delete method 'void setUp()' declared in type 'junit.framework.TestCase'". Here TestCase is shown with the fully qualified name. Shouldn't then the 'copy method' text be consistent and also use the fully qualified name? (Markus)
|
resolved fixed
|
51fcda2
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-25T12:36:24Z | 2002-03-28T15:40:00Z |
org.eclipse.jdt.ui/core
| |
12,428 |
Bug 12428 Pull Up: Confusing message
|
Run Pull up on TestCase.setUp (copies the method to Assert) Go to 2nd page of wizard. In tree of changes, under Assert, we get the message "copy method 'void setUp()' to type 'TestCase'". Shouldn't it be 'Copy method 'void setUp()' FROM type 'TestCase'" (also with upper-case C in Copy). Another thing: if I select to delete setUp from TestCase, I get under TestCase the message "Delete method 'void setUp()' declared in type 'junit.framework.TestCase'". Here TestCase is shown with the fully qualified name. Shouldn't then the 'copy method' text be consistent and also use the fully qualified name? (Markus)
|
resolved fixed
|
51fcda2
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-25T12:36:24Z | 2002-03-28T15:40:00Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/PullUpRefactoring.java
| |
9,619 |
Bug 9619 Move static member: Dialog details
|
20020212 a. Mnemonics b. Browse button is too small (use SWTUtil for standard button sizes) c. Title is used for long text. I would use the title for 'Move static field (s)' and use the description for 'x fields from xx' d. Browse offers my a type from a CU in a different project. When going to the next page, it says 'Type not found' Only types from the source folders of the own project should be shown in the dialog. e. No validation on the type field. Type existance is not too expensive (done in the type wizard for super class), so could be done. At least isValidTypeName f. label could say 'Select destination type:' g. Selection dialog should be initialized with the type currently entered. h. destination type can be source type: refactoring warns that this will result in errors (which is not true) and makes pseudo-changes in all referencing classes.
|
resolved fixed
|
007c12d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-25T16:34:23Z | 2002-02-13T14:20:00Z |
org.eclipse.jdt.ui/ui
| |
9,619 |
Bug 9619 Move static member: Dialog details
|
20020212 a. Mnemonics b. Browse button is too small (use SWTUtil for standard button sizes) c. Title is used for long text. I would use the title for 'Move static field (s)' and use the description for 'x fields from xx' d. Browse offers my a type from a CU in a different project. When going to the next page, it says 'Type not found' Only types from the source folders of the own project should be shown in the dialog. e. No validation on the type field. Type existance is not too expensive (done in the type wizard for super class), so could be done. At least isValidTypeName f. label could say 'Select destination type:' g. Selection dialog should be initialized with the type currently entered. h. destination type can be source type: refactoring warns that this will result in errors (which is not true) and makes pseudo-changes in all referencing classes.
|
resolved fixed
|
007c12d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-25T16:34:23Z | 2002-02-13T14:20:00Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/MoveMembersInputPage.java
| |
14,368 |
Bug 14368 Create getter and setter insert code into read-only file
|
1. Create a class C as follow: package jp1; public class C { private int id; } 2. Close it and mark it as read only 3. Reopen it and you should not be able to modify anything 4. From the outline view, select "id - int" and right mouse click and select "Create getter and setter". 5. The class becomes package jp1; public class C { private int id; /** * Gets the id. * @return Returns a int */ public int getId() { return id; } /** * Sets the id. * @param id The id to set */ public void setId(int id) { this.id = id; } } and the editor is dirty, but you cannot save it until clear the read-only flag.
|
resolved fixed
|
e6ed913
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-26T12:41:25Z | 2002-04-22T21:13:20Z |
org.eclipse.jdt.ui/core
| |
14,368 |
Bug 14368 Create getter and setter insert code into read-only file
|
1. Create a class C as follow: package jp1; public class C { private int id; } 2. Close it and mark it as read only 3. Reopen it and you should not be able to modify anything 4. From the outline view, select "id - int" and right mouse click and select "Create getter and setter". 5. The class becomes package jp1; public class C { private int id; /** * Gets the id. * @return Returns a int */ public int getId() { return id; } /** * Sets the id. * @param id The id to set */ public void setId(int id) { this.id = id; } } and the editor is dirty, but you cannot save it until clear the read-only flag.
|
resolved fixed
|
e6ed913
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-26T12:41:25Z | 2002-04-22T21:13:20Z |
extension/org/eclipse/jdt/internal/corext/util/JavaModelUtil.java
| |
14,368 |
Bug 14368 Create getter and setter insert code into read-only file
|
1. Create a class C as follow: package jp1; public class C { private int id; } 2. Close it and mark it as read only 3. Reopen it and you should not be able to modify anything 4. From the outline view, select "id - int" and right mouse click and select "Create getter and setter". 5. The class becomes package jp1; public class C { private int id; /** * Gets the id. * @return Returns a int */ public int getId() { return id; } /** * Sets the id. * @param id The id to set */ public void setId(int id) { this.id = id; } } and the editor is dirty, but you cannot save it until clear the read-only flag.
|
resolved fixed
|
e6ed913
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-26T12:41:25Z | 2002-04-22T21:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/actions/AddGetterSetterAction.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.actions;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMethod;
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.JavaUIMessages;
import org.eclipse.jdt.internal.corext.codemanipulation.AddGetterSetterOperation;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.codemanipulation.IRequestQuery;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.preferences.CodeGenerationPreferencePage;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
/**
* Create Getter and Setter for selected fields.
* Will open the parent compilation unit in the editor.
* The result is unsaved, so the user can decide if the
* changes are acceptable.
*
* @deprecated Use action from package org.eclipse.jdt.ui.actions
*/
public class AddGetterSetterAction extends Action {
private ISelectionProvider fSelectionProvider;
public AddGetterSetterAction(ISelectionProvider selProvider) {
super(JavaUIMessages.getString("AddGetterSetterAction.label")); //$NON-NLS-1$
setDescription(JavaUIMessages.getString("AddGetterSetterAction.description")); //$NON-NLS-1$
setToolTipText(JavaUIMessages.getString("AddGetterSetterAction.tooltip")); //$NON-NLS-1$
fSelectionProvider= selProvider;
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.GETTERSETTER_ACTION);
}
public void run() {
IField[] fields= getSelectedFields();
if (fields == null) {
return;
}
try {
ICompilationUnit cu= fields[0].getCompilationUnit();
// open the editor, forces the creation of a working copy
IEditorPart editor= EditorUtility.openInEditor(cu);
ICompilationUnit workingCopyCU;
IField[] workingCopyFields;
if (cu.isWorkingCopy()) {
workingCopyCU= cu;
workingCopyFields= fields;
} else {
workingCopyCU= EditorUtility.getWorkingCopy(cu);
if (workingCopyCU == null) {
showError(JavaUIMessages.getString("AddGetterSetterAction.error.actionfailed")); //$NON-NLS-1$
return;
}
workingCopyFields= new IField[fields.length];
for (int i= 0; i < fields.length; i++) {
IField field= fields[i];
IField workingCopyField= (IField) JavaModelUtil.findMemberInCompilationUnit(workingCopyCU, field);
if (workingCopyField == null) {
showError(JavaUIMessages.getFormattedString("AddGetterSetterAction.error.fieldNotExisting", field.getElementName())); //$NON-NLS-1$
return;
}
workingCopyFields[i]= workingCopyField;
}
}
IRequestQuery skipSetterForFinalQuery= skipSetterForFinalQuery();
IRequestQuery skipReplaceQuery= skipReplaceQuery();
String[] prefixes= CodeGenerationPreferencePage.getGetterStetterPrefixes();
String[] suffixes= CodeGenerationPreferencePage.getGetterStetterSuffixes();
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
AddGetterSetterOperation op= new AddGetterSetterOperation(workingCopyFields, prefixes, suffixes, settings, skipSetterForFinalQuery, skipReplaceQuery);
ProgressMonitorDialog dialog= new ProgressMonitorDialog(JavaPlugin.getActiveWorkbenchShell());
dialog.run(false, true, new WorkbenchRunnableAdapter(op));
IMethod[] createdMethods= op.getCreatedAccessors();
if (createdMethods.length > 0) {
EditorUtility.revealInEditor(editor, createdMethods[0]);
}
} catch (InvocationTargetException e) {
JavaPlugin.log(e);
showError(JavaUIMessages.getString("AddGetterSetterAction.error.actionfailed")); //$NON-NLS-1$
} catch (CoreException e) {
JavaPlugin.log(e.getStatus());
showError(JavaUIMessages.getString("AddGetterSetterAction.error.actionfailed")); //$NON-NLS-1$
return;
} catch (InterruptedException e) {
// operation cancelled
}
}
private IRequestQuery skipSetterForFinalQuery() {
return new IRequestQuery() {
public int doQuery(IMember field) {
int[] returnCodes= {IRequestQuery.YES, IRequestQuery.NO, IRequestQuery.YES_ALL, IRequestQuery.CANCEL};
String[] options= {IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.YES_TO_ALL_LABEL, IDialogConstants.CANCEL_LABEL};
String fieldName= JavaElementLabels.getElementLabel(field, 0);
String formattedMessage= JavaUIMessages.getFormattedString("AddGetterSetterAction.SkipSetterForFinalDialog.message", fieldName); //$NON-NLS-1$
return showQueryDialog(formattedMessage, options, returnCodes);
}
};
}
private IRequestQuery skipReplaceQuery() {
return new IRequestQuery() {
public int doQuery(IMember method) {
int[] returnCodes= {IRequestQuery.YES, IRequestQuery.NO, IRequestQuery.YES_ALL, IRequestQuery.CANCEL};
String skipLabel= JavaUIMessages.getString("AddGetterSetterAction.SkipExistingDialog.skip.label"); //$NON-NLS-1$
String replaceLabel= JavaUIMessages.getString("AddGetterSetterAction.SkipExistingDialog.replace.label"); //$NON-NLS-1$
String skipAllLabel= JavaUIMessages.getString("AddGetterSetterAction.SkipExistingDialog.skipAll.label"); //$NON-NLS-1$
String[] options= { skipLabel, replaceLabel, skipAllLabel, IDialogConstants.CANCEL_LABEL};
String methodName= JavaElementLabels.getElementLabel(method, JavaElementLabels.M_PARAMETER_TYPES);
String formattedMessage= JavaUIMessages.getFormattedString("AddGetterSetterAction.SkipExistingDialog.message", methodName); //$NON-NLS-1$
return showQueryDialog(formattedMessage, options, returnCodes);
}
};
}
private int showQueryDialog(final String message, final String[] buttonLabels, int[] returnCodes) {
final Shell shell= JavaPlugin.getActiveWorkbenchShell();
if (shell == null) {
JavaPlugin.logErrorMessage("AddGetterSetterAction.showQueryDialog: No active shell found"); //$NON-NLS-1$
return IRequestQuery.CANCEL;
}
final int[] result= { MessageDialog.CANCEL };
shell.getDisplay().syncExec(new Runnable() {
public void run() {
String title= JavaUIMessages.getString("AddGetterSetterAction.QueryDialog.title"); //$NON-NLS-1$
MessageDialog dialog= new MessageDialog(shell, title, null, message, MessageDialog.QUESTION, buttonLabels, 0);
result[0]= dialog.open();
}
});
int returnVal= result[0];
return returnVal < 0 ? IRequestQuery.CANCEL : returnCodes[returnVal];
}
private void showError(String message) {
Shell shell= JavaPlugin.getActiveWorkbenchShell();
String title= JavaUIMessages.getString("AddGetterSetterAction.error.title"); //$NON-NLS-1$
MessageDialog.openError(shell, title, message);
}
/*
* Returns fields in the selection or <code>null</code> if the selection is
* empty or not valid.
*/
private IField[] getSelectedFields() {
ISelection sel= fSelectionProvider.getSelection();
if (sel instanceof IStructuredSelection) {
List elements= ((IStructuredSelection)sel).toList();
int nElements= elements.size();
if (nElements > 0) {
IField[] res= new IField[nElements];
ICompilationUnit cu= null;
for (int i= 0; i < nElements; i++) {
Object curr= elements.get(i);
if (curr instanceof IField) {
IField fld= (IField)curr;
if (i == 0) {
// remember the cu of the first element
cu= fld.getCompilationUnit();
if (cu == null) {
return null;
}
} else if (!cu.equals(fld.getCompilationUnit())) {
// all fields must be in the same CU
return null;
}
try {
if (fld.getDeclaringType().isInterface()) {
// no setters/getters for interfaces
return null;
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
return null;
}
res[i]= fld;
} else {
return null;
}
}
return res;
}
}
return null;
}
/**
* Tests if the acion can be run using the current selection.
*/
public boolean canActionBeAdded() {
return getSelectedFields() != null;
}
}
|
14,368 |
Bug 14368 Create getter and setter insert code into read-only file
|
1. Create a class C as follow: package jp1; public class C { private int id; } 2. Close it and mark it as read only 3. Reopen it and you should not be able to modify anything 4. From the outline view, select "id - int" and right mouse click and select "Create getter and setter". 5. The class becomes package jp1; public class C { private int id; /** * Gets the id. * @return Returns a int */ public int getId() { return id; } /** * Sets the id. * @param id The id to set */ public void setId(int id) { this.id = id; } } and the editor is dirty, but you cannot save it until clear the read-only flag.
|
resolved fixed
|
e6ed913
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-26T12:41:25Z | 2002-04-22T21:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/actions/AddJavaDocStubAction.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.actions;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
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.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IEditorPart;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.internal.corext.codemanipulation.AddJavaDocStubOperation;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaUIMessages;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
/**
* Create Java Doc Stubs for selected members
* Always forces the he field to be in an open editor. The result is unsaved,
* so the user can decide if he wnats to accept the changes
*
* @deprecated Use action from package org.eclipse.jdt.ui.actions
*/
public class AddJavaDocStubAction extends Action {
private ISelectionProvider fSelectionProvider;
public AddJavaDocStubAction(ISelectionProvider selProvider) {
super(JavaUIMessages.getString("AddJavaDocStubAction.label")); //$NON-NLS-1$
setDescription(JavaUIMessages.getString("AddJavaDocStubAction.description")); //$NON-NLS-1$
setToolTipText(JavaUIMessages.getString("AddJavaDocStubAction.tooltip")); //$NON-NLS-1$
fSelectionProvider= selProvider;
}
public void run() {
IMember[] members= getSelectedMembers();
if (members == null || members.length == 0) {
return;
}
try {
ICompilationUnit cu= members[0].getCompilationUnit();
// open the editor, forces the creation of a working copy
IEditorPart editor= EditorUtility.openInEditor(cu);
ICompilationUnit workingCopyCU;
IMember[] workingCopyMembers;
if (cu.isWorkingCopy()) {
workingCopyCU= cu;
workingCopyMembers= members;
} else {
// get the corresponding elements from the working copy
workingCopyCU= EditorUtility.getWorkingCopy(cu);
if (workingCopyCU == null) {
showError(JavaUIMessages.getString("AddJavaDocStubsAction.error.noWorkingCopy")); //$NON-NLS-1$
return;
}
workingCopyMembers= new IMember[members.length];
for (int i= 0; i < members.length; i++) {
IMember member= members[i];
IMember workingCopyMember= (IMember) JavaModelUtil.findMemberInCompilationUnit(workingCopyCU, member);
if (workingCopyMember == null) {
showError(JavaUIMessages.getFormattedString("AddJavaDocStubsAction.error.memberNotExisting", member.getElementName())); //$NON-NLS-1$
return;
}
workingCopyMembers[i]= workingCopyMember;
}
}
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
AddJavaDocStubOperation op= new AddJavaDocStubOperation(workingCopyMembers, settings);
ProgressMonitorDialog dialog= new ProgressMonitorDialog(JavaPlugin.getActiveWorkbenchShell());
dialog.run(false, true, new WorkbenchRunnableAdapter(op));
EditorUtility.revealInEditor(editor, members[0]);
} catch (InvocationTargetException e) {
JavaPlugin.log(e);
showError(JavaUIMessages.getString("AddJavaDocStubsAction.error.actionFailed")); //$NON-NLS-1$
} catch (InterruptedException e) {
// operation cancelled
} catch (CoreException e) {
JavaPlugin.log(e.getStatus());
showError(JavaUIMessages.getString("AddJavaDocStubsAction.error.actionFailed")); //$NON-NLS-1$
return;
}
}
private void showError(String message) {
Shell shell= JavaPlugin.getActiveWorkbenchShell();
String title= JavaUIMessages.getString("AddJavaDocStubsAction.error.dialogTitle"); //$NON-NLS-1$
MessageDialog.openError(shell, title, message);
}
private IMember[] getSelectedMembers() {
ISelection sel= fSelectionProvider.getSelection();
if (sel instanceof IStructuredSelection) {
List elements= ((IStructuredSelection)sel).toList();
int nElements= elements.size();
if (nElements > 0) {
IMember[] res= new IMember[nElements];
ICompilationUnit cu= null;
for (int i= 0; i < nElements; i++) {
Object curr= elements.get(i);
if (curr instanceof IMethod || curr instanceof IType) {
IMember member= (IMember)curr; // limit to methods & types
if (i == 0) {
cu= member.getCompilationUnit();
if (cu == null) {
return null;
}
} else if (!cu.equals(member.getCompilationUnit())) {
return null;
}
res[i]= member;
} else {
return null;
}
}
return res;
}
}
return null;
}
public boolean canActionBeAdded() {
return getSelectedMembers() != null;
}
}
|
14,368 |
Bug 14368 Create getter and setter insert code into read-only file
|
1. Create a class C as follow: package jp1; public class C { private int id; } 2. Close it and mark it as read only 3. Reopen it and you should not be able to modify anything 4. From the outline view, select "id - int" and right mouse click and select "Create getter and setter". 5. The class becomes package jp1; public class C { private int id; /** * Gets the id. * @return Returns a int */ public int getId() { return id; } /** * Sets the id. * @param id The id to set */ public void setId(int id) { this.id = id; } } and the editor is dirty, but you cannot save it until clear the read-only flag.
|
resolved fixed
|
e6ed913
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-26T12:41:25Z | 2002-04-22T21:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/actions/AddMethodStubAction.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.actions;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaUIMessages;
import org.eclipse.jdt.internal.corext.codemanipulation.AddMethodStubOperation;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.codemanipulation.IRequestQuery;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
/**
* Creates method stubs in a type.
* The type has to be set before usage (init)
* Always forces the type to open in an editor. The result is unsaved,
* so the user can decide if the changes are acceptable.
*/
public class AddMethodStubAction extends Action {
private ISelection fSelection;
private IType fParentType;
public AddMethodStubAction() {
super(JavaUIMessages.getString("AddMethodStubAction.label")); //$NON-NLS-1$
setDescription(JavaUIMessages.getString("AddMethodStubAction.description")); //$NON-NLS-1$
setToolTipText(JavaUIMessages.getString("AddMethodStubAction.tooltip")); //$NON-NLS-1$
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.ADD_METHODSTUB_ACTION);
}
public boolean init(IType parentType, ISelection selection) {
if (canActionBeAdded(parentType, selection)) {
fParentType= parentType;
fSelection= selection;
if (parentType != null) {
try {
if (parentType.isInterface()) {
setText(JavaUIMessages.getFormattedString("AddMethodStubAction.detailed.implement", parentType.getElementName())); //$NON-NLS-1$
} else {
setText(JavaUIMessages.getFormattedString("AddMethodStubAction.detailed.override", parentType.getElementName())); //$NON-NLS-1$
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
} else {
setText(JavaUIMessages.getString("AddMethodStubAction.label")); //$NON-NLS-1$
}
return true;
}
fParentType= null;
fSelection= null;
return false;
}
public void run() {
if (!canActionBeAdded(fParentType, fSelection)) {
return;
}
Shell shell= JavaPlugin.getActiveWorkbenchShell();
try {
// open an editor and work on a working copy
IEditorPart editor= EditorUtility.openInEditor(fParentType);
IType usedType= (IType)EditorUtility.getWorkingCopy(fParentType);
if (usedType == null) {
MessageDialog.openError(shell, JavaUIMessages.getString("AddMethodStubAction.error.title"), JavaUIMessages.getString("AddMethodStubAction.error.type_removed_in_editor")); //$NON-NLS-2$ //$NON-NLS-1$
return;
}
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
List list= ((IStructuredSelection)fSelection).toList();
IMethod[] methods= (IMethod[]) list.toArray(new IMethod[list.size()]);
AddMethodStubOperation op= new AddMethodStubOperation(usedType, methods, settings, createOverrideQuery(), createReplaceQuery(), false);
ProgressMonitorDialog dialog= new ProgressMonitorDialog(shell);
dialog.run(false, true, new WorkbenchRunnableAdapter(op));
IMethod[] res= op.getCreatedMethods();
if (res != null && res.length > 0 && editor != null) {
EditorUtility.revealInEditor(editor, res[0]);
}
} catch (InvocationTargetException e) {
MessageDialog.openError(shell, JavaUIMessages.getString("AddMethodStubAction.error.title"), e.getTargetException().getMessage()); //$NON-NLS-1$
JavaPlugin.log(e.getTargetException());
} catch (CoreException e) {
ErrorDialog.openError(shell, JavaUIMessages.getString("AddMethodStubAction.error.title"), null, e.getStatus()); //$NON-NLS-1$
JavaPlugin.log(e.getStatus());
} catch (InterruptedException e) {
// Do nothing. Operation has been canceled by user.
}
}
private IRequestQuery createOverrideQuery() {
return new IRequestQuery() {
public int doQuery(IMember method) {
String methodName= JavaElementLabels.getElementLabel(method, JavaElementLabels.M_PARAMETER_TYPES);
String declTypeName= JavaElementLabels.getElementLabel(method.getDeclaringType(), 0);
String formattedMessage;
try {
if (Flags.isFinal(method.getFlags())) {
formattedMessage= JavaUIMessages.getFormattedString("AddMethodStubAction.OverridesFinalDialog.message", new String[] { methodName, declTypeName }); //$NON-NLS-1$
} else {
formattedMessage= JavaUIMessages.getFormattedString("AddMethodStubAction.OverridesPrivateDialog.message", new String[] { methodName, declTypeName }); //$NON-NLS-1$
}
} catch (JavaModelException e) {
JavaPlugin.log(e.getStatus());
return IRequestQuery.CANCEL;
}
return showQueryDialog(formattedMessage);
}
};
}
private IRequestQuery createReplaceQuery() {
return new IRequestQuery() {
public int doQuery(IMember method) {
String methodName= JavaElementLabels.getElementLabel(method, JavaElementLabels.M_PARAMETER_TYPES);
String formattedMessage= JavaUIMessages.getFormattedString("AddMethodStubAction.ReplaceExistingDialog.message", methodName); //$NON-NLS-1$
return showQueryDialog(formattedMessage);
}
};
}
private int showQueryDialog(final String message) {
int[] returnCodes= {IRequestQuery.YES, IRequestQuery.NO, IRequestQuery.YES_ALL, IRequestQuery.CANCEL};
final Shell shell= JavaPlugin.getActiveWorkbenchShell();
if (shell == null) {
JavaPlugin.logErrorMessage("AddMethodStubAction.showQueryDialog: No active shell found"); //$NON-NLS-1$
return IRequestQuery.CANCEL;
}
final int[] result= { MessageDialog.CANCEL };
shell.getDisplay().syncExec(new Runnable() {
public void run() {
String title= JavaUIMessages.getString("AddMethodStubAction.QueryDialog.title"); //$NON-NLS-1$
String[] options= {IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.YES_TO_ALL_LABEL, IDialogConstants.CANCEL_LABEL};
MessageDialog dialog= new MessageDialog(shell, title, null, message, MessageDialog.QUESTION, options, 0);
result[0]= dialog.open();
}
});
int returnVal= result[0];
return returnVal < 0 ? IRequestQuery.CANCEL : returnCodes[returnVal];
}
/**
* Tests if the action can run with given arguments
*/
public static boolean canActionBeAdded(IType parentType, ISelection selection) {
if (parentType == null || parentType.getCompilationUnit() == null ||
!(selection instanceof IStructuredSelection) || selection.isEmpty()) {
return false;
}
Object[] elems= ((IStructuredSelection)selection).toArray();
int nSelected= elems.length;
if (nSelected > 0) {
for (int i= 0; i < nSelected; i++) {
Object elem= elems[i];
if (!(elem instanceof IMethod)) {
return false;
}
IMethod meth= (IMethod)elem;
if (meth.getDeclaringType().equals(parentType)) {
return false;
}
}
return true;
}
return false;
}
}
|
14,368 |
Bug 14368 Create getter and setter insert code into read-only file
|
1. Create a class C as follow: package jp1; public class C { private int id; } 2. Close it and mark it as read only 3. Reopen it and you should not be able to modify anything 4. From the outline view, select "id - int" and right mouse click and select "Create getter and setter". 5. The class becomes package jp1; public class C { private int id; /** * Gets the id. * @return Returns a int */ public int getId() { return id; } /** * Sets the id. * @param id The id to set */ public void setId(int id) { this.id = id; } } and the editor is dirty, but you cannot save it until clear the read-only flag.
|
resolved fixed
|
e6ed913
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-26T12:41:25Z | 2002-04-22T21:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/actions/AddUnimplementedConstructorsAction.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.actions;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.corext.codemanipulation.AddUnimplementedConstructorsOperation;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
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.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
/**
* Evaluates constructors needed.
* Will open an editor for the type. Changes are unsaved.
*
* @deprecated Use action from package org.eclipse.jdt.ui.actions
*/
public class AddUnimplementedConstructorsAction extends Action {
private ISelectionProvider fSelectionProvider;
public AddUnimplementedConstructorsAction(ISelectionProvider selProvider) {
super(JavaUIMessages.getString("AddUnimplementedConstructorsAction.label")); //$NON-NLS-1$
setDescription(JavaUIMessages.getString("AddUnimplementedConstructorsAction.description")); //$NON-NLS-1$
setToolTipText(JavaUIMessages.getString("AddUnimplementedConstructorsAction.tooltip")); //$NON-NLS-1$
fSelectionProvider= selProvider;
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.ADD_UNIMPLEMENTED_CONSTRUCTORS_ACTION);
}
public void run() {
Shell shell= JavaPlugin.getActiveWorkbenchShell();
try {
IType type= getSelectedType();
if (type == null) {
return;
}
// open an editor and work on a working copy
IEditorPart editor= EditorUtility.openInEditor(type);
type= (IType)EditorUtility.getWorkingCopy(type);
if (type == null) {
MessageDialog.openError(shell, JavaUIMessages.getString("AddUnimplementedConstructorsAction.error.title"), JavaUIMessages.getString("AddUnimplementedConstructorsAction.error.type_removed_in_editor")); //$NON-NLS-2$ //$NON-NLS-1$
return;
}
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
AddUnimplementedConstructorsOperation op= new AddUnimplementedConstructorsOperation(type, settings, false);
try {
ProgressMonitorDialog dialog= new ProgressMonitorDialog(shell);
dialog.run(false, true, new WorkbenchRunnableAdapter(op));
IMethod[] res= op.getCreatedMethods();
if (res == null || res.length == 0) {
MessageDialog.openInformation(shell, JavaUIMessages.getString("AddUnimplementedConstructorsAction.error.title"), JavaUIMessages.getString("AddUnimplementedConstructorsAction.error.nothing_found")); //$NON-NLS-2$ //$NON-NLS-1$
} else if (editor != null) {
EditorUtility.revealInEditor(editor, res[0]);
}
} catch (InvocationTargetException e) {
JavaPlugin.log(e);
MessageDialog.openError(shell, JavaUIMessages.getString("AddUnimplementedConstructorsAction.error.title"), e.getTargetException().getMessage()); //$NON-NLS-1$
} catch (InterruptedException e) {
// Do nothing. Operation has been canceled by user.
}
} catch (CoreException e) {
JavaPlugin.log(e);
ErrorDialog.openError(shell, JavaUIMessages.getString("AddUnimplementedConstructorsAction.error.title"), null, e.getStatus()); //$NON-NLS-1$
}
}
private IType getSelectedType() throws JavaModelException {
ISelection sel= fSelectionProvider.getSelection();
if (sel instanceof IStructuredSelection) {
Object[] elements= ((IStructuredSelection)sel).toArray();
if (elements.length == 1 && (elements[0] instanceof IType)) {
IType type= (IType) elements[0];
if (type.getCompilationUnit() != null && type.isClass()) {
return type;
}
}
}
return null;
}
public boolean canActionBeAdded() {
try {
return getSelectedType() != null;
} catch (JavaModelException e) {
JavaPlugin.log(e.getStatus());
}
return false;
}
}
|
14,368 |
Bug 14368 Create getter and setter insert code into read-only file
|
1. Create a class C as follow: package jp1; public class C { private int id; } 2. Close it and mark it as read only 3. Reopen it and you should not be able to modify anything 4. From the outline view, select "id - int" and right mouse click and select "Create getter and setter". 5. The class becomes package jp1; public class C { private int id; /** * Gets the id. * @return Returns a int */ public int getId() { return id; } /** * Sets the id. * @param id The id to set */ public void setId(int id) { this.id = id; } } and the editor is dirty, but you cannot save it until clear the read-only flag.
|
resolved fixed
|
e6ed913
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-26T12:41:25Z | 2002-04-22T21:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/actions/AddUnimplementedMethodsAction.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.actions;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.corext.codemanipulation.AddUnimplementedMethodsOperation;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
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.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext;
/**
* Evaluates unimplemented methods of a type.
* Will open an editor for the type. Changes are unsaved.
*
* @deprecated Use action org.eclipse.jdt.ui.actions.OverrideMethodsAction
*/
public class AddUnimplementedMethodsAction extends Action {
private ISelectionProvider fSelectionProvider;
public AddUnimplementedMethodsAction(ISelectionProvider selProvider) {
super(JavaUIMessages.getString("AddUnimplementedMethodsAction.label")); //$NON-NLS-1$
setDescription(JavaUIMessages.getString("AddUnimplementedMethodsAction.description")); //$NON-NLS-1$
setToolTipText(JavaUIMessages.getString("AddUnimplementedMethodsAction.tooltip")); //$NON-NLS-1$
fSelectionProvider= selProvider;
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.ADD_UNIMPLEMENTED_METHODS_ACTION);
}
public void run() {
Shell shell= JavaPlugin.getActiveWorkbenchShell();
try {
IType type= getSelectedType();
if (type == null) {
return;
}
// open an editor and work on a working copy
IEditorPart editor= EditorUtility.openInEditor(type);
type= (IType)EditorUtility.getWorkingCopy(type);
if (type == null) {
MessageDialog.openError(shell, JavaUIMessages.getString("AddUnimplementedMethodsAction.error.title"), JavaUIMessages.getString("AddUnimplementedMethodsAction.error.type_removed_in_editor")); //$NON-NLS-2$ //$NON-NLS-1$
return;
}
OverrideMethodQuery selectionQuery= new OverrideMethodQuery(shell, false);
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
AddUnimplementedMethodsOperation op= new AddUnimplementedMethodsOperation(type, settings, selectionQuery, false);
try {
BusyIndicatorRunnableContext context= new BusyIndicatorRunnableContext();
context.run(false, true, new WorkbenchRunnableAdapter(op));
IMethod[] res= op.getCreatedMethods();
if (res == null || res.length == 0) {
MessageDialog.openInformation(shell, JavaUIMessages.getString("AddUnimplementedMethodsAction.error.title"), JavaUIMessages.getString("AddUnimplementedMethodsAction.error.nothing_found")); //$NON-NLS-2$ //$NON-NLS-1$
} else if (editor != null) {
EditorUtility.revealInEditor(editor, res[0]);
}
} catch (InvocationTargetException e) {
JavaPlugin.log(e);
MessageDialog.openError(shell, JavaUIMessages.getString("AddUnimplementedMethodsAction.error.title"), e.getTargetException().getMessage()); //$NON-NLS-1$
} catch (InterruptedException e) {
// Do nothing. Operation has been canceled by user.
}
} catch (CoreException e) {
JavaPlugin.log(e);
ErrorDialog.openError(shell, JavaUIMessages.getString("AddUnimplementedMethodsAction.error.title"), null, e.getStatus()); //$NON-NLS-1$
}
}
private IType getSelectedType() throws JavaModelException {
ISelection sel= fSelectionProvider.getSelection();
if (sel instanceof IStructuredSelection) {
Object[] elements= ((IStructuredSelection)sel).toArray();
if (elements.length == 1 && (elements[0] instanceof IType)) {
IType type= (IType) elements[0];
if (type.getCompilationUnit() != null && type.isClass()) {
return type;
}
}
}
return null;
}
public boolean canActionBeAdded() {
try {
return getSelectedType() != null;
} catch (JavaModelException e) {
JavaPlugin.log(e.getStatus());
}
return false;
}
}
|
14,368 |
Bug 14368 Create getter and setter insert code into read-only file
|
1. Create a class C as follow: package jp1; public class C { private int id; } 2. Close it and mark it as read only 3. Reopen it and you should not be able to modify anything 4. From the outline view, select "id - int" and right mouse click and select "Create getter and setter". 5. The class becomes package jp1; public class C { private int id; /** * Gets the id. * @return Returns a int */ public int getId() { return id; } /** * Sets the id. * @param id The id to set */ public void setId(int id) { this.id = id; } } and the editor is dirty, but you cannot save it until clear the read-only flag.
|
resolved fixed
|
e6ed913
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-26T12:41:25Z | 2002-04-22T21:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/AddImportOnSelectionAction.java
|
package org.eclipse.jdt.internal.ui.javaeditor;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.dialogs.ElementListSelectionDialog;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.ui.texteditor.IUpdate;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.core.search.IJavaSearchConstants;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.ITypeNameRequestor;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.ui.IWorkingCopyManager;
import org.eclipse.jdt.internal.corext.codemanipulation.AddImportsOperation;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.util.TypeInfo;
import org.eclipse.jdt.internal.corext.util.TypeInfoRequestor;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.util.TypeInfoLabelProvider;
public class AddImportOnSelectionAction extends Action implements IUpdate {
private ITextEditor fEditor;
public AddImportOnSelectionAction(ITextEditor editor) {
super(JavaEditorMessages.getString("AddImportOnSelection.label")); //$NON-NLS-1$
setToolTipText(JavaEditorMessages.getString("AddImportOnSelection.tooltip")); //$NON-NLS-1$
setDescription(JavaEditorMessages.getString("AddImportOnSelection.description")); //$NON-NLS-1$
fEditor= editor;
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.ADD_IMPORT_ON_SELECTION_ACTION);
}
public AddImportOnSelectionAction() {
this(null);
}
public void setContentEditor(ITextEditor editor) {
fEditor= editor;
}
public void update() {
ISelection selection= fEditor.getSelectionProvider().getSelection();
setEnabled(selection instanceof ITextSelection);
}
private ICompilationUnit getCompilationUnit () {
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
return manager.getWorkingCopy(fEditor.getEditorInput());
}
/**
* @see IAction#actionPerformed
*/
public void run() {
ICompilationUnit cu= getCompilationUnit();
if (cu != null) {
ISelection s= fEditor.getSelectionProvider().getSelection();
IDocument doc= fEditor.getDocumentProvider().getDocument(fEditor.getEditorInput());
ITextSelection selection= (ITextSelection) s;
if (doc != null) {
try {
int nameStart= getNameStart(doc, selection.getOffset());
int nameEnd= getNameEnd(doc, selection.getOffset() + selection.getLength());
int len= nameEnd - nameStart;
String name= doc.get(nameStart, len).trim();
String simpleName= Signature.getSimpleName(name);
String containerName= Signature.getQualifier(name);
IJavaSearchScope searchScope= SearchEngine.createJavaSearchScope(new IJavaElement[] { cu.getJavaProject() });
TypeInfo[] types= findAllTypes(simpleName, searchScope, null);
if (types.length== 0) {
getShell().getDisplay().beep();
return;
}
TypeInfo chosen= selectResult(types, containerName, getShell());
if (chosen == null) {
return;
}
IType type= chosen.resolveType(searchScope);
if (type == null) {
JavaPlugin.logErrorMessage("AddImportOnSelectionAction: Failed to resolve TypeRef: " + chosen.toString()); //$NON-NLS-1$
MessageDialog.openError(getShell(), JavaEditorMessages.getString("AddImportOnSelection.error.title"), JavaEditorMessages.getString("AddImportOnSelection.error.notresolved.message")); //$NON-NLS-1$ //$NON-NLS-2$
return;
}
removeQualification(doc, nameStart, chosen);
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
AddImportsOperation op= new AddImportsOperation(cu, new IJavaElement[] { type }, settings, false);
ProgressMonitorDialog dialog= new ProgressMonitorDialog(getShell());
try {
dialog.run(false, true, new WorkbenchRunnableAdapter(op));
} catch (InvocationTargetException e) {
JavaPlugin.log(e);
MessageDialog.openError(getShell(), JavaEditorMessages.getString("AddImportOnSelection.error.title"), e.getTargetException().getMessage()); //$NON-NLS-1$
} catch (InterruptedException e) {
// Do nothing. Operation has been canceled.
}
return;
} catch (CoreException e) {
JavaPlugin.log(e);
ErrorDialog.openError(getShell(), JavaEditorMessages.getString("AddImportOnSelection.error.title"), null, e.getStatus()); //$NON-NLS-1$
} catch (BadLocationException e) {
JavaPlugin.log(e);
MessageDialog.openError(getShell(), JavaEditorMessages.getString("AddImportOnSelection.error.title"), e.getMessage()); //$NON-NLS-1$
}
}
}
}
private int getNameStart(IDocument doc, int pos) throws BadLocationException {
while (pos > 0) {
char ch= doc.getChar(pos - 1);
if (!Character.isJavaIdentifierPart(ch) && ch != '.') {
return pos;
}
pos--;
}
return pos;
}
private int getNameEnd(IDocument doc, int pos) throws BadLocationException {
int len= doc.getLength();
while (pos < len) {
char ch= doc.getChar(pos);
if (!Character.isJavaIdentifierPart(ch)) {
return pos;
}
pos++;
}
return pos;
}
private void removeQualification(IDocument doc, int nameStart, TypeInfo typeInfo) throws BadLocationException {
String containerName= typeInfo.getTypeContainerName();
int containerLen= containerName.length();
if (containerLen > 0) {
for (int k= 0; k < containerLen; k++) {
if (doc.getChar(nameStart + k) != containerName.charAt(k)) {
return;
}
}
doc.replace(nameStart, containerLen + 1, ""); //$NON-NLS-1$
}
}
/**
* Finds a type by the simple name.
*/
private static TypeInfo[] findAllTypes(String simpleTypeName, IJavaSearchScope searchScope, IProgressMonitor monitor) throws CoreException {
SearchEngine searchEngine= new SearchEngine();
ArrayList typeRefsFound= new ArrayList(10);
ITypeNameRequestor requestor= new TypeInfoRequestor(typeRefsFound);
searchEngine.searchAllTypeNames(
JavaPlugin.getWorkspace(),
null,
simpleTypeName.toCharArray(),
IJavaSearchConstants.EXACT_MATCH,
IJavaSearchConstants.CASE_SENSITIVE,
IJavaSearchConstants.TYPE,
searchScope,
requestor,
IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH,
monitor);
return (TypeInfo[]) typeRefsFound.toArray(new TypeInfo[typeRefsFound.size()]);
}
private Shell getShell() {
return fEditor.getSite().getShell();
}
private TypeInfo selectResult(TypeInfo[] results, String containerName, Shell shell) {
int nResults= results.length;
if (nResults == 0) {
return null;
} else if (nResults == 1) {
return results[0];
}
if (containerName.length() != 0) {
for (int i= 0; i < nResults; i++) {
TypeInfo curr= (TypeInfo) results[i];
if (containerName.equals(curr.getTypeContainerName())) {
return curr;
}
}
}
ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), new TypeInfoLabelProvider(TypeInfoLabelProvider.SHOW_FULLYQUALIFIED));
dialog.setTitle(JavaEditorMessages.getString("AddImportOnSelection.dialog.title")); //$NON-NLS-1$
dialog.setMessage(JavaEditorMessages.getString("AddImportOnSelection.dialog.message")); //$NON-NLS-1$
dialog.setElements(results);
if (dialog.open() == dialog.OK) {
return (TypeInfo) dialog.getFirstResult();
}
return null;
}
}
|
14,368 |
Bug 14368 Create getter and setter insert code into read-only file
|
1. Create a class C as follow: package jp1; public class C { private int id; } 2. Close it and mark it as read only 3. Reopen it and you should not be able to modify anything 4. From the outline view, select "id - int" and right mouse click and select "Create getter and setter". 5. The class becomes package jp1; public class C { private int id; /** * Gets the id. * @return Returns a int */ public int getId() { return id; } /** * Sets the id. * @param id The id to set */ public void setId(int id) { this.id = id; } } and the editor is dirty, but you cannot save it until clear the read-only flag.
|
resolved fixed
|
e6ed913
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-26T12:41:25Z | 2002-04-22T21:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/AddGetterSetterAction.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.ui.actions;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.corext.codemanipulation.AddGetterSetterOperation;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.codemanipulation.IRequestQuery;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.ActionMessages;
import org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.preferences.CodeGenerationPreferencePage;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
/**
* Create Getter and Setter for selected fields.
* Will open the parent compilation unit in the editor.
* The result is unsaved, so the user can decide if the
* changes are acceptable.
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 2.0
*/
public class AddGetterSetterAction extends SelectionDispatchAction {
/**
* Creates a new <code>AddGetterSetterAction</code>.
*
* @param site the site providing context information for this action
*/
public AddGetterSetterAction(IWorkbenchSite site) {
super(site);
setText(ActionMessages.getString("AddGetterSetterAction.label")); //$NON-NLS-1$
setDescription(ActionMessages.getString("AddGetterSetterAction.description")); //$NON-NLS-1$
setToolTipText(ActionMessages.getString("AddGetterSetterAction.tooltip")); //$NON-NLS-1$
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.GETTERSETTER_ACTION);
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void selectionChanged(IStructuredSelection selection) {
setEnabled(getSelectedFields(selection) != null);
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void run(IStructuredSelection selection) {
IField[] fields= getSelectedFields(selection);
if (fields == null) {
return;
}
try {
ICompilationUnit cu= fields[0].getCompilationUnit();
// open the editor, forces the creation of a working copy
IEditorPart editor= EditorUtility.openInEditor(cu);
ICompilationUnit workingCopyCU;
IField[] workingCopyFields;
if (cu.isWorkingCopy()) {
workingCopyCU= cu;
workingCopyFields= fields;
} else {
workingCopyCU= EditorUtility.getWorkingCopy(cu);
if (workingCopyCU == null) {
showError(ActionMessages.getString("AddGetterSetterAction.error.actionfailed")); //$NON-NLS-1$
return;
}
workingCopyFields= new IField[fields.length];
for (int i= 0; i < fields.length; i++) {
IField field= fields[i];
IField workingCopyField= (IField) JavaModelUtil.findMemberInCompilationUnit(workingCopyCU, field);
if (workingCopyField == null) {
showError(ActionMessages.getFormattedString("AddGetterSetterAction.error.fieldNotExisting", field.getElementName())); //$NON-NLS-1$
return;
}
workingCopyFields[i]= workingCopyField;
}
}
IRequestQuery skipSetterForFinalQuery= skipSetterForFinalQuery();
IRequestQuery skipReplaceQuery= skipReplaceQuery();
String[] prefixes= CodeGenerationPreferencePage.getGetterStetterPrefixes();
String[] suffixes= CodeGenerationPreferencePage.getGetterStetterSuffixes();
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
AddGetterSetterOperation op= new AddGetterSetterOperation(workingCopyFields, prefixes, suffixes, settings, skipSetterForFinalQuery, skipReplaceQuery);
ProgressMonitorDialog dialog= new ProgressMonitorDialog(getShell());
dialog.run(false, true, new WorkbenchRunnableAdapter(op));
IMethod[] createdMethods= op.getCreatedAccessors();
if (createdMethods.length > 0) {
EditorUtility.revealInEditor(editor, createdMethods[0]);
}
} catch (InvocationTargetException e) {
JavaPlugin.log(e);
showError(ActionMessages.getString("AddGetterSetterAction.error.actionfailed")); //$NON-NLS-1$
} catch (CoreException e) {
JavaPlugin.log(e.getStatus());
showError(ActionMessages.getString("AddGetterSetterAction.error.actionfailed")); //$NON-NLS-1$
return;
} catch (InterruptedException e) {
// operation cancelled
}
}
private IRequestQuery skipSetterForFinalQuery() {
return new IRequestQuery() {
public int doQuery(IMember field) {
int[] returnCodes= {IRequestQuery.YES, IRequestQuery.NO, IRequestQuery.YES_ALL, IRequestQuery.CANCEL};
String[] options= {IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.YES_TO_ALL_LABEL, IDialogConstants.CANCEL_LABEL};
String fieldName= JavaElementLabels.getElementLabel(field, 0);
String formattedMessage= ActionMessages.getFormattedString("AddGetterSetterAction.SkipSetterForFinalDialog.message", fieldName); //$NON-NLS-1$
return showQueryDialog(formattedMessage, options, returnCodes);
}
};
}
private IRequestQuery skipReplaceQuery() {
return new IRequestQuery() {
public int doQuery(IMember method) {
int[] returnCodes= {IRequestQuery.YES, IRequestQuery.NO, IRequestQuery.YES_ALL, IRequestQuery.CANCEL};
String skipLabel= ActionMessages.getString("AddGetterSetterAction.SkipExistingDialog.skip.label"); //$NON-NLS-1$
String replaceLabel= ActionMessages.getString("AddGetterSetterAction.SkipExistingDialog.replace.label"); //$NON-NLS-1$
String skipAllLabel= ActionMessages.getString("AddGetterSetterAction.SkipExistingDialog.skipAll.label"); //$NON-NLS-1$
String[] options= { skipLabel, replaceLabel, skipAllLabel, IDialogConstants.CANCEL_LABEL};
String methodName= JavaElementLabels.getElementLabel(method, JavaElementLabels.M_PARAMETER_TYPES);
String formattedMessage= ActionMessages.getFormattedString("AddGetterSetterAction.SkipExistingDialog.message", methodName); //$NON-NLS-1$
return showQueryDialog(formattedMessage, options, returnCodes);
}
};
}
private int showQueryDialog(final String message, final String[] buttonLabels, int[] returnCodes) {
final Shell shell= getShell();
if (shell == null) {
JavaPlugin.logErrorMessage("AddGetterSetterAction.showQueryDialog: No active shell found"); //$NON-NLS-1$
return IRequestQuery.CANCEL;
}
final int[] result= { MessageDialog.CANCEL };
shell.getDisplay().syncExec(new Runnable() {
public void run() {
String title= ActionMessages.getString("AddGetterSetterAction.QueryDialog.title"); //$NON-NLS-1$
MessageDialog dialog= new MessageDialog(shell, title, null, message, MessageDialog.QUESTION, buttonLabels, 0);
result[0]= dialog.open();
}
});
int returnVal= result[0];
return returnVal < 0 ? IRequestQuery.CANCEL : returnCodes[returnVal];
}
private void showError(String message) {
MessageDialog.openError(getShell(), getDialogTitle(), message);
}
/*
* Returns fields in the selection or <code>null</code> if the selection is
* empty or not valid.
*/
private IField[] getSelectedFields(IStructuredSelection selection) {
List elements= selection.toList();
int nElements= elements.size();
if (nElements > 0) {
IField[] res= new IField[nElements];
ICompilationUnit cu= null;
for (int i= 0; i < nElements; i++) {
Object curr= elements.get(i);
if (curr instanceof IField) {
IField fld= (IField)curr;
if (i == 0) {
// remember the cu of the first element
cu= fld.getCompilationUnit();
if (cu == null) {
return null;
}
} else if (!cu.equals(fld.getCompilationUnit())) {
// all fields must be in the same CU
return null;
}
try {
if (fld.getDeclaringType().isInterface()) {
// no setters/getters for interfaces
return null;
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
return null;
}
res[i]= fld;
} else {
return null;
}
}
return res;
}
return null;
}
private String getDialogTitle() {
return ActionMessages.getString("AddGetterSetterAction.error.title"); //$NON-NLS-1$
}
}
|
14,368 |
Bug 14368 Create getter and setter insert code into read-only file
|
1. Create a class C as follow: package jp1; public class C { private int id; } 2. Close it and mark it as read only 3. Reopen it and you should not be able to modify anything 4. From the outline view, select "id - int" and right mouse click and select "Create getter and setter". 5. The class becomes package jp1; public class C { private int id; /** * Gets the id. * @return Returns a int */ public int getId() { return id; } /** * Sets the id. * @param id The id to set */ public void setId(int id) { this.id = id; } } and the editor is dirty, but you cannot save it until clear the read-only flag.
|
resolved fixed
|
e6ed913
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-26T12:41:25Z | 2002-04-22T21:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/AddJavaDocStubAction.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.ui.actions;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.internal.corext.codemanipulation.AddJavaDocStubOperation;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
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.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
/**
* Create Java Doc Stubs for selected members
* Always forces the he field to be in an open editor. The result is unsaved,
* so the user can decide if he wnats to accept the changes.
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 2.0
*/
public class AddJavaDocStubAction extends SelectionDispatchAction {
/**
* Creates a new <code>AddJavaDocStubAction</code>.
*
* @param site the site providing context information for this action
*/
public AddJavaDocStubAction(IWorkbenchSite site) {
super(site);
setText(ActionMessages.getString("AddJavaDocStubAction.label")); //$NON-NLS-1$
setDescription(ActionMessages.getString("AddJavaDocStubAction.description")); //$NON-NLS-1$
setToolTipText(ActionMessages.getString("AddJavaDocStubAction.tooltip")); //$NON-NLS-1$
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void selectionChanged(IStructuredSelection selection) {
setEnabled(getSelectedMembers(selection) != null);
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void run(IStructuredSelection selection) {
IMember[] members= getSelectedMembers(selection);
if (members == null || members.length == 0) {
return;
}
try {
ICompilationUnit cu= members[0].getCompilationUnit();
// open the editor, forces the creation of a working copy
IEditorPart editor= EditorUtility.openInEditor(cu);
ICompilationUnit workingCopyCU;
IMember[] workingCopyMembers;
if (cu.isWorkingCopy()) {
workingCopyCU= cu;
workingCopyMembers= members;
} else {
// get the corresponding elements from the working copy
workingCopyCU= EditorUtility.getWorkingCopy(cu);
if (workingCopyCU == null) {
showError(ActionMessages.getString("AddJavaDocStubsAction.error.noWorkingCopy")); //$NON-NLS-1$
return;
}
workingCopyMembers= new IMember[members.length];
for (int i= 0; i < members.length; i++) {
IMember member= members[i];
IMember workingCopyMember= (IMember) JavaModelUtil.findMemberInCompilationUnit(workingCopyCU, member);
if (workingCopyMember == null) {
showError(ActionMessages.getFormattedString("AddJavaDocStubsAction.error.memberNotExisting", member.getElementName())); //$NON-NLS-1$
return;
}
workingCopyMembers[i]= workingCopyMember;
}
}
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
AddJavaDocStubOperation op= new AddJavaDocStubOperation(workingCopyMembers, settings);
ProgressMonitorDialog dialog= new ProgressMonitorDialog(getShell());
dialog.run(false, true, new WorkbenchRunnableAdapter(op));
EditorUtility.revealInEditor(editor, members[0]);
} catch (InvocationTargetException e) {
JavaPlugin.log(e);
showError(ActionMessages.getString("AddJavaDocStubsAction.error.actionFailed")); //$NON-NLS-1$
} catch (InterruptedException e) {
// operation cancelled
} catch (CoreException e) {
JavaPlugin.log(e.getStatus());
showError(ActionMessages.getString("AddJavaDocStubsAction.error.actionFailed")); //$NON-NLS-1$
return;
}
}
private void showError(String message) {
MessageDialog.openError(getShell(), getDialogTitle(), message);
}
private IMember[] getSelectedMembers(IStructuredSelection selection) {
List elements= selection.toList();
int nElements= elements.size();
if (nElements > 0) {
IMember[] res= new IMember[nElements];
ICompilationUnit cu= null;
for (int i= 0; i < nElements; i++) {
Object curr= elements.get(i);
if (curr instanceof IMethod || curr instanceof IType) {
IMember member= (IMember)curr; // limit to methods & types
if (i == 0) {
cu= member.getCompilationUnit();
if (cu == null) {
return null;
}
} else if (!cu.equals(member.getCompilationUnit())) {
return null;
}
res[i]= member;
} else {
return null;
}
}
return res;
}
return null;
}
private String getDialogTitle() {
return ActionMessages.getString("AddJavaDocStubsAction.error.dialogTitle"); //$NON-NLS-1$
}
}
|
14,368 |
Bug 14368 Create getter and setter insert code into read-only file
|
1. Create a class C as follow: package jp1; public class C { private int id; } 2. Close it and mark it as read only 3. Reopen it and you should not be able to modify anything 4. From the outline view, select "id - int" and right mouse click and select "Create getter and setter". 5. The class becomes package jp1; public class C { private int id; /** * Gets the id. * @return Returns a int */ public int getId() { return id; } /** * Sets the id. * @param id The id to set */ public void setId(int id) { this.id = id; } } and the editor is dirty, but you cannot save it until clear the read-only flag.
|
resolved fixed
|
e6ed913
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-26T12:41:25Z | 2002-04-22T21:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/AddUnimplementedConstructorsAction.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.ui.actions;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.corext.codemanipulation.AddUnimplementedConstructorsOperation;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
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.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
/**
* Evaluates constructors needed.
* Will open an editor for the type. Changes are unsaved.
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 2.0
*/
public class AddUnimplementedConstructorsAction extends SelectionDispatchAction {
/**
* Creates a new <code>AddUnimplementedConstructorsAction</code>.
*
* @param site the site providing context information for this action
*/
public AddUnimplementedConstructorsAction(IWorkbenchSite site) {
super(site);
setText(ActionMessages.getString("AddUnimplementedConstructorsAction.label")); //$NON-NLS-1$
setDescription(ActionMessages.getString("AddUnimplementedConstructorsAction.description")); //$NON-NLS-1$
setToolTipText(ActionMessages.getString("AddUnimplementedConstructorsAction.tooltip")); //$NON-NLS-1$
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.ADD_UNIMPLEMENTED_CONSTRUCTORS_ACTION);
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void selectionChanged(IStructuredSelection selection) {
boolean enabled= false;
try {
enabled= getSelectedType(selection) != null;
} catch (JavaModelException e) {
}
setEnabled(enabled);
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
public void run(IStructuredSelection selection) {
Shell shell= getShell();
try {
IType type= getSelectedType(selection);
if (type == null) {
return;
}
// open an editor and work on a working copy
IEditorPart editor= EditorUtility.openInEditor(type);
type= (IType)EditorUtility.getWorkingCopy(type);
if (type == null) {
MessageDialog.openError(shell, getDialogTitle(), ActionMessages.getString("AddUnimplementedConstructorsAction.error.type_removed_in_editor")); //$NON-NLS-1$
return;
}
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
AddUnimplementedConstructorsOperation op= new AddUnimplementedConstructorsOperation(type, settings, false);
try {
ProgressMonitorDialog dialog= new ProgressMonitorDialog(shell);
dialog.run(false, true, new WorkbenchRunnableAdapter(op));
IMethod[] res= op.getCreatedMethods();
if (res == null || res.length == 0) {
MessageDialog.openInformation(shell, getDialogTitle(), ActionMessages.getString("AddUnimplementedConstructorsAction.error.nothing_found")); //$NON-NLS-1$
} else if (editor != null) {
EditorUtility.revealInEditor(editor, res[0]);
}
} catch (InvocationTargetException e) {
JavaPlugin.log(e);
MessageDialog.openError(shell, getDialogTitle(), e.getTargetException().getMessage());
} catch (InterruptedException e) {
// Do nothing. Operation has been canceled by user.
}
} catch (CoreException e) {
JavaPlugin.log(e);
ErrorDialog.openError(shell, getDialogTitle(), null, e.getStatus());
}
}
private IType getSelectedType(IStructuredSelection selection) throws JavaModelException {
Object[] elements= selection.toArray();
if (elements.length == 1 && (elements[0] instanceof IType)) {
IType type= (IType) elements[0];
if (type.getCompilationUnit() != null && type.isClass()) {
return type;
}
}
return null;
}
private String getDialogTitle() {
return ActionMessages.getString("AddUnimplementedConstructorsAction.error.title"); //$NON-NLS-1$
}
}
|
14,368 |
Bug 14368 Create getter and setter insert code into read-only file
|
1. Create a class C as follow: package jp1; public class C { private int id; } 2. Close it and mark it as read only 3. Reopen it and you should not be able to modify anything 4. From the outline view, select "id - int" and right mouse click and select "Create getter and setter". 5. The class becomes package jp1; public class C { private int id; /** * Gets the id. * @return Returns a int */ public int getId() { return id; } /** * Sets the id. * @param id The id to set */ public void setId(int id) { this.id = id; } } and the editor is dirty, but you cannot save it until clear the read-only flag.
|
resolved fixed
|
e6ed913
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-26T12:41:25Z | 2002-04-22T21:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/OrganizeImportsAction.java
|
package org.eclipse.jdt.ui.actions;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.HashSet;
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.operation.IRunnableWithProgress;
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.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.IPackageFragment;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.IWorkingCopyManager;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.internal.corext.codemanipulation.OrganizeImportsOperation;
import org.eclipse.jdt.internal.corext.codemanipulation.OrganizeImportsOperation.IChooseImportQuery;
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.ImportOrganizePreferencePage;
import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.util.TypeInfoLabelProvider;
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);
}
}
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);
}
/**
* Creates a new <code>OrganizeImportsAction</code>.
* <p>
* Note: This constructor is for internal use only. Clients should not call this constructor.
* </p>
*/
public OrganizeImportsAction(JavaEditor editor) {
this(editor.getEditorSite());
fEditor= editor;
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
protected void selectionChanged(ITextSelection selection) {
setEnabled(fEditor != null);
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
protected void selectionChanged(IStructuredSelection selection) {
setEnabled(getCompilationUnits(selection).length > 0);
}
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:
IPackageFragment pack= (IPackageFragment) elem;
result.addAll(Arrays.asList(pack.getCompilationUnits()));
break;
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
return (ICompilationUnit[]) result.toArray(new ICompilationUnit[result.size()]);
}
/* (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);
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
protected void run(IStructuredSelection selection) {
ICompilationUnit[] cus= getCompilationUnits(selection);
if (cus.length == 1) {
runOnSingle(cus[0], true);
} 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 IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
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 InterruptedException {
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 {
String[] prefOrder= ImportOrganizePreferencePage.getImportOrderPreference();
int threshold= ImportOrganizePreferencePage.getImportNumberThreshold();
boolean ignoreLowerCaseNames= ImportOrganizePreferencePage.doIgnoreLowerCaseNames();
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];
try {
if (!cu.isWorkingCopy()) {
ICompilationUnit workingCopy= EditorUtility.getWorkingCopy(cu);
if (workingCopy != null) {
cu= workingCopy;
}
}
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, prefOrder, threshold, ignoreLowerCaseNames, !cu.isWorkingCopy(), doResolve, query);
op.run(new SubProgressMonitor(monitor, 1));
ISourceRange errorRange= op.getErrorSourceRange();
if (errorRange != null) {
String message= ActionMessages.getFormattedString("OrganizeImportsAction.multi.error.parse", cu.getElementName()); //$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", cu.getElementName()); //$NON-NLS-1$
status.add(new Status(Status.INFO, JavaUI.ID_PLUGIN, Status.ERROR, message, null));
} catch (CoreException e) {
JavaPlugin.log(e);
String message= ActionMessages.getFormattedString("OrganizeImportsAction.multi.error.unexpected", e.getMessage()); //$NON-NLS-1$
status.add(new Status(Status.ERROR, JavaUI.ID_PLUGIN, Status.ERROR, message, null));
} catch (OperationCanceledException e) {
throw new InterruptedException();
}
}
} finally {
monitor.done();
}
}
private void runOnSingle(ICompilationUnit cu, boolean doResolve) {
try {
String[] prefOrder= ImportOrganizePreferencePage.getImportOrderPreference();
int threshold= ImportOrganizePreferencePage.getImportNumberThreshold();
boolean ignoreLowerCaseNames= ImportOrganizePreferencePage.doIgnoreLowerCaseNames();
if (!cu.isWorkingCopy()) {
IEditorPart editor= EditorUtility.openInEditor(cu);
if (editor instanceof JavaEditor) {
fEditor= (JavaEditor) editor;
}
ICompilationUnit workingCopy= EditorUtility.getWorkingCopy(cu);
if (workingCopy != null) {
cu= workingCopy;
}
}
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 {
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() == dialog.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);
}
}
}
|
14,368 |
Bug 14368 Create getter and setter insert code into read-only file
|
1. Create a class C as follow: package jp1; public class C { private int id; } 2. Close it and mark it as read only 3. Reopen it and you should not be able to modify anything 4. From the outline view, select "id - int" and right mouse click and select "Create getter and setter". 5. The class becomes package jp1; public class C { private int id; /** * Gets the id. * @return Returns a int */ public int getId() { return id; } /** * Sets the id. * @param id The id to set */ public void setId(int id) { this.id = id; } } and the editor is dirty, but you cannot save it until clear the read-only flag.
|
resolved fixed
|
e6ed913
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-26T12:41:25Z | 2002-04-22T21:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/OverrideMethodsAction.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.ui.actions;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.corext.codemanipulation.AddUnimplementedMethodsOperation;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
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.OverrideMethodQuery;
import org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext;
/**
* Adds unimplemented methods of a type.
* Will open an editor for the type. Changes are unsaved.
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 2.0
*/
public class OverrideMethodsAction extends SelectionDispatchAction {
/**
* Creates a new <code>OverrideMethodsAction</code>.
*
* @param site the site providing context information for this action
*/
public OverrideMethodsAction(IWorkbenchSite site) {
super(site);
setText(ActionMessages.getString("OverrideMethodsAction.label")); //$NON-NLS-1$
setDescription(ActionMessages.getString("OverrideMethodsAction.description")); //$NON-NLS-1$
setToolTipText(ActionMessages.getString("OverrideMethodsAction.tooltip")); //$NON-NLS-1$
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.ADD_UNIMPLEMENTED_METHODS_ACTION);
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void selectionChanged(IStructuredSelection selection) {
boolean enabled= false;
try {
enabled= getSelectedType(selection) != null;
} catch (JavaModelException e) {
}
setEnabled(enabled);
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void run(IStructuredSelection selection) {
Shell shell= getShell();
try {
IType type= getSelectedType(selection);
if (type == null) {
return;
}
// open an editor and work on a working copy
IEditorPart editor= EditorUtility.openInEditor(type);
type= (IType)EditorUtility.getWorkingCopy(type);
if (type == null) {
MessageDialog.openError(shell, getDialogTitle(), ActionMessages.getString("OverrideMethodsAction.error.type_removed_in_editor")); //$NON-NLS-1$
return;
}
OverrideMethodQuery selectionQuery= new OverrideMethodQuery(shell, false);
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
AddUnimplementedMethodsOperation op= new AddUnimplementedMethodsOperation(type, settings, selectionQuery, false);
try {
BusyIndicatorRunnableContext context= new BusyIndicatorRunnableContext();
context.run(false, true, new WorkbenchRunnableAdapter(op));
IMethod[] res= op.getCreatedMethods();
if (res == null || res.length == 0) {
MessageDialog.openInformation(shell, getDialogTitle(), ActionMessages.getString("OverrideMethodsAction.error.nothing_found")); //$NON-NLS-1$
} else if (editor != null) {
EditorUtility.revealInEditor(editor, res[0]);
}
} catch (InvocationTargetException e) {
JavaPlugin.log(e);
MessageDialog.openError(shell, getDialogTitle(), e.getTargetException().getMessage());
} catch (InterruptedException e) {
// Do nothing. Operation has been canceled by user.
}
} catch (CoreException e) {
JavaPlugin.log(e);
ErrorDialog.openError(shell, getDialogTitle(), null, e.getStatus());
}
}
private IType getSelectedType(IStructuredSelection selection) throws JavaModelException {
Object[] elements= selection.toArray();
if (elements.length == 1 && (elements[0] instanceof IType)) {
IType type= (IType) elements[0];
if (type.getCompilationUnit() != null && type.isClass()) {
return type;
}
}
return null;
}
private String getDialogTitle() {
return ActionMessages.getString("OverrideMethodsAction.error.title"); //$NON-NLS-1$
}
}
|
14,368 |
Bug 14368 Create getter and setter insert code into read-only file
|
1. Create a class C as follow: package jp1; public class C { private int id; } 2. Close it and mark it as read only 3. Reopen it and you should not be able to modify anything 4. From the outline view, select "id - int" and right mouse click and select "Create getter and setter". 5. The class becomes package jp1; public class C { private int id; /** * Gets the id. * @return Returns a int */ public int getId() { return id; } /** * Sets the id. * @param id The id to set */ public void setId(int id) { this.id = id; } } and the editor is dirty, but you cannot save it until clear the read-only flag.
|
resolved fixed
|
e6ed913
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-26T12:41:25Z | 2002-04-22T21:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/wizards/NewTypeWizardPage.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
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.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.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.internal.compiler.env.IConstants;
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.CodeGenerationPreferencePage;
import org.eclipse.jdt.internal.ui.preferences.ImportOrganizePreferencePage;
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;
/**
* <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.
* Applets, Servlets, Classes, Interfaces...
* See <code>NewClassWizardPage</code> or <code>NewInterfaceWizardPage</code> for an
* example usage of NewTypeWizardPage.
* @since 2.0
*/
public abstract class NewTypeWizardPage extends NewContainerWizardPage {
private final static String PAGE_NAME= "NewTypeWizardPage"; //$NON-NLS-1$
protected final static String PACKAGE= PAGE_NAME + ".package"; //$NON-NLS-1$
protected final static String ENCLOSING= PAGE_NAME + ".enclosing"; //$NON-NLS-1$
protected final static String ENCLOSINGSELECTION= ENCLOSING + ".selection"; //$NON-NLS-1$
protected final static String TYPENAME= PAGE_NAME + ".typename"; //$NON-NLS-1$
protected final static String SUPER= PAGE_NAME + ".superclass"; //$NON-NLS-1$
protected final static String INTERFACES= PAGE_NAME + ".interfaces"; //$NON-NLS-1$
protected final static String MODIFIERS= PAGE_NAME + ".modifiers"; //$NON-NLS-1$
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;
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 type page with a given
* Java element as selection. To implement a different selection strategy do not call this
* method or overwrite it.
* @param elem The initial selection of this page or null 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 GridLayout 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 GridLayout 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 GridLayout 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 GridLayout 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 GridLayout 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 GridLayout 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 GridLayout 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.
*/
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(DialogField field, int index) {
typePageCustomButtonPressed(field, index);
}
public void selectionChanged(DialogField field) {}
// -------- IDialogFieldListener
public void dialogFieldChanged(DialogField field) {
typePageDialogFieldChanged(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 ----------------
/**
* Called whenever a content of a field has changed.
* Implementors of NewTypeWizardPage can hook in.
* @see ContainerPage#handleFieldChanged
*/
protected void handleFieldChanged(String fieldName) {
super.handleFieldChanged(fieldName);
if (fieldName == CONTAINER) {
fPackageStatus= packageChanged();
fEnclosingTypeStatus= enclosingTypeChanged();
fTypeNameStatus= typeNameChanged();
fSuperClassStatus= superClassChanged();
fSuperInterfacesStatus= superInterfacesChanged();
}
}
// ---- set / get ----------------
/**
* Gets the text of package field.
*/
public String getPackageText() {
return fPackageDialogField.getText();
}
/**
* Gets the text of enclosing type field.
*/
public String getEnclosingTypeText() {
return fEnclosingTypeDialogField.getText();
}
/**
* Returns the package fragment corresponding to the current input.
* @return Returns <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.
* This will update model and the text of the control.
* @param canBeModified Selects if the package fragment can be changed by the user
*/
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 Returns <code>null</code> if 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.
* This will update model and the text of the control.
* @param canBeModified Selects if the enclosing type can be changed by the user
*/
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 <code>true</code> if the enclosing type selection check box is enabled.
*/
public boolean isEnclosingTypeSelected() {
return fEnclosingTypeSelection.isSelected();
}
/**
* Sets the enclosing type selection checkbox.
* @param canBeModified Selects if the enclosing type selection can be changed by the user
*/
public void setEnclosingTypeSelection(boolean isSelected, boolean canBeModified) {
fEnclosingTypeSelection.setSelection(isSelected);
fEnclosingTypeSelection.setEnabled(canBeModified);
updateEnableState();
}
/**
* Gets the type name.
*/
public String getTypeName() {
return fTypeNameDialogField.getText();
}
/**
* Sets the type name.
* @param canBeModified Selects if the type name can be changed by the user
*/
public void setTypeName(String name, boolean canBeModified) {
fTypeNameDialogField.setText(name);
fTypeNameDialogField.setEnabled(canBeModified);
}
/**
* Gets the selected modifiers.
* @see Flags
*/
public int getModifiers() {
int mdf= 0;
if (fAccMdfButtons.isSelected(PUBLIC_INDEX)) {
mdf+= IConstants.AccPublic;
} else if (fAccMdfButtons.isSelected(PRIVATE_INDEX)) {
mdf+= IConstants.AccPrivate;
} else if (fAccMdfButtons.isSelected(PROTECTED_INDEX)) {
mdf+= IConstants.AccProtected;
}
if (fOtherMdfButtons.isSelected(ABSTRACT_INDEX) && (fStaticMdfIndex != 0)) {
mdf+= IConstants.AccAbstract;
}
if (fOtherMdfButtons.isSelected(FINAL_INDEX)) {
mdf+= IConstants.AccFinal;
}
if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) {
mdf+= IConstants.AccStatic;
}
return mdf;
}
/**
* Sets the modifiers.
* @param canBeModified Selects if the modifiers can be changed by the user
* @see IConstants
*/
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);
}
/**
* Gets the content of the super class text field.
*/
public String getSuperClass() {
return fSuperClassDialogField.getText();
}
/**
* Sets the super class name.
* @param canBeModified Selects if the super class can be changed by the user
*/
public void setSuperClass(String name, boolean canBeModified) {
fSuperClassDialogField.setText(name);
fSuperClassDialogField.setEnabled(canBeModified);
}
/**
* Gets the currently chosen super interfaces.
* @return returns a list of String
*/
public List getSuperInterfaces() {
return fSuperInterfacesDialogField.getElements();
}
/**
* Sets the super interfaces.
* @param canBeModified Selects if the modifiers can be changed by the user.
* @param interfacesNames a list of String
*/
public void setSuperInterfaces(List interfacesNames, boolean canBeModified) {
fSuperInterfacesDialogField.setElements(interfacesNames);
fSuperInterfacesDialogField.setEnabled(canBeModified);
}
// ----------- validation ----------
/**
* Called when the package field has changed.
* The method validates the package name and returns the status of the validation
* This also updates the package fragment model.
* Can be extended to add more 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);
}
/**
* Called when the enclosing type name has changed.
* The method validates the enclosing type and returns the status of the validation
* This also updates the enclosing type model.
* Can be extended to add more 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;
}
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;
}
}
/**
* Called when the type name has changed.
* The method validates the type name and returns the status of the validation.
* Can be extended to add more 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;
}
/**
* Called when the superclass name has changed.
* The method validates the superclass name and returns the status of the validation.
* Can be extended to add more 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;
}
/**
* Called when the list of super interface has changed.
* The method validates the superinterfaces and returns the status of the validation.
* Can be extended to add more 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;
}
/**
* Called when the modifiers have changed.
* The method validates the modifiers and returns the status of the validation.
* Can be extended to add more 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) {
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);
if (fCurrPackage != null) {
dialog.setInitialSelections(new Object[] { fCurrPackage });
}
if (dialog.open() == dialog.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$
if (fCurrEnclosingType != null) {
dialog.setInitialSelections(new Object[] { fCurrEnclosingType });
dialog.setFilter(fCurrEnclosingType.getElementName().substring(0, 1));
}
if (dialog.open() == dialog.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$
if (fSuperClass != null) {
dialog.setFilter(fSuperClass.getElementName());
}
if (dialog.open() == dialog.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 a type using the current field values.
*/
public void createType(IProgressMonitor monitor) throws CoreException, InterruptedException {
monitor.beginTask(NewWizardMessages.getString("NewTypeWizardPage.operationdesc"), 10); //$NON-NLS-1$
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;
String[] prefOrder= ImportOrganizePreferencePage.getImportOrderPreference();
int threshold= ImportOrganizePreferencePage.getImportNumberThreshold();
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", packStatement, false, new SubProgressMonitor(monitor, 2)); //$NON-NLS-1$
imports= new ImportsStructure(parentCU, prefOrder, threshold, false);
String content= constructTypeStub(imports, lineDelimiter, parentCU);
createdType= parentCU.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);
lineDelimiter= StubUtility.getLineDelimiterUsed(enclosingType);
String content= constructTypeStub(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(!isInnerClass, new SubProgressMonitor(monitor, 1));
createTypeMembers(createdType, imports, new SubProgressMonitor(monitor, 1));
// add imports
imports.create(!isInnerClass, new SubProgressMonitor(monitor, 1));
ICompilationUnit cu= createdType.getCompilationUnit();
ISourceRange range;
if (isInnerClass) {
synchronized(cu) {
cu.reconcile();
}
range= createdType.getSourceRange();
} else {
range= cu.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);
}
buf.save(new SubProgressMonitor(monitor, 1), false);
} else {
monitor.worked(1);
}
fCreatedType= createdType;
monitor.done();
}
/**
* Returns the created type. Only valid after createType has been invoked
*/
public IType getCreatedType() {
return fCreatedType;
}
// ---- construct cu body----------------
private void writeSuperClass(StringBuffer buf, IImportsStructure imports) {
String typename= getSuperClass();
if (fIsClass && typename.length() > 0 && !"java.lang.Object".equals(typename)) { //$NON-NLS-1$
buf.append(" extends "); //$NON-NLS-1$
buf.append(Signature.getSimpleName(typename));
if (fSuperClass != null) {
imports.addImport(JavaModelUtil.getFullyQualifiedName(fSuperClass));
} else {
imports.addImport(typename);
}
}
}
private void writeSuperInterfaces(StringBuffer buf, IImportsStructure 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);
imports.addImport(typename);
buf.append(Signature.getSimpleName(typename));
if (i < last) {
buf.append(',');
}
}
}
}
/*
* Called from createType to construct the source for this type
*/
private String constructTypeStub(IImportsStructure 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();
}
/**
* Called from createType to allow adding methods, fielse, inner types ect for the newly created type.
* Implementors can use the create methods on the new type.
* Formatting will be applied to the content by the createType
* @param newType The new type to add members to
* @param imports To add the needed imports to.
* @param monitor Progress monitor
*/
protected void createTypeMembers(IType newType, IImportsStructure imports, IProgressMonitor monitor) throws CoreException {
// default implementation does nothing
// example would be
// String mainMathod= "public static void main(String[]) {}"
// createdType.createMethod(main, null, false, null);
}
/**
* Called from createType to get a file comment. By default the content of template
* 'filecomment' is taken.
* Returns source or null, if no file comment should be added
*/
protected String getFileComment(ICompilationUnit parentCU) {
if (CodeGenerationPreferencePage.doFileComments()) {
return getTemplate("filecomment", parentCU); //$NON-NLS-1$
}
return null;
}
/**
* Called from createType to get a type comment.
* Returns source or null, if no type comment should be added
*/
protected String getTypeComment(ICompilationUnit parentCU) {
if (CodeGenerationPreferencePage.doCreateComments()) {
return getTemplate("typecomment", parentCU); //$NON-NLS-1$
}
return null;
}
/**
* Gets the template of the given name, evaluated in the context of a CU.
*/
protected String getTemplate(String name, ICompilationUnit parentCU) {
try {
Template[] templates= Templates.getInstance().getTemplates(name);
if (templates.length > 0) {
return JavaContext.evaluateTemplate(templates[0], parentCU);
}
} catch (CoreException e) {
JavaPlugin.log(e);
}
return null;
}
/**
* Creates the bodies of all unimplemented methods or/and all constructors and adds them to the type
* Can be used by implementors of NewTypeWizardPage to add method stub checkboxes.
*/
protected IMethod[] createInheritedMethods(IType type, boolean doConstructors, boolean doUnimplementedMethods, IImportsStructure imports, IProgressMonitor monitor) throws CoreException {
List 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);
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);
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"; //$NON-NLS-1$
createdMethods[i]= type.createMethod(content, null, false, null);
}
return createdMethods;
}
// ---- creation ----------------
/**
* Returns a runnable that creates a type using the current settings.
* To be called in the UI thread.
*/
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);
}
}
};
}
}
|
14,572 |
Bug 14572 JavaCapatibilityConfigurationPage.java misspelled
|
org.eclipse.jdt.ui.wizards.JavaCapatibilityConfigurationPage.java Should probably be spelled: org.eclipse.jdt.ui.wizards.JavaCapabilityConfigurationPage.java (capability instead of capatibility)
|
resolved fixed
|
d9209ec
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-26T15:10:20Z | 2002-04-25T02:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/JavaCapabilityWizard.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.resources.IWorkspaceRoot;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.ICapabilityInstallWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.actions.WorkspaceModifyDelegatingOperation;
import org.eclipse.jdt.ui.wizards.JavaCapatibilityConfigurationPage;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
public class JavaCapabilityWizard extends Wizard implements ICapabilityInstallWizard {
private JavaCapatibilityConfigurationPage fJavaPage;
private IProject fProject;
public JavaCapabilityWizard() {
super();
setDefaultPageImageDescriptor(JavaPluginImages.DESC_WIZBAN_NEWJPRJ);
setDialogSettings(JavaPlugin.getDefault().getDialogSettings());
setWindowTitle(NewWizardMessages.getString("JavaCapabilityWizard.title")); //$NON-NLS-1$
}
/*
* @see ICapabilityWizard#init(IWorkbench, IStructuredSelection, IProject)
*/
public void init(IWorkbench workbench, IStructuredSelection selection, IProject project) {
fProject= project;
}
/*
* @see Wizard#addPages
*/
public void addPages() {
super.addPages();
IWorkspaceRoot root= JavaPlugin.getWorkspace().getRoot();
fJavaPage= new JavaCapatibilityConfigurationPage(fProject);
addPage(fJavaPage);
}
/*
* @see Wizard#performFinish
*/
public boolean performFinish() {
IRunnableWithProgress op= new WorkspaceModifyDelegatingOperation(fJavaPage.getRunnable());
try {
getContainer().run(false, true, op);
} catch (InvocationTargetException e) {
String title= NewWizardMessages.getString("JavaCapabilityWizard.op_error.title"); //$NON-NLS-1$
String message= NewWizardMessages.getString("JavaCapabilityWizard.op_error.message"); //$NON-NLS-1$
ExceptionHandler.handle(e, getShell(), title, message);
return false;
} catch (InterruptedException e) {
return false;
}
return true;
}
}
|
14,572 |
Bug 14572 JavaCapatibilityConfigurationPage.java misspelled
|
org.eclipse.jdt.ui.wizards.JavaCapatibilityConfigurationPage.java Should probably be spelled: org.eclipse.jdt.ui.wizards.JavaCapabilityConfigurationPage.java (capability instead of capatibility)
|
resolved fixed
|
d9209ec
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-26T15:10:20Z | 2002-04-25T02:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/wizards/JavaCapabilityConfigurationPage.java
| |
14,572 |
Bug 14572 JavaCapatibilityConfigurationPage.java misspelled
|
org.eclipse.jdt.ui.wizards.JavaCapatibilityConfigurationPage.java Should probably be spelled: org.eclipse.jdt.ui.wizards.JavaCapabilityConfigurationPage.java (capability instead of capatibility)
|
resolved fixed
|
d9209ec
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-26T15:10:20Z | 2002-04-25T02:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/wizards/JavaCapatibilityConfigurationPage.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.ui.wizards;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
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.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.jface.wizard.WizardPage;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
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;
/**
* Wizard page to be used for capability wizards that want to configure Java build page.
*/
public class JavaCapatibilityConfigurationPage extends NewElementWizardPage {
private static final String PAGE_NAME= "NewJavaProjectWizardPage"; //$NON-NLS-1$
private IJavaProject fJavaProject;
private BuildPathsBlock fBuildPathsBlock;
/**
* Creates a Java project wizard creation page.
* <p>
* The Java project wizard reads project name and location from the main page.
* </p>
*
* @param project the project to configure
*/
public JavaCapatibilityConfigurationPage(IProject project) {
super(PAGE_NAME);
fJavaProject= JavaCore.create(project);
setTitle(NewWizardMessages.getString("NewJavaProjectWizardPage.title")); //$NON-NLS-1$
setDescription(NewWizardMessages.getString("NewJavaProjectWizardPage.description")); //$NON-NLS-1$
IStatusChangeListener listener= new IStatusChangeListener() {
public void statusChanged(IStatus status) {
updateStatus(status);
}
};
fBuildPathsBlock= new BuildPathsBlock(ResourcesPlugin.getWorkspace().getRoot(), listener, true);
fBuildPathsBlock.init(fJavaProject, null, null);
}
/**
* Sets the build paths to be used as default by the new Java project.
* <p>
* The caller of this method is responsible for creating the classpath entries
* for the <code>IJavaProject</code> that corresponds to the created project.
* The caller is responsible for creating any new folders that might be mentioned
* on the classpath.
* </p>
* <p>
* The wizard will create the output folder if required.
* </p>
*
*
* @param entries the default classpath entries or <code>null</code> to take the default
* @param path the folder to be taken as the default output path or <code>null</code> to take the default
* @return overrideExistingClasspath If set to true, an existing '.classpath' file is ignored. If set to <code>false</code>
* the default classpath is only used if no '.classpath' exists.
*/
public void setDefaultPaths(IPath outputLocation, IClasspathEntry[] entries, boolean overrideExistingClasspath) {
if (!overrideExistingClasspath && fJavaProject.getProject().getFile(".classpath").exists()) { //$NON-NLS-1$
entries= null;
outputLocation= null;
}
fBuildPathsBlock.init(fJavaProject, outputLocation, entries);
}
/* (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 must not be valid.
*/
public IPath getOutputLocation() {
return fBuildPathsBlock.getOutputLocation();
}
/**
* Returns the currently configured class path. Note that the class path must not be valid.
*/
public IClasspathEntry[] getRawClassPath() {
return fBuildPathsBlock.getRawClassPath();
}
/**
* Returns the runnable that will create the Java project.
* The runnable sets the project's classpath and output location to the values configured in the page.
*
* @return the runnable
*/
public IRunnableWithProgress getRunnable() {
return new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
if (monitor == null) {
monitor= new NullProgressMonitor();
}
int nSteps= 10;
monitor.beginTask(NewWizardMessages.getString("NewJavaProjectWizardPage.op_desc"), nSteps); //$NON-NLS-1$
try {
IProject project= fJavaProject.getProject();
if (!project.hasNature(JavaCore.NATURE_ID)) {
addNatureToProject(project, JavaCore.NATURE_ID, new SubProgressMonitor(monitor, 1));
nSteps--;
}
// configure the build paths
IRunnableWithProgress jrunnable= fBuildPathsBlock.getRunnable();
jrunnable.run(new SubProgressMonitor(monitor, nSteps));
} catch (CoreException e) {
throw new InvocationTargetException(e);
} finally {
monitor.done();
}
}
};
}
/**
* Adds a nature to a project
*/
private static void addNatureToProject(IProject proj, String natureId, IProgressMonitor monitor) throws CoreException {
IProjectDescription description = proj.getDescription();
String[] prevNatures= description.getNatureIds();
String[] newNatures= new String[prevNatures.length + 1];
System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length);
newNatures[prevNatures.length]= natureId;
description.setNatureIds(newNatures);
proj.setDescription(description, monitor);
}
}
|
14,438 |
Bug 14438 JarPackager support for setting comment on jar
|
Would it be possible to support setting a comment on jars? I'm more interested in doing this via the API than the UI. One approach would be to set something in the JarPackageData which the JarWriter can extract and call setComment() on the JarOutputStream. Alternatively, if the output stream were made accessible to subclasses of JarWriter, I could have my own writer handle this. The ability to set a comment is actually at the ZipOutputStream level, so maybe this needs to go even further down.
|
resolved fixed
|
bc4712f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-30T09:00:16Z | 2002-04-23T16:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/jarpackager/JarPackageData.java
| |
14,438 |
Bug 14438 JarPackager support for setting comment on jar
|
Would it be possible to support setting a comment on jars? I'm more interested in doing this via the API than the UI. One approach would be to set something in the JarPackageData which the JarWriter can extract and call setComment() on the JarOutputStream. Alternatively, if the output stream were made accessible to subclasses of JarWriter, I could have my own writer handle this. The ability to set a comment is actually at the ZipOutputStream level, so maybe this needs to go even further down.
|
resolved fixed
|
bc4712f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-30T09:00:16Z | 2002-04-23T16:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/jarpackager/JarWriter.java
| |
14,891 |
Bug 14891 NPE during organize imports
|
Build 20020425.3 java.lang.NullPointerException Stack trace: java/lang/Throwable.<init>()V java/lang/Throwable.<init>(Ljava/lang/String;)V java/lang/NullPointerException.<init>(Ljava/lang/String;)V org/eclipse/jdt/ui/actions/OrganizeImportsAction.setStatusBarMessage (Ljava/lang/String;)V org/eclipse/jdt/ui/actions/OrganizeImportsAction.runOnSingle (Lorg/eclipse/jdt/core/ICompilationUnit;Z)V org/eclipse/jdt/ui/actions/OrganizeImportsAction.run (Lorg/eclipse/jface/viewers/IStructuredSelection;)V org/eclipse/jdt/ui/actions/SelectionDispatchAction.dispatchRun (Lorg/eclipse/jface/viewers/ISelection;)V org/eclipse/jdt/ui/actions/SelectionDispatchAction.run()V org/eclipse/jface/action/Action.runWithEvent(Lorg/eclipse/swt/widgets/Event;) V org/eclipse/jface/action/ActionContributionItem.handleWidgetSelection (Lorg/eclipse/swt/widgets/Event;)V org/eclipse/jface/action/ActionContributionItem.handleWidgetEvent (Lorg/eclipse/swt/widgets/Event;)V org/eclipse/jface/action/ActionContributionItem.access$0 (Lorg/eclipse/jface/action/ActionContributionItem;Lorg/eclipse/swt/widgets/Event ;)V org/eclipse/jface/action/ActionContributionItem$ActionListener.handleEvent (Lorg/eclipse/swt/widgets/Event;)V org/eclipse/swt/widgets/EventTable.sendEvent(Lorg/eclipse/swt/widgets/Event;) V org/eclipse/swt/widgets/Widget.notifyListeners (ILorg/eclipse/swt/widgets/Event;)V org/eclipse/swt/widgets/Display.runDeferredEvents()Z org/eclipse/swt/widgets/Display.readAndDispatch()Z org/eclipse/ui/internal/Workbench.runEventLoop()V org/eclipse/ui/internal/Workbench.run(Ljava/lang/Object;)Ljava/lang/Object; org/eclipse/core/internal/boot/InternalBootLoader.run (Ljava/lang/String;Ljava/net/URL;Ljava/lang/String; [Ljava/lang/String;Ljava/lang/Runnable;)Ljava/lang/Object; org/eclipse/core/boot/BootLoader.run (Ljava/lang/String;Ljava/net/URL;Ljava/lang/String;[Ljava/lang/String;) Ljava/lang/Object; EclipseRuntimeLauncher.main([Ljava/lang/String;)V
|
resolved fixed
|
d8124c0
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-30T12:08:21Z | 2002-04-30T09:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/OrganizeImportsAction.java
|
package org.eclipse.jdt.ui.actions;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.HashSet;
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.operation.IRunnableWithProgress;
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.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.IPackageFragment;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.IWorkingCopyManager;
import org.eclipse.jdt.ui.JavaUI;
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.ImportOrganizePreferencePage;
import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.util.TypeInfoLabelProvider;
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);
}
}
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);
}
/**
* Creates a new <code>OrganizeImportsAction</code>.
* <p>
* Note: This constructor is for internal use only. Clients should not call this constructor.
* </p>
*/
public OrganizeImportsAction(JavaEditor editor) {
this(editor.getEditorSite());
fEditor= editor;
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
protected void selectionChanged(ITextSelection selection) {
boolean isEnabled= false;
try {
if (fEditor != null) {
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
ICompilationUnit cu= manager.getWorkingCopy(fEditor.getEditorInput());
isEnabled= JavaModelUtil.isEditable(cu);
}
} catch (JavaModelException e) {
}
setEnabled(isEnabled);
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
protected void selectionChanged(IStructuredSelection selection) {
ICompilationUnit[] cus= getCompilationUnits(selection);
boolean isEnabled= cus.length > 0;
try {
for (int i= 0; i < cus.length; i++) {
if (!JavaModelUtil.isEditable(cus[i])) {
isEnabled= false;
break;
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
setEnabled(isEnabled);
}
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:
IPackageFragment pack= (IPackageFragment) elem;
result.addAll(Arrays.asList(pack.getCompilationUnits()));
break;
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
return (ICompilationUnit[]) result.toArray(new ICompilationUnit[result.size()]);
}
/* (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);
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
protected void run(IStructuredSelection selection) {
ICompilationUnit[] cus= getCompilationUnits(selection);
if (cus.length == 1) {
runOnSingle(cus[0], true);
} 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 IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
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 InterruptedException {
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 {
String[] prefOrder= ImportOrganizePreferencePage.getImportOrderPreference();
int threshold= ImportOrganizePreferencePage.getImportNumberThreshold();
boolean ignoreLowerCaseNames= ImportOrganizePreferencePage.doIgnoreLowerCaseNames();
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];
try {
if (!cu.isWorkingCopy()) {
ICompilationUnit workingCopy= EditorUtility.getWorkingCopy(cu);
if (workingCopy != null) {
cu= workingCopy;
}
}
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, prefOrder, threshold, ignoreLowerCaseNames, !cu.isWorkingCopy(), doResolve, query);
op.run(new SubProgressMonitor(monitor, 1));
ISourceRange errorRange= op.getErrorSourceRange();
if (errorRange != null) {
String message= ActionMessages.getFormattedString("OrganizeImportsAction.multi.error.parse", cu.getElementName()); //$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", cu.getElementName()); //$NON-NLS-1$
status.add(new Status(Status.INFO, JavaUI.ID_PLUGIN, Status.ERROR, message, null));
} catch (CoreException e) {
JavaPlugin.log(e);
String message= ActionMessages.getFormattedString("OrganizeImportsAction.multi.error.unexpected", e.getMessage()); //$NON-NLS-1$
status.add(new Status(Status.ERROR, JavaUI.ID_PLUGIN, Status.ERROR, message, null));
} catch (OperationCanceledException e) {
throw new InterruptedException();
}
}
} finally {
monitor.done();
}
}
private void runOnSingle(ICompilationUnit cu, boolean doResolve) {
try {
String[] prefOrder= ImportOrganizePreferencePage.getImportOrderPreference();
int threshold= ImportOrganizePreferencePage.getImportNumberThreshold();
boolean ignoreLowerCaseNames= ImportOrganizePreferencePage.doIgnoreLowerCaseNames();
if (!cu.isWorkingCopy()) {
IEditorPart editor= EditorUtility.openInEditor(cu);
if (editor instanceof JavaEditor) {
fEditor= (JavaEditor) editor;
}
ICompilationUnit workingCopy= EditorUtility.getWorkingCopy(cu);
if (workingCopy != null) {
cu= workingCopy;
}
}
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 {
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() == dialog.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);
}
}
}
|
9,440 |
Bug 9440 Duplicate non-qualified class names no handled by import generator
|
If I have two types: org.acme.goodstuff.MyType and org.acme.coolstuff.MyType and I use Code Completion (or something that invokes the smart import logic). The smart import stuff generates imports for both references to these types, ignoring the fact that one of them has to remain qualified in the code in order not to conflict with the other. You cannot have two import statements which resolve the same non-qualified type identifier. The standard library has some instances of this (for instance the Interface 'Certificate' and the abstract Class 'Certificate').
|
resolved fixed
|
5105ba9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-30T14:15:35Z | 2002-02-12T05:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/AnonymousTypeCompletionProposal.java
|
package org.eclipse.jdt.internal.ui.text.java;
import org.eclipse.swt.graphics.Image;
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.core.runtime.CoreException;
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.CodeFormatterUtil;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
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.ImportOrganizePreferencePage;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
public class AnonymousTypeCompletionProposal extends JavaCompletionProposal {
private IType fDeclaringType;
private ICompilationUnit fCompilationUnit;
private ImportsStructure fImportStructure;
public AnonymousTypeCompletionProposal(IJavaProject jproject, ICompilationUnit cu, int start, int length, String constructorCompletion, String displayName, String declaringTypeName, int relevance) {
super(constructorCompletion, start, length, null, displayName, relevance);
Assert.isNotNull(declaringTypeName);
Assert.isNotNull(jproject);
fCompilationUnit= cu; // can be null -> no imports
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;
}
/*
* @see JavaCompletionProposal#applyImports(IDocument)
*/
protected void applyImports(IDocument document) {
if (fImportStructure != null) {
try {
fImportStructure.create(false, null);
} catch (CoreException e) {
JavaPlugin.log(e);
}
}
}
/*
* @see ICompletionProposalExtension#apply(IDocument, char)
*/
public void apply(IDocument document, char trigger, int offset) {
try {
if (fCompilationUnit == null) {
fImportStructure= null;
} else {
String[] prefOrder= ImportOrganizePreferencePage.getImportOrderPreference();
int threshold= ImportOrganizePreferencePage.getImportNumberThreshold();
fImportStructure= new ImportsStructure(fCompilationUnit, prefOrder, threshold, true);
}
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, fImportStructure)) {
return;
}
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);
replacement= Strings.trimLeadingTabsAndSpaces(replacement);
setReplacementString(replacement);
} catch (BadLocationException e) {
JavaPlugin.log(e);
} catch (CoreException e) {
JavaPlugin.log(e);
}
super.apply(document, trigger, offset);
}
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;
}
}
|
9,440 |
Bug 9440 Duplicate non-qualified class names no handled by import generator
|
If I have two types: org.acme.goodstuff.MyType and org.acme.coolstuff.MyType and I use Code Completion (or something that invokes the smart import logic). The smart import stuff generates imports for both references to these types, ignoring the fact that one of them has to remain qualified in the code in order not to conflict with the other. You cannot have two import statements which resolve the same non-qualified type identifier. The standard library has some instances of this (for instance the Interface 'Certificate' and the abstract Class 'Certificate').
|
resolved fixed
|
5105ba9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-30T14:15:35Z | 2002-02-12T05:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/JavaCompletionProposal.java
|
package org.eclipse.jdt.internal.ui.text.java;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.contentassist.ICompletionProposalExtension;
import org.eclipse.jface.text.contentassist.IContextInformation;
import org.eclipse.jface.util.Assert;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.internal.corext.codemanipulation.ImportsStructure;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.preferences.ImportOrganizePreferencePage;
public class JavaCompletionProposal implements IJavaCompletionProposal, ICompletionProposalExtension {
private String fDisplayString;
private String fReplacementString;
private int fReplacementOffset;
private int fReplacementLength;
private int fCursorPosition;
private Image fImage;
private IContextInformation fContextInformation;
private int fContextInformationPosition;
private ProposalInfo fProposalInfo;
private IImportDeclaration fImportDeclaration;
private char[] fTriggerCharacters;
private int fRelevance;
/**
* Creates a new completion proposal. All fields are initialized based on the provided information.
*
* @param replacementString the actual string to be inserted into the document
* @param replacementOffset the offset of the text to be replaced
* @param replacementLength the length of the text to be replaced
* @param image the image to display for this proposal
* @param displayString the string to be displayed for the proposal
* If set to <code>null</code>, the replacement string will be taken as display string.
*/
public JavaCompletionProposal(String replacementString, int replacementOffset, int replacementLength, Image image, String displayString, int relevance) {
Assert.isNotNull(replacementString);
Assert.isTrue(replacementOffset >= 0);
Assert.isTrue(replacementLength >= 0);
fReplacementString= replacementString;
fReplacementOffset= replacementOffset;
fReplacementLength= replacementLength;
fImage= image;
fDisplayString= displayString != null ? displayString : replacementString;
fRelevance= relevance;
fCursorPosition= replacementString.length();
fContextInformation= null;
fContextInformationPosition= -1;
fImportDeclaration= null;
fTriggerCharacters= null;
fProposalInfo= null;
}
/**
* Sets the context information.
* @param contentInformation The context information associated with this proposal
*/
public void setContextInformation(IContextInformation contextInformation) {
fContextInformation= contextInformation;
fContextInformationPosition= (fContextInformation != null ? fCursorPosition : -1);
}
/**
* Sets the import declaration to import when applied.
* @param importDeclaration Optional import declaration to be added. Can be <code>null</code>. The underlying compilation unit
* is assumed to be compatible with the document passed in <code>apply</code>.
*/
public void setImportDeclaration(IImportDeclaration importDeclaration) {
fImportDeclaration= importDeclaration;
}
/**
* Sets the trigger characters.
* @param triggerCharacters The set of characters which can trigger the application of this completion proposal
*/
public void setTriggerCharacters(char[] triggerCharacters) {
fTriggerCharacters= triggerCharacters;
}
/**
* Sets the proposal info.
* @param additionalProposalInfo The additional information associated with this proposal or <code>null</code>
*/
public void setProposalInfo(ProposalInfo proposalInfo) {
fProposalInfo= proposalInfo;
}
/**
* Sets the cursor position relative to the insertion offset. By default this is the length of the completion string
* (Cursor positioned after the completion)
* @param cursorPosition The cursorPosition to set
*/
public void setCursorPosition(int cursorPosition) {
Assert.isTrue(cursorPosition >= 0);
fCursorPosition= cursorPosition;
fContextInformationPosition= (fContextInformation != null ? fCursorPosition : -1);
}
protected void applyImports(IDocument document) {
if (fImportDeclaration == null) {
return;
}
ICompilationUnit cu= (ICompilationUnit) fImportDeclaration.getAncestor(IJavaElement.COMPILATION_UNIT);
if (cu != null) {
try {
IType[] types= cu.getTypes();
if (types.length == 0 || types[0].getSourceRange().getOffset() > fReplacementOffset) {
// do not add import for code assist on import statements
return;
}
String[] prefOrder= ImportOrganizePreferencePage.getImportOrderPreference();
int threshold= ImportOrganizePreferencePage.getImportNumberThreshold();
ImportsStructure impStructure= new ImportsStructure(cu, prefOrder, threshold, true);
impStructure.addImport(fImportDeclaration.getElementName());
// will modify the document as the CU works on the document
impStructure.create(false, null);
} catch (CoreException e) {
JavaPlugin.log(e);
}
}
}
/*
* @see ICompletionProposalExtension#apply(IDocument, char, int)
*/
public void apply(IDocument document, char trigger, int offset) {
try {
// patch replacement length
int delta= offset - (fReplacementOffset + fReplacementLength);
if (delta > 0)
fReplacementLength += delta;
if (trigger == (char) 0) {
replace(document, fReplacementOffset, fReplacementLength, fReplacementString);
} else {
StringBuffer buffer= new StringBuffer(fReplacementString);
// fix for PR #5533. Assumes that no eating takes place.
if ((fCursorPosition > 0 && fCursorPosition <= buffer.length() && buffer.charAt(fCursorPosition - 1) != trigger)) {
buffer.insert(fCursorPosition, trigger);
++fCursorPosition;
}
replace(document, fReplacementOffset, fReplacementLength, buffer.toString());
}
int oldLen= document.getLength();
applyImports(document);
fReplacementOffset += document.getLength() - oldLen;
} catch (BadLocationException x) {
// ignore
}
}
// #6410 - File unchanged but dirtied by code assist
private void replace(IDocument document, int offset, int length, String string) throws BadLocationException {
if (!document.get(offset, length).equals(string))
document.replace(offset, length, string);
}
/*
* @see ICompletionProposal#apply
*/
public void apply(IDocument document) {
apply(document, (char) 0, fReplacementOffset + fReplacementLength);
}
/*
* @see ICompletionProposal#getSelection
*/
public Point getSelection(IDocument document) {
return new Point(fReplacementOffset + fCursorPosition, 0);
}
/*
* @see ICompletionProposal#getContextInformation()
*/
public IContextInformation getContextInformation() {
return fContextInformation;
}
/*
* @see ICompletionProposal#getImage()
*/
public Image getImage() {
return fImage;
}
/*
* @see ICompletionProposal#getDisplayString()
*/
public String getDisplayString() {
return fDisplayString;
}
/*
* @see ICompletionProposal#getAdditionalProposalInfo()
*/
public String getAdditionalProposalInfo() {
if (fProposalInfo != null) {
return fProposalInfo.getInfo();
}
return null;
}
/*
* @see ICompletionProposalExtension#getTriggerCharacters()
*/
public char[] getTriggerCharacters() {
return fTriggerCharacters;
}
/*
* @see ICompletionProposalExtension#getContextInformationPosition()
*/
public int getContextInformationPosition() {
return fReplacementOffset + fContextInformationPosition;
}
/**
* Gets the replacement offset.
* @return Returns a int
*/
public int getReplacementOffset() {
return fReplacementOffset;
}
/**
* Sets the replacement offset.
* @param replacementOffset The replacement offset to set
*/
public void setReplacementOffset(int replacementOffset) {
Assert.isTrue(replacementOffset >= 0);
fReplacementOffset= replacementOffset;
}
/**
* Gets the replacement length.
* @return Returns a int
*/
public int getReplacementLength() {
return fReplacementLength;
}
/**
* Sets the replacement length.
* @param replacementLength The replacementLength to set
*/
public void setReplacementLength(int replacementLength) {
Assert.isTrue(replacementLength >= 0);
fReplacementLength= replacementLength;
}
/**
* Gets the replacement string.
* @return Returns a String
*/
public String getReplacementString() {
return fReplacementString;
}
/**
* Sets the replacement string.
* @param replacementString The replacement string to set
*/
public void setReplacementString(String replacementString) {
fReplacementString= replacementString;
}
/**
* Sets the image.
* @param image The image to set
*/
public void setImage(Image image) {
fImage= image;
}
/*
* @see ICompletionProposalExtension#isValidFor(IDocument, int)
*/
public boolean isValidFor(IDocument document, int offset) {
if (offset < fReplacementOffset)
return false;
int replacementLength= fReplacementString == null ? 0 : fReplacementString.length();
if (offset > fReplacementOffset + replacementLength)
return false;
try {
int length= offset - fReplacementOffset;
String start= document.get(fReplacementOffset, length);
return fReplacementString.substring(0, length).equalsIgnoreCase(start);
} catch (BadLocationException x) {
}
return false;
}
/**
* Gets the proposal's relevance.
* @return Returns a int
*/
public int getRelevance() {
return fRelevance;
}
/**
* Sets the proposal's relevance.
* @param relevance The relevance to set
*/
public void setRelevance(int relevance) {
fRelevance= relevance;
}
}
|
9,440 |
Bug 9440 Duplicate non-qualified class names no handled by import generator
|
If I have two types: org.acme.goodstuff.MyType and org.acme.coolstuff.MyType and I use Code Completion (or something that invokes the smart import logic). The smart import stuff generates imports for both references to these types, ignoring the fact that one of them has to remain qualified in the code in order not to conflict with the other. You cannot have two import statements which resolve the same non-qualified type identifier. The standard library has some instances of this (for instance the Interface 'Certificate' and the abstract Class 'Certificate').
|
resolved fixed
|
5105ba9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-30T14:15:35Z | 2002-02-12T05:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/JavaTypeCompletionProposal.java
| |
9,440 |
Bug 9440 Duplicate non-qualified class names no handled by import generator
|
If I have two types: org.acme.goodstuff.MyType and org.acme.coolstuff.MyType and I use Code Completion (or something that invokes the smart import logic). The smart import stuff generates imports for both references to these types, ignoring the fact that one of them has to remain qualified in the code in order not to conflict with the other. You cannot have two import statements which resolve the same non-qualified type identifier. The standard library has some instances of this (for instance the Interface 'Certificate' and the abstract Class 'Certificate').
|
resolved fixed
|
5105ba9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-30T14:15:35Z | 2002-02-12T05:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/MethodStubCompletionProposal.java
|
package org.eclipse.jdt.internal.ui.text.java;
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.core.runtime.CoreException;
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.CodeFormatterUtil;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.corext.util.Strings;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
public class MethodStubCompletionProposal extends JavaCompletionProposal {
private String fTypeName;
private String fMethodName;
private String[] fParamTypes;
private ICompilationUnit fCompilationUnit;
private IJavaProject fJavaProject;
private ImportsStructure fImportStructure;
public MethodStubCompletionProposal(IJavaProject jproject, ICompilationUnit cu, String declaringTypeName, String methodName, String[] paramTypes, int start, int length, String displayName, String completionProposal) {
super(completionProposal, 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;
fCompilationUnit= cu; // can be null -> no imports
fImportStructure= null;
}
/*
* @see JavaCompletionProposal#applyImports(IDocument)
*/
protected void applyImports(IDocument document) {
if (fImportStructure != null) {
try {
fImportStructure.create(false, null);
} catch (CoreException e) {
JavaPlugin.log(e);
}
}
}
/*
* @see ICompletionProposalExtension#apply(IDocument, char)
*/
public void apply(IDocument document, char trigger, int offset) {
try {
fImportStructure= null;
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 (fCompilationUnit != null) {
fImportStructure= new ImportsStructure(fCompilationUnit, settings.importOrder, settings.importThreshold, true);
IJavaElement currElem= fCompilationUnit.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, fImportStructure);
// 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);
replacement= Strings.trimLeadingTabsAndSpaces(replacement);
setReplacementString(replacement);
setCursorPosition(replacement.length());
}
}
} catch (BadLocationException e) {
JavaPlugin.log(e);
} catch (CoreException e) {
JavaPlugin.log(e);
}
super.apply(document, trigger, offset);
}
}
|
9,440 |
Bug 9440 Duplicate non-qualified class names no handled by import generator
|
If I have two types: org.acme.goodstuff.MyType and org.acme.coolstuff.MyType and I use Code Completion (or something that invokes the smart import logic). The smart import stuff generates imports for both references to these types, ignoring the fact that one of them has to remain qualified in the code in order not to conflict with the other. You cannot have two import statements which resolve the same non-qualified type identifier. The standard library has some instances of this (for instance the Interface 'Certificate' and the abstract Class 'Certificate').
|
resolved fixed
|
5105ba9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-30T14:15:35Z | 2002-02-12T05:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/ResultCollector.java
|
package org.eclipse.jdt.internal.ui.text.java;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import java.util.ArrayList;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jdt.core.CompletionRequestorAdapter;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.ui.JavaElementImageDescriptor;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.viewsupport.ImageDescriptorRegistry;
/**
* Bin to collect the proposal of the infrastructure on code assist in a java text.
*/
public class ResultCollector extends CompletionRequestorAdapter {
private final static char[] METHOD_WITH_ARGUMENTS_TRIGGERS= new char[] { '(', '-', ' ' };
private final static char[] METHOD_TRIGGERS= new char[] { ';', ',', '.', '\t', '[', ' ' };
private final static char[] TYPE_TRIGGERS= new char[] { '.', '\t', '[', '(', ' ' };
private final static char[] VAR_TRIGGER= new char[] { '\t', ' ', '=', ';' };
private ArrayList fFields= new ArrayList(), fKeywords= new ArrayList(10),
fLabels= new ArrayList(10), fMethods= new ArrayList(),
fModifiers= new ArrayList(10), fPackages= new ArrayList(),
fTypes= new ArrayList(), fVariables= new ArrayList();
private IProblem fLastProblem;
private IJavaProject fJavaProject;
private ICompilationUnit fCompilationUnit; // set when imports can be added
private int fCodeAssistOffset;
private ImageDescriptorRegistry fRegistry= JavaPlugin.getImageDescriptorRegistry();
private ArrayList[] fResults = new ArrayList[] {
fPackages, fLabels, fModifiers, fKeywords, fTypes, fMethods, fFields, fVariables
};
private int fUserReplacementLength;
/*
* Is eating code assist enabled or disabled? PR #3666
* When eating is enabled, JavaCompletionProposal must be revisited: PR #5533
*/
private boolean fPreventEating= true;
/*
* @see ICompletionRequestor#acceptClass
*/
public void acceptClass(char[] packageName, char[] typeName, char[] completionName, int modifiers, int start, int end, int relevance) {
ImageDescriptor descriptor= JavaPluginImages.DESC_OBJS_CLASS;
if (Flags.isDeprecated(modifiers))
descriptor= getDeprecatedDescriptor(descriptor);
ProposalInfo info= new ProposalInfo(fJavaProject, packageName, typeName);
fTypes.add(createTypeCompletion(start, end, new String(completionName), descriptor, new String(typeName), new String(packageName), info, relevance));
}
/*
* @see ICompletionRequestor#acceptError
*/
public void acceptError(IProblem error) {
fLastProblem= error;
}
/*
* @see ICompletionRequestor#acceptField
*/
public void acceptField(
char[] declaringTypePackageName, char[] declaringTypeName, char[] name,
char[] typePackageName, char[] typeName, char[] completionName,
int modifiers, int start, int end, int relevance) {
ImageDescriptor descriptor= getMemberDescriptor(modifiers);
StringBuffer nameBuffer= new StringBuffer();
nameBuffer.append(name);
if (typeName.length > 0) {
nameBuffer.append(" "); //$NON-NLS-1$
nameBuffer.append(typeName);
}
if (declaringTypeName != null && declaringTypeName.length > 0) {
nameBuffer.append(" - "); //$NON-NLS-1$
nameBuffer.append(declaringTypeName);
}
JavaCompletionProposal proposal= createCompletion(start, end, new String(completionName), descriptor, nameBuffer.toString(), relevance);
proposal.setProposalInfo(new ProposalInfo(fJavaProject, declaringTypePackageName, declaringTypeName, name));
proposal.setTriggerCharacters(VAR_TRIGGER);
fFields.add(proposal);
}
/*
* @see ICompletionRequestor#acceptInterface
*/
public void acceptInterface(char[] packageName, char[] typeName, char[] completionName, int modifiers, int start, int end, int relevance) {
ImageDescriptor descriptor= JavaPluginImages.DESC_OBJS_INTERFACE;
if (Flags.isDeprecated(modifiers))
descriptor= getDeprecatedDescriptor(descriptor);
ProposalInfo info= new ProposalInfo(fJavaProject, packageName, typeName);
fTypes.add(createTypeCompletion(start, end, new String(completionName), descriptor, new String(typeName), new String(packageName), info, relevance));
}
/*
* @see ICompletionRequestor#acceptAnonymousType
*/
public void acceptAnonymousType(char[] superTypePackageName, char[] superTypeName, char[][] parameterPackageNames, char[][] parameterTypeNames, char[][] parameterNames,
char[] completionName, int modifiers, int completionStart, int completionEnd, int relevance) {
JavaCompletionProposal proposal= createAnonymousTypeCompletion(superTypePackageName, superTypeName, parameterTypeNames, parameterNames, completionName, completionStart, completionEnd, relevance);
proposal.setProposalInfo(new ProposalInfo(fJavaProject, superTypePackageName, superTypeName));
fTypes.add(proposal);
}
/*
* @see ICompletionRequestor#acceptKeyword
*/
public void acceptKeyword(char[] keyword, int start, int end, int relevance) {
String kw= new String(keyword);
fKeywords.add(createCompletion(start, end, kw, null, kw, relevance));
}
/*
* @see ICompletionRequestor#acceptLabel
*/
public void acceptLabel(char[] labelName, int start, int end, int relevance) {
String ln= new String(labelName);
fLabels.add(createCompletion(start, end, ln, null, ln, relevance));
}
/*
* @see ICompletionRequestor#acceptLocalVariable
*/
public void acceptLocalVariable(char[] name, char[] typePackageName, char[] typeName, int modifiers, int start, int end, int relevance) {
StringBuffer buf= new StringBuffer();
buf.append(name);
if (typeName != null) {
buf.append(" "); //$NON-NLS-1$
buf.append(typeName);
}
JavaCompletionProposal proposal= createCompletion(start, end, new String(name), null, buf.toString(), relevance);
proposal.setTriggerCharacters(VAR_TRIGGER);
fVariables.add(proposal);
}
private String getParameterSignature(char[][] parameterTypeNames, char[][] parameterNames) {
StringBuffer buf = new StringBuffer();
if (parameterTypeNames != null) {
for (int i = 0; i < parameterTypeNames.length; i++) {
if (i > 0) {
buf.append(',');
buf.append(' ');
}
buf.append(parameterTypeNames[i]);
if (parameterNames != null && parameterNames[i] != null) {
buf.append(' ');
buf.append(parameterNames[i]);
}
}
}
return buf.toString();
}
/*
* @see ICompletionRequestor#acceptMethod
*/
public void acceptMethod(char[] declaringTypePackageName, char[] declaringTypeName, char[] name,
char[][] parameterPackageNames, char[][] parameterTypeNames, char[][] parameterNames,
char[] returnTypePackageName, char[] returnTypeName, char[] completionName, int modifiers,
int start, int end, int relevance) {
JavaCompletionProposal proposal= createMethodCallCompletion(declaringTypeName, name, parameterTypeNames, parameterNames, returnTypeName, completionName, modifiers, start, end, relevance);
proposal.setProposalInfo(new ProposalInfo(fJavaProject, declaringTypePackageName, declaringTypeName, name, parameterPackageNames, parameterTypeNames, returnTypeName.length == 0));
boolean hasOpeningBracket= completionName.length == 0 || (completionName.length > 0 && completionName[completionName.length - 1] == ')');
ProposalContextInformation contextInformation= null;
if (hasOpeningBracket && parameterTypeNames.length > 0) {
contextInformation= new ProposalContextInformation();
contextInformation.setInformationDisplayString(getParameterSignature(parameterTypeNames, parameterNames));
contextInformation.setContextDisplayString(proposal.getDisplayString());
contextInformation.setImage(proposal.getImage());
proposal.setContextInformation(contextInformation);
}
boolean userMustCompleteParameters= (contextInformation != null && completionName.length > 0);
char[] triggers= userMustCompleteParameters ? METHOD_WITH_ARGUMENTS_TRIGGERS : METHOD_TRIGGERS;
proposal.setTriggerCharacters(triggers);
if (userMustCompleteParameters) {
// set the cursor before the closing bracket
proposal.setCursorPosition(completionName.length - 1);
}
fMethods.add(proposal);
}
/*
* @see ICompletionRequestor#acceptModifier
*/
public void acceptModifier(char[] modifier, int start, int end, int relevance) {
String mod= new String(modifier);
fModifiers.add(createCompletion(start, end, mod, null, mod, relevance));
}
/*
* @see ICompletionRequestor#acceptPackage
*/
public void acceptPackage(char[] packageName, char[] completionName, int start, int end, int relevance) {
fPackages.add(createCompletion(start, end, new String(completionName), JavaPluginImages.DESC_OBJS_PACKAGE, new String(packageName), relevance));
}
/*
* @see ICompletionRequestor#acceptType
*/
public void acceptType(char[] packageName, char[] typeName, char[] completionName, int start, int end, int relevance) {
ProposalInfo info= new ProposalInfo(fJavaProject, packageName, typeName);
fTypes.add(createTypeCompletion(start, end, new String(completionName), JavaPluginImages.DESC_OBJS_CLASS, new String(typeName), new String(packageName), info, relevance));
}
/*
* @see ICodeCompletionRequestor#acceptMethodDeclaration
*/
public void acceptMethodDeclaration(char[] declaringTypePackageName, char[] declaringTypeName, char[] name, char[][] parameterPackageNames, char[][] parameterTypeNames, char[][] parameterNames, char[] returnTypePackageName, char[] returnTypeName, char[] completionName, int modifiers, int start, int end, int relevance) {
StringBuffer displayString= getMethodDisplayString(declaringTypeName, name, parameterTypeNames, parameterNames, returnTypeName);
StringBuffer typeName= new StringBuffer();
if (declaringTypePackageName.length > 0) {
typeName.append(declaringTypePackageName);
typeName.append('.');
}
typeName.append(declaringTypeName);
String[] paramTypes= new String[parameterTypeNames.length];
for (int i= 0; i < parameterTypeNames.length; i++) {
paramTypes[i]= Signature.createTypeSignature(parameterTypeNames[i], true);
}
JavaCompletionProposal proposal= new MethodStubCompletionProposal(fJavaProject, fCompilationUnit, typeName.toString(), new String(name), paramTypes, start, getLength(start, end), displayString.toString(), new String(completionName));
proposal.setImage(fRegistry.get(getMemberDescriptor(modifiers)));
proposal.setProposalInfo(new ProposalInfo(fJavaProject, declaringTypePackageName, declaringTypeName, name, parameterPackageNames, parameterTypeNames, returnTypeName.length == 0));
proposal.setRelevance(relevance);
fMethods.add(proposal);
}
/*
* @see ICodeCompletionRequestor#acceptVariableName
*/
public void acceptVariableName(char[] typePackageName, char[] typeName, char[] name, char[] completionName, int start, int end, int relevance) {
// XXX: To be revised
StringBuffer buf= new StringBuffer();
buf.append(name);
if (typeName != null && typeName.length > 0) {
buf.append(" - "); //$NON-NLS-1$
buf.append(typeName);
}
JavaCompletionProposal proposal= createCompletion(start, end, new String(completionName), null, buf.toString(), relevance);
proposal.setTriggerCharacters(VAR_TRIGGER);
fVariables.add(proposal);
}
public String getErrorMessage() {
if (fLastProblem != null)
return fLastProblem.getMessage();
return ""; //$NON-NLS-1$
}
public JavaCompletionProposal[] getResults() {
// return unsorted
int totLen= 0;
for (int i= 0; i < fResults.length; i++) {
totLen += fResults[i].size();
}
JavaCompletionProposal[] result= new JavaCompletionProposal[totLen];
int k= 0;
for (int i= 0; i < fResults.length; i++) {
ArrayList curr= fResults[i];
int currLen= curr.size();
for (int j= 0; j < currLen; j++) {
JavaCompletionProposal proposal= (JavaCompletionProposal) curr.get(j);
// for equal relevance, take categories
proposal.setRelevance(proposal.getRelevance() * 16 + i);
result[k++]= proposal;
}
}
return result;
}
private StringBuffer getMethodDisplayString(char[] declaringTypeName, char[] name, char[][] parameterTypeNames, char[][] parameterNames, char[] returnTypeName) {
StringBuffer nameBuffer= new StringBuffer();
nameBuffer.append(name);
nameBuffer.append('(');
if (parameterTypeNames != null && parameterTypeNames.length > 0) {
nameBuffer.append(getParameterSignature(parameterTypeNames, parameterNames));
}
nameBuffer.append(')');
if (returnTypeName != null && returnTypeName.length > 0) {
nameBuffer.append(" "); //$NON-NLS-1$
nameBuffer.append(returnTypeName);
}
if (declaringTypeName != null && declaringTypeName.length > 0) {
nameBuffer.append(" - "); //$NON-NLS-1$
nameBuffer.append(declaringTypeName);
}
return nameBuffer;
}
protected JavaCompletionProposal createMethodCallCompletion(char[] declaringTypeName, char[] name, char[][] parameterTypeNames, char[][] parameterNames, char[] returnTypeName, char[] completionName, int modifiers, int start, int end, int relevance) {
ImageDescriptor descriptor= getMemberDescriptor(modifiers);
StringBuffer nameBuffer= getMethodDisplayString(declaringTypeName, name, parameterTypeNames, parameterNames, returnTypeName);
return createCompletion(start, end, new String(completionName), descriptor, nameBuffer.toString(), relevance);
}
protected JavaCompletionProposal createAnonymousTypeCompletion(char[] declaringTypePackageName, char[] declaringTypeName, char[][] parameterTypeNames, char[][] parameterNames, char[] completionName, int start, int end, int relevance) {
StringBuffer declTypeBuf= new StringBuffer();
if (declaringTypePackageName.length > 0) {
declTypeBuf.append(declaringTypePackageName);
declTypeBuf.append('.');
}
declTypeBuf.append(declaringTypeName);
StringBuffer nameBuffer= new StringBuffer();
nameBuffer.append(declaringTypeName);
nameBuffer.append('(');
if (parameterTypeNames.length > 0) {
nameBuffer.append(getParameterSignature(parameterTypeNames, parameterNames));
}
nameBuffer.append(')');
nameBuffer.append(" "); //$NON-NLS-1$
nameBuffer.append(JavaTextMessages.getString("ResultCollector.anonymous_type")); //$NON-NLS-1$
int length= end - start;
return new AnonymousTypeCompletionProposal(fJavaProject, fCompilationUnit, start, length, new String(completionName), nameBuffer.toString(), declTypeBuf.toString(), relevance);
}
protected JavaCompletionProposal createTypeCompletion(int start, int end, String completion, ImageDescriptor descriptor, String typeName, String containerName, ProposalInfo proposalInfo, int relevance) {
IImportDeclaration importDeclaration= null;
if (containerName != null && fCompilationUnit != null) {
if (completion.equals(JavaModelUtil.concatenateName(containerName, typeName))) {
importDeclaration= fCompilationUnit.getImport(completion);
completion= typeName;
}
}
StringBuffer buf= new StringBuffer(typeName);
if (containerName != null) {
buf.append(" - "); //$NON-NLS-1$
if (containerName.length() > 0) {
buf.append(containerName);
} else {
buf.append(JavaTextMessages.getString("ResultCollector.default_package")); //$NON-NLS-1$
}
}
String name= buf.toString();
JavaCompletionProposal proposal= createCompletion(start, end, completion, descriptor, name, relevance);
proposal.setImportDeclaration(importDeclaration);
proposal.setProposalInfo(proposalInfo);
proposal.setTriggerCharacters(TYPE_TRIGGERS);
return proposal;
}
protected ImageDescriptor getMemberDescriptor(int modifiers) {
ImageDescriptor desc;
if (Flags.isPublic(modifiers)) {
desc= JavaPluginImages.DESC_MISC_PUBLIC;
} else if (Flags.isProtected(modifiers)) {
desc= JavaPluginImages.DESC_MISC_PROTECTED;
} else if (Flags.isPrivate(modifiers)) {
desc= JavaPluginImages.DESC_MISC_PRIVATE;
} else {
desc= JavaPluginImages.DESC_MISC_DEFAULT;
}
if (Flags.isDeprecated(modifiers))
return getDeprecatedDescriptor(desc);
return desc;
}
protected ImageDescriptor getDeprecatedDescriptor(ImageDescriptor descriptor) {
Point size= new Point(16, 16);
return new JavaElementImageDescriptor(descriptor, JavaElementImageDescriptor.WARNING, size);
}
protected JavaCompletionProposal createCompletion(int start, int end, String completion, ImageDescriptor descriptor, String name, int relevance) {
Image icon= (descriptor == null) ? null : fRegistry.get(descriptor);
return new JavaCompletionProposal(completion, start, getLength(start, end), icon, name, relevance);
}
private int getLength(int start, int end) {
int length;
if (fUserReplacementLength == -1) {
length= fPreventEating ? fCodeAssistOffset - start : end - start;
} else {
length= fUserReplacementLength;
// extend length to begin at start
if (start < fCodeAssistOffset) {
length+= fCodeAssistOffset - start;
}
}
return length;
}
/**
* Specifies the context of the code assist operation.
* @param codeAssistOffset The Offset on which the code assist will be called.
* Used to modify the offsets of the created proposals. ('Non Eating')
* @param jproject The Java project to which the underlying source belongs.
* Needed to find types referred.
* @param cu The compilation unit that is edited. Used to add import statements.
* Can be <code>null</code> if no import statements should be added.
*/
public void reset(int codeAssistOffset, IJavaProject jproject, ICompilationUnit cu) {
fJavaProject= jproject;
fCompilationUnit= cu;
fCodeAssistOffset= codeAssistOffset;
fUserReplacementLength= -1;
fLastProblem= null;
for (int i= 0; i < fResults.length; i++)
fResults[i].clear();
}
/**
* If the replacement length is set, it overrides the length returned from
* the content assist infrastructure.
* Use this setting if code assist is called with a none empty selection.
*/
public void setReplacementLength(int length) {
fUserReplacementLength= length;
}
/**
* If set, proposals created will not remove characters after the code assist position
* @param preventEating The preventEating to set
*/
public void setPreventEating(boolean preventEating) {
fPreventEating= preventEating;
}
}
|
14,898 |
Bug 14898 working set class cast exception
|
20020425 with plugin export .5 on Linux-Motif and W2k: 1) Edit an existing working set from package view. 2) Select and Unselect a project -> Finish button is enabled now. 3) Press Finish -> see result below ---8<--- java.lang.ClassCastException: java.lang.String at org.eclipse.jdt.internal.ui.packageview.PackageExplorerActionGroup$1.propertyCha nge(PackageExplorerActionGroup.java:299) at org.eclipse.jdt.internal.ui.workingsets.WorkingSetFilterActionGroup$2.propertyCh ange(WorkingSetFilterActionGroup.java:223) at org.eclipse.ui.internal.WorkingSet.firePropertyChange (WorkingSet.java:74) at org.eclipse.ui.internal.WorkingSet.setName(WorkingSet.java:214) at org.eclipse.ui.internal.dialogs.ResourceWorkingSetPage.finish (ResourceWorkingSetPage.java:189) at org.eclipse.ui.internal.dialogs.WorkingSetEditWizard.performFinish (WorkingSetEditWizard.java:78) at org.eclipse.jface.wizard.WizardDialog.finishPressed (WizardDialog.java:577) at org.eclipse.jface.wizard.WizardDialog.buttonPressed (WizardDialog.java:312) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:379) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:85) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:75) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:637) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1412) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1208) at org.eclipse.jface.window.Window.runEventLoop(Window.java:538) at org.eclipse.jface.window.Window.open(Window.java:525) at org.eclipse.ui.internal.dialogs.WorkingSetSelectionDialog.editSelectedWorkingSet (WorkingSetSelectionDialog.java:246) at org.eclipse.ui.internal.dialogs.WorkingSetSelectionDialog.access$1 (WorkingSetSelectionDialog.java:214) at org.eclipse.ui.internal.dialogs.WorkingSetSelectionDialog$2.widgetSelected (WorkingSetSelectionDialog.java:110) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:85) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:75) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:637) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1412) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1208) at org.eclipse.jface.window.Window.runEventLoop(Window.java:538) at org.eclipse.jface.window.Window.open(Window.java:525) at org.eclipse.ui.internal.dialogs.WorkingSetSelectionDialog.open (WorkingSetSelectionDialog.java:297) at org.eclipse.jdt.internal.ui.workingsets.SelectWorkingSetAction.run (SelectWorkingSetAction.java:66) at org.eclipse.jface.action.Action.runWithEvent(Action.java:590) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java:361) at org.eclipse.jface.action.ActionContributionItem.access$0 (ActionContributionItem.java:352) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java:47) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:75) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:637) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1412) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1208) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:842) at org.eclipse.ui.internal.Workbench.run(Workbench.java:825) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:643) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:349) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:160) at org.eclipse.core.launcher.Main.run(Main.java:548) at org.eclipse.core.launcher.Main.main(Main.java:403)
|
resolved fixed
|
18ba29a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-30T14:37:43Z | 2002-04-30T12:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/browsing/JavaBrowsingPart.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.browsing;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IAdaptable;
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.Transfer;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.graphics.Image;
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.Shell;
import org.eclipse.jface.action.Action;
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.text.ITextSelection;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.DecoratingLabelProvider;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ILabelDecorator;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.StructuredViewer;
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.ISelectionListener;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchPartSite;
import org.eclipse.ui.IWorkingSet;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.actions.NewWizardMenu;
import org.eclipse.ui.actions.OpenWithMenu;
import org.eclipse.ui.actions.RefreshAction;
import org.eclipse.ui.dialogs.PropertyDialogAction;
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.IMember;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.IWorkingCopy;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.IWorkingCopyManager;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.ui.JavaElementSorter;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.actions.CCPActionGroup;
import org.eclipse.jdt.ui.actions.GenerateActionGroup;
import org.eclipse.jdt.ui.actions.OpenAction;
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.ui.actions.ShowInNavigatorViewAction;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.actions.ContextMenuGroup;
import org.eclipse.jdt.internal.ui.actions.GenerateGroup;
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.packageview.BuildGroup;
import org.eclipse.jdt.internal.ui.packageview.PackagesMessages;
import org.eclipse.jdt.internal.ui.packageview.SelectionTransferDragAdapter;
import org.eclipse.jdt.internal.ui.packageview.SelectionTransferDropAdapter;
import org.eclipse.jdt.internal.ui.search.JavaSearchGroup;
import org.eclipse.jdt.internal.ui.util.JavaUIHelp;
import org.eclipse.jdt.internal.ui.viewsupport.BaseJavaElementContentProvider;
import org.eclipse.jdt.internal.ui.viewsupport.IProblemChangedListener;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
import org.eclipse.jdt.internal.ui.viewsupport.ProblemTableViewer;
import org.eclipse.jdt.internal.ui.viewsupport.StandardJavaUILabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater;
import org.eclipse.jdt.internal.ui.workingsets.WorkingSetFilter;
import org.eclipse.jdt.internal.ui.workingsets.WorkingSetFilterActionGroup;
abstract class JavaBrowsingPart extends ViewPart implements IMenuListener, ISelectionListener {
private ILabelProvider fLabelProvider;
private ILabelProvider fTitleProvider;
private StructuredViewer fViewer;
private IMemento fMemento;
private JavaElementTypeComparator fTypeComparator;
// Actions
private BuildGroup fBuildGroup;
private ContextMenuGroup[] fStandardGroups;
private CompositeActionGroup fStandardActionGroups;
private OpenAction fOpenAction;
private Action fOpenToAction;
private Action fShowNavigatorAction;
protected PropertyDialogAction fPropertyDialogAction;
private RefreshAction fRefreshAction;
private Menu fContextMenu;
private IWorkbenchPart fPreviousSelectionProvider;
private Object fPreviousSelectedElement;
private Image fOriginalTitleImage;
private WorkingSetFilterActionGroup fWorkingSetFilterActionGroup;
private CCPActionGroup fCCPActionGroup;
/*
* Ensure selection changed events being processed only if
* initiated by user interaction with this part.
*/
private boolean fProcessSelectionEvents= true;
private IPartListener fPartListener= new IPartListener() {
public void partActivated(IWorkbenchPart part) {
setSelectionFromEditor(part);
}
public void partBroughtToTop(IWorkbenchPart part) {
}
public void partClosed(IWorkbenchPart part) {
}
public void partDeactivated(IWorkbenchPart part) {
}
public void partOpened(IWorkbenchPart part) {
}
};
/*
* Implements method from IViewPart.
*/
public void init(IViewSite site, IMemento memento) throws PartInitException {
super.init(site, memento);
fMemento= memento;
}
/*
* Implements method from IViewPart.
*/
public void saveState(IMemento memento) {
if (fViewer == null) {
// part has not been created
if (fMemento != null) //Keep the old state;
memento.putMemento(fMemento);
return;
}
fWorkingSetFilterActionGroup.saveState(memento);
}
protected void restoreState(IMemento memento) {
fWorkingSetFilterActionGroup.restoreState(memento);
}
/**
* Creates the search list inner viewer.
*/
public void createPartControl(Composite parent) {
Assert.isTrue(fViewer == null);
fTypeComparator= new JavaElementTypeComparator();
// Setup viewer
fViewer= createViewer(parent);
fLabelProvider= createLabelProvider();
ILabelDecorator decorationMgr= PlatformUI.getWorkbench().getDecoratorManager();
fViewer.setLabelProvider(new DecoratingLabelProvider(fLabelProvider, decorationMgr));
fViewer.setSorter(new JavaElementSorter());
fViewer.setUseHashlookup(true);
JavaPlugin.getDefault().getProblemMarkerManager().addListener((IProblemChangedListener)fViewer);
fTitleProvider= createTitleProvider();
MenuManager menuMgr= new MenuManager("#PopupMenu"); //$NON-NLS-1$
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(this);
fContextMenu= menuMgr.createContextMenu(fViewer.getControl());
fViewer.getControl().setMenu(fContextMenu);
getSite().registerContextMenu(menuMgr, fViewer);
getSite().setSelectionProvider(fViewer);
createActions(); // call before registering for selection changes
addKeyListener();
if (fMemento != null)
restoreState(fMemento);
fMemento= null;
getSite().setSelectionProvider(fViewer);
// Status line
IStatusLineManager slManager= getViewSite().getActionBars().getStatusLineManager();
fViewer.addSelectionChangedListener(new StatusBarUpdater(slManager));
hookViewerListeners();
// Filters
addFilters();
// Initialize viewer input
fViewer.setContentProvider(createContentProvider());
setInitialInput();
initDragAndDrop();
// Initialize selecton
setInitialSelection();
// Listen to workbench window changes
getViewSite().getWorkbenchWindow().getSelectionService().addSelectionListener(this);
getViewSite().getPage().addPartListener(fPartListener);
fillActionBars();
setHelp();
}
private void initDragAndDrop() {
int ops= DND.DROP_COPY | DND.DROP_MOVE;
Transfer[] transfers= new Transfer[] {
LocalSelectionTransfer.getInstance(),
ResourceTransfer.getInstance()};
// Drop Adapter
TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] {
new SelectionTransferDropAdapter(fViewer)
};
fViewer.addDropSupport(ops, transfers, new DelegatingDropAdapter(dropListeners));
// Drag Adapter
Control control= fViewer.getControl();
TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] {
new SelectionTransferDragAdapter(fViewer),
new ResourceTransferDragAdapter(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)getSelectionProvider().getSelection();
for (Iterator iter= selection.iterator(); iter.hasNext(); ) {
if (iter.next() instanceof IMember) {
setPossibleListeners(new TransferDragSourceListener[] {new SelectionTransferDragAdapter(fViewer)});
break;
}
}
super.dragStart(event);
}
});
}
protected void fillActionBars() {
IActionBars actionBars= getViewSite().getActionBars();
IToolBarManager toolBar= actionBars.getToolBarManager();
fillToolBar(toolBar);
fWorkingSetFilterActionGroup.fillActionBars(getViewSite().getActionBars());
actionBars.updateActionBars();
// IMenuManager menu= actionBars.getMenuManager();
// menu.add(fFilterAction);
// menu.add(fShowLibrariesAction);
//menu.add(fShowBinariesAction);
// menu.add(fFilterWorkingSetAction);
// menu.add(fRemoveWorkingSetAction);
//
// menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
// menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS+"-end"));//$NON-NLS-1$
fStandardActionGroups.fillActionBars(actionBars);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.REFRESH, fRefreshAction);
// actionBars.setGlobalActionHandler(IWorkbenchActionConstants.BOOKMARK, fAddBookmarkAction);
fBuildGroup.fillActionBars(actionBars);
}
//---- IWorkbenchPart ------------------------------------------------------
public void setFocus() {
fViewer.getControl().setFocus();
}
public void dispose() {
if (fViewer != null) {
JavaPlugin.getDefault().getProblemMarkerManager().removeListener((IProblemChangedListener)fViewer);
getViewSite().getWorkbenchWindow().getSelectionService().removeSelectionListener(this);
getViewSite().getPage().removePartListener(fPartListener);
fViewer= null;
}
if (fStandardActionGroups != null)
fStandardActionGroups.dispose();
super.dispose();
}
/**
* Adds the KeyListener
*/
protected void addKeyListener() {
fViewer.getControl().addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent event) {
handleKeyReleased(event);
}
});
}
protected void handleKeyReleased(KeyEvent event) {
if (event.stateMask != 0)
return;
int key= event.keyCode;
if (key == SWT.F5) {
fRefreshAction.selectionChanged(
(IStructuredSelection) fViewer.getSelection());
if (fRefreshAction.isEnabled())
fRefreshAction.run();
} if (event.character == SWT.DEL) {
if (fCCPActionGroup.getDeleteAction().isEnabled())
fCCPActionGroup.getDeleteAction().run();
}
}
//---- Adding Action to Toolbar -------------------------------------------
protected void fillToolBar(IToolBarManager tbm) {
}
/**
* 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);
IStructuredSelection selection= (IStructuredSelection) fViewer.getSelection();
int size= selection.size();
fPropertyDialogAction.selectionChanged(selection);
MenuManager newMenu= new MenuManager(PackagesMessages.getString("PackageExplorer.new")); //$NON-NLS-1$
menu.appendToGroup(IContextMenuConstants.GROUP_NEW, newMenu);
new NewWizardMenu(newMenu, getSite().getWorkbenchWindow(), false);
// Open menus
fOpenAction.update();
if (fOpenAction.isEnabled())
menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, fOpenAction);
addOpenWithMenu(menu, selection);
if (size == 1)
addOpenNewWindowAction(menu, selection.getFirstElement());
ContextMenuGroup.add(menu, fStandardGroups, fViewer);
menu.appendToGroup(IContextMenuConstants.GROUP_BUILD, fRefreshAction);
fRefreshAction.selectionChanged(selection);
// XXX workaround until we have fully converted the code to use the new action groups
fStandardActionGroups.get(2).fillContextMenu(menu);
fStandardActionGroups.get(3).fillContextMenu(menu);
fStandardActionGroups.get(4).fillContextMenu(menu);
menu.add(new Separator());
if (fPropertyDialogAction.isApplicableForSelection())
menu.appendToGroup(IContextMenuConstants.GROUP_PROPERTIES, fPropertyDialogAction);
}
private void addOpenNewWindowAction(IMenuManager menu, Object element) {
if (element instanceof IJavaElement) {
try {
element= ((IJavaElement)element).getCorrespondingResource();
} catch(JavaModelException e) {
}
}
if (!(element instanceof IContainer))
return;
menu.appendToGroup(
IContextMenuConstants.GROUP_OPEN,
new PatchedOpenInNewWindowAction(getSite().getWorkbenchWindow(), (IContainer)element));
}
private void createActions() {
ISelectionProvider provider= getSelectionProvider();
fOpenAction= new OpenAction(getViewSite());
fPropertyDialogAction= new PropertyDialogAction(getShell(), provider);
fShowNavigatorAction= new ShowInNavigatorViewAction(getViewSite());
fBuildGroup= new BuildGroup(this, true);
fStandardGroups= new ContextMenuGroup[] {
fBuildGroup,
new GenerateGroup(),
new JavaSearchGroup()
};
fStandardActionGroups= new CompositeActionGroup(new ActionGroup[] {
new OpenEditorActionGroup(this),
new OpenViewActionGroup(this),
new ShowActionGroup(this),
fCCPActionGroup= new CCPActionGroup(this),
new RefactorActionGroup(this),
new GenerateActionGroup(this)});
fRefreshAction= new RefreshAction(getShell());
String viewId= getConfigurationElement().getAttribute("id"); //$NON-NLS-1$
Assert.isNotNull(viewId);
IPropertyChangeListener titleUpdater= new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
String property= event.getProperty();
if (IWorkbenchPage.CHANGE_WORKING_SET_REPLACE.equals(property))
updateTitle();
else if (IWorkingSet.CHANGE_WORKING_SET_NAME_CHANGE.equals(property))
updateTitle();
}
};
fWorkingSetFilterActionGroup= new WorkingSetFilterActionGroup(fViewer, viewId, getShell(), titleUpdater);
}
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;
IAdaptable element= (IAdaptable)selection.getFirstElement();
Object resource= element.getAdapter(IResource.class);
if (!(resource instanceof IFile))
return;
// Create a menu flyout.
MenuManager submenu= new MenuManager(PackagesMessages.getString("PackageExplorer.openWith")); //$NON-NLS-1$
submenu.add(new OpenWithMenu(getSite().getPage(), (IFile) resource));
// Add the submenu.
menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, submenu);
}
/**
* Returns the shell to use for opening dialogs.
* Used in this class, and in the actions.
*/
private Shell getShell() {
return fViewer.getControl().getShell();
}
protected final Display getDisplay() {
return fViewer.getControl().getDisplay();
}
/**
* Returns the selection provider.
*/
ISelectionProvider getSelectionProvider() {
return fViewer;
}
/**
* Answers if the given <code>element</code> is a valid
* input for this part.
*
* @param element the object to test
* @return <true> if the given element is a valid input
*/
abstract protected boolean isValidInput(Object element);
/**
* Answers if the given <code>element</code> is a valid
* element for this part.
*
* @param element the object to test
* @return <true> if the given element is a valid element
*/
protected boolean isValidElement(Object element) {
if (element == null)
return false;
element= getSuitableJavaElement(element);
if (element == null)
return false;
Object input= getViewer().getInput();
if (input == null)
return false;
if (input instanceof Collection)
return ((Collection)input).contains(element);
else
return input.equals(element);
}
private boolean isInputResetBy(Object newInput, Object input, IWorkbenchPart part) {
if (newInput == null)
return part == fPreviousSelectionProvider;
if (input instanceof IJavaElement && newInput instanceof IJavaElement)
return getTypeComparator().compare(newInput, input) > 0;
else
return false;
}
private boolean isInputResetBy(IWorkbenchPart part) {
if (!(part instanceof JavaBrowsingPart))
return true;
Object thisInput= getViewer().getInput();
Object partInput= ((JavaBrowsingPart)part).getViewer().getInput();
if (thisInput instanceof IJavaElement && partInput instanceof IJavaElement)
return getTypeComparator().compare(partInput, thisInput) > 0;
else
return true;
}
protected boolean isAncestorOf(Object ancestor, Object element) {
if (element instanceof IJavaElement && ancestor instanceof IJavaElement)
return !element.equals(ancestor) && internalIsAncestorOf((IJavaElement)ancestor, (IJavaElement)element);
return false;
}
private boolean internalIsAncestorOf(IJavaElement ancestor, IJavaElement element) {
if (element != null)
return element.equals(ancestor) || internalIsAncestorOf(ancestor, element.getParent());
else
return false;
}
public void selectionChanged(IWorkbenchPart part, ISelection selection) {
if (!fProcessSelectionEvents || part == this || !(selection instanceof IStructuredSelection))
return;
// Set selection
Object selectedElement= getSingleElementFromSelection(selection);
if (selectedElement != null && part.equals(fPreviousSelectionProvider) && selectedElement.equals(fPreviousSelectedElement))
return;
fPreviousSelectedElement= selectedElement;
Object currentInput= (IJavaElement)getViewer().getInput();
if (selectedElement != null && selectedElement.equals(currentInput)) {
IJavaElement elementToSelect= findElementToSelect(getSingleElementFromSelection(selection));
if (elementToSelect != null && getTypeComparator().compare(selectedElement, elementToSelect) < 0)
setSelection(new StructuredSelection(elementToSelect), true);
fPreviousSelectionProvider= part;
return;
}
// Clear input if needed
if (part != fPreviousSelectionProvider && selectedElement != null && !selectedElement.equals(currentInput) && isInputResetBy(selectedElement, currentInput, part)) {
if (!isAncestorOf(selectedElement, currentInput))
setInput(null);
fPreviousSelectionProvider= part;
return;
} else if (selection.isEmpty() && !isInputResetBy(part)) {
fPreviousSelectionProvider= part;
return;
} else if (selectedElement == null && part == fPreviousSelectionProvider) {
setInput(null);
fPreviousSelectionProvider= part;
return;
}
fPreviousSelectionProvider= part;
// Adjust input and set selection and
if (selectedElement instanceof IJavaElement)
adjustInputAndSetSelection((IJavaElement)selectedElement);
else
setSelection(StructuredSelection.EMPTY, true);
}
protected void setInput(Object input) {
if (input == null)
setTitleImage(fOriginalTitleImage);
else if (input instanceof Collection) {
if (((Collection)input).isEmpty())
setTitleImage(fOriginalTitleImage);
else {
Object firstElement= ((Collection)input).iterator().next();
setTitleImage(fTitleProvider.getImage(firstElement));
}
} else
setTitleImage(fTitleProvider.getImage(input));
setViewerInput(input);
updateTitle();
}
private void setViewerInput(Object input) {
fProcessSelectionEvents= false;
fViewer.setInput(input);
fProcessSelectionEvents= true;
}
void updateTitle() {
setTitleToolTip(getToolTipText(fViewer.getInput()));
}
/**
* Returns the tool tip text for the given element.
*/
String getToolTipText(Object element) {
String result;
if (!(element instanceof IResource)) {
result= JavaElementLabels.getTextLabel(element, StandardJavaUILabelProvider.DEFAULT_TEXTFLAGS);
} else {
IPath path= ((IResource) element).getFullPath();
if (path.isRoot()) {
result= getConfigurationElement().getAttribute("name"); //$NON-NLS-1$
} else {
result= path.makeRelative().toString();
}
}
if (fWorkingSetFilterActionGroup == null || fWorkingSetFilterActionGroup.getWorkingSet() == null)
return result;
IWorkingSet ws= fWorkingSetFilterActionGroup.getWorkingSet();
String wsstr= JavaBrowsingMessages.getFormattedString("JavaBrowsingPart.toolTip", new String[] { ws.getName() }); //$NON-NLS-1$
if (result.length() == 0)
return wsstr;
return JavaBrowsingMessages.getFormattedString("JavaBrowsingPart.toolTip2", new String[] { result, ws.getName() }); //$NON-NLS-1$
}
public String getTitleToolTip() {
if (fViewer == null)
return super.getTitleToolTip();
return getToolTipText(fViewer.getInput());
}
/**
* Sets or clears the title image of this part and
* store the orignal image on the first call.
*/
protected void setTitleImage(Image titleImage) {
if (fOriginalTitleImage == null)
fOriginalTitleImage= getTitleImage();
if (titleImage == null)
titleImage= fOriginalTitleImage;
super.setTitleImage(titleImage);
}
protected final StructuredViewer getViewer() {
return fViewer;
}
protected ILabelProvider createLabelProvider() {
return new StandardJavaUILabelProvider(
StandardJavaUILabelProvider.DEFAULT_TEXTFLAGS,
StandardJavaUILabelProvider.DEFAULT_IMAGEFLAGS | JavaElementImageProvider.SMALL_ICONS,
StandardJavaUILabelProvider.getAdornmentProviders(true, null)
);
}
protected ILabelProvider createTitleProvider() {
return new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_BASICS | JavaElementLabelProvider.SHOW_SMALL_ICONS);
}
protected final ILabelProvider getLabelProvider() {
return fLabelProvider;
}
protected final ILabelProvider getTitleProvider() {
return fTitleProvider;
}
/**
* Creates the the viewer of this part.
*
* @param parent the parent for the viewer
*/
protected StructuredViewer createViewer(Composite parent) {
return new ProblemTableViewer(parent, SWT.MULTI);
}
protected int getLabelProviderFlags() {
return JavaElementLabelProvider.SHOW_BASICS | JavaElementLabelProvider.SHOW_OVERLAY_ICONS |
JavaElementLabelProvider.SHOW_SMALL_ICONS | JavaElementLabelProvider.SHOW_VARIABLE | JavaElementLabelProvider.SHOW_PARAMETERS;
}
/**
* Adds filters the viewer of this part.
*/
protected void addFilters() {
// default is to have no filters
}
/**
* Creates the the content provider of this part.
*/
protected BaseJavaElementContentProvider createContentProvider() {
return new JavaElementContentProvider(true, this); //
}
protected void setInitialInput() {
// Use the selection, if any
ISelection selection= getSite().getPage().getSelection();
Object input= getSingleElementFromSelection(selection);
if (!(input instanceof IJavaElement)) {
// Use the input of the page
input= getSite().getPage().getInput();
if (!(input instanceof IJavaElement) && input instanceof IAdaptable)
input= ((IAdaptable)input).getAdapter(IJavaElement.class);
}
setInput(findInputForJavaElement((IJavaElement)input));
}
protected void setInitialSelection() {
// Use the selection, if any
Object input;
ISelection selection= getSite().getPage().getSelection();
if (selection != null && !selection.isEmpty())
input= getSingleElementFromSelection(selection);
else {
// Use the input of the page
input= getSite().getPage().getInput();
if (!(input instanceof IJavaElement)) {
if (input instanceof IAdaptable)
input= ((IAdaptable)input).getAdapter(IJavaElement.class);
else
return;
}
}
if (findElementToSelect((IJavaElement)input) != null)
adjustInputAndSetSelection((IJavaElement)input);
}
final protected void setHelp() {
JavaUIHelp.setHelp(fViewer, getHelpContextId());
}
/**
* Returns the context ID for the Help system
*
* @return the string used as ID for the Help context
*/
abstract protected String getHelpContextId();
/**
* Adds additional listeners to this view.
*/
protected void hookViewerListeners() {
fViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
if (!fProcessSelectionEvents)
return;
if (JavaBrowsingPreferencePage.openEditorOnSingleClick())
new ShowInEditorAction().run(event.getSelection(), getSite().getPage());
else if (JavaBrowsingPart.this.equals(getSite().getPage().getActivePart()))
linkToEditor((IStructuredSelection)event.getSelection());
}
});
fViewer.addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
if (fProcessSelectionEvents && !JavaBrowsingPreferencePage.openEditorOnSingleClick())
new ShowInEditorAction().run(event.getSelection(), getSite().getPage());
}
});
}
void adjustInputAndSetSelection(IJavaElement je) {
je= getSuitableJavaElement(je);
IJavaElement elementToSelect= findElementToSelect(je);
IJavaElement newInput= findInputForJavaElement(je);
if (elementToSelect == null && !isValidInput(newInput))
// Clear input
setInput(null);
else if (elementToSelect == null || getViewer().testFindItem(elementToSelect) == null)
// Adjust input to selection
setInput(findInputForJavaElement(je));
if (elementToSelect != null)
setSelection(new StructuredSelection(elementToSelect), true);
else
setSelection(StructuredSelection.EMPTY, true);
}
/**
* Finds the closest Java element which can be used as input for
* this part and has the given Java element as child
*
* @param je the Java element for which to search the closest input
* @return the closest Java element used as input for this part
*/
protected IJavaElement findInputForJavaElement(IJavaElement je) {
if (je == null || !je.exists())
return null;
if (isValidInput(je))
return je;
return findInputForJavaElement(je.getParent());
}
final protected IJavaElement findElementToSelect(Object obj) {
if (obj instanceof IJavaElement)
return findElementToSelect((IJavaElement)obj);
return null;
}
/**
* Finds the element which has to be selected in this part.
*
* @param je the Java element which has the focus
*/
abstract protected IJavaElement findElementToSelect(IJavaElement je);
private Object getSingleElementFromSelection(ISelection selection) {
if (!(selection instanceof StructuredSelection) || selection.isEmpty())
return null;
Iterator iter= ((StructuredSelection)selection).iterator();
Object firstElement= iter.next();
if (!(firstElement instanceof IJavaElement)) {
if (firstElement instanceof IAdaptable)
return (IJavaElement)((IAdaptable)firstElement).getAdapter(IJavaElement.class);
else
return firstElement;
}
Object currentInput= (IJavaElement)getViewer().getInput();
if (currentInput == null || !currentInput.equals(findInputForJavaElement((IJavaElement)firstElement)))
if (iter.hasNext())
// multi selection and view is empty
return null;
else
// ok: single selection and view is empty
return firstElement;
// be nice to multi selection
while (iter.hasNext()) {
Object element= iter.next();
if (!(element instanceof IJavaElement))
return null;
if (!currentInput.equals(findInputForJavaElement((IJavaElement)element)))
return null;
}
return firstElement;
}
/**
* Gets the typeComparator.
* @return Returns a JavaElementTypeComparator
*/
protected Comparator getTypeComparator() {
return fTypeComparator;
}
/**
* Links to editor (if option enabled)
*/
private void linkToEditor(IStructuredSelection selection) {
if (selection == null || selection.isEmpty())
return;
Object obj= selection.getFirstElement();
Object element= null;
if (selection.size() == 1) {
if (obj instanceof IJavaElement) {
IJavaElement cu= ((IJavaElement)obj).getAncestor(IJavaElement.COMPILATION_UNIT);
if (cu != null)
element= getResourceFor(cu);
if (element == null)
element= ((IJavaElement)obj).getAncestor(IJavaElement.CLASS_FILE);
}
else if (obj instanceof IFile)
element= obj;
if (element == null)
return;
IWorkbenchPage page= getSite().getPage();
IEditorPart editorArray[]= page.getEditors();
for (int i= 0; i < editorArray.length; ++i) {
IEditorPart editor= editorArray[i];
Object input= getElementOfInput(editor.getEditorInput());
if (input != null && input.equals(element)) {
page.bringToTop(editor);
if (obj instanceof IJavaElement)
EditorUtility.revealInEditor(editor, (IJavaElement) obj);
return;
}
}
}
}
private void setSelectionFromEditor(IWorkbenchPart part) {
if (part == null)
return;
IWorkbenchPartSite site= part.getSite();
if (site == null)
return;
ISelectionProvider provider= site.getSelectionProvider();
if (provider != null)
setSelectionFromEditor(part, provider.getSelection());
}
private void setSelectionFromEditor(IWorkbenchPart part, ISelection selection) {
if (part instanceof IEditorPart && JavaBrowsingPreferencePage.linkViewSelectionToEditor()) {
IEditorInput ei= ((IEditorPart)part).getEditorInput();
if (selection instanceof ITextSelection) {
int offset= ((ITextSelection)selection).getOffset();
IJavaElement element= getElementForInputAt(ei, offset);
if (element != null) {
adjustInputAndSetSelection(element);
return;
}
}
if (ei instanceof IFileEditorInput) {
IFile file= ((IFileEditorInput)ei).getFile();
IJavaElement je= (IJavaElement)file.getAdapter(IJavaElement.class);
if (je == null) {
setSelection(null, false);
return;
}
adjustInputAndSetSelection(je);
} else if (ei instanceof IClassFileEditorInput) {
IClassFile cf= ((IClassFileEditorInput)ei).getClassFile();
adjustInputAndSetSelection(cf);
}
return;
}
}
/**
* 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;
}
private IResource getResourceFor(Object element) {
if (element instanceof IJavaElement) {
if (element instanceof IWorkingCopy) {
IWorkingCopy wc= (IWorkingCopy)element;
IJavaElement original= wc.getOriginalElement();
if (original != null)
element= original;
}
try {
element= ((IJavaElement)element).getUnderlyingResource();
} catch (JavaModelException e) {
return null;
}
}
if (!(element instanceof IResource) || ((IResource)element).isPhantom()) {
return null;
}
return (IResource)element;
}
private void setSelection(ISelection selection, boolean reveal) {
if (selection != null && selection.equals(fViewer.getSelection()))
return;
fProcessSelectionEvents= false;
fViewer.setSelection(selection, reveal);
fProcessSelectionEvents= true;
}
/**
* Tries to find the given element in a workingcopy.
*/
protected static IJavaElement getWorkingCopy(IJavaElement input) {
try {
if (input instanceof ICompilationUnit)
return EditorUtility.getWorkingCopy((ICompilationUnit)input);
else
return EditorUtility.getWorkingCopy(input, false);
} catch (JavaModelException ex) {
}
return null;
}
/**
* Returns the original element from which the specified working copy
* element was created from. This is a handle only method, the
* returned element may or may not exist.
*
* @param workingCopy the element for which to get the original
* @return the original Java element or <code>null</code> if this is not a working copy element
*/
protected static IJavaElement getOriginal(IJavaElement workingCopy) {
ICompilationUnit cu= getCompilationUnit(workingCopy);
if (cu != null)
return ((IWorkingCopy)cu).getOriginal(workingCopy);
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
*/
protected static ICompilationUnit getCompilationUnit(IJavaElement element) {
if (element == null)
return null;
if (element instanceof IMember)
return ((IMember) element).getCompilationUnit();
int type= element.getElementType();
if (IJavaElement.COMPILATION_UNIT == type)
return (ICompilationUnit) element;
if (IJavaElement.CLASS_FILE == type)
return null;
return getCompilationUnit(element.getParent());
}
/**
* Converts the given Java element to one which is suitable for this
* view. It takes into account wether the view shows working copies or not.
*
* @param element the Java element to be converted
* @return an element suitable for this view
*/
protected IJavaElement getSuitableJavaElement(Object obj) {
if (!(obj instanceof IJavaElement))
return null;
IJavaElement element= (IJavaElement)obj;
if (fTypeComparator.compare(element, IJavaElement.COMPILATION_UNIT) > 0)
return element;
if (element.getElementType() == IJavaElement.CLASS_FILE)
return element;
if (((BaseJavaElementContentProvider)getViewer().getContentProvider()).getProvideWorkingCopy()) {
IJavaElement wc= getWorkingCopy(element);
if (wc != null)
element= wc;
return element;
}
else {
ICompilationUnit cu= getCompilationUnit(element);
if (cu != null && ((IWorkingCopy)cu).isWorkingCopy())
return ((IWorkingCopy)cu).getOriginal(element);
else
return element;
}
}
/**
* @see JavaEditor#getElementAt(int)
*/
protected IJavaElement getElementForInputAt(IEditorInput input, int offset) {
if (input instanceof IClassFileEditorInput) {
try {
return ((IClassFileEditorInput)input).getClassFile().getElementAt(offset);
} catch (JavaModelException ex) {
return null;
}
}
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
ICompilationUnit unit= manager.getWorkingCopy(input);
if (unit != null)
try {
unit.reconcile();
return unit.getElementAt(offset);
} catch (JavaModelException ex) {
}
return null;
}
protected IType getTypeForCU(ICompilationUnit cu) {
cu= (ICompilationUnit)getSuitableJavaElement(cu);
// Use primary type if possible
IType primaryType= cu.findPrimaryType();
if (primaryType != null)
return primaryType;
// Use first top-level type
try {
IType[] types= cu.getTypes();
if (types.length > 0)
return types[0];
else
return null;
} catch (JavaModelException ex) {
return null;
}
}
void setProcessSelectionEvents(boolean state) {
fProcessSelectionEvents= state;
}
}
|
14,898 |
Bug 14898 working set class cast exception
|
20020425 with plugin export .5 on Linux-Motif and W2k: 1) Edit an existing working set from package view. 2) Select and Unselect a project -> Finish button is enabled now. 3) Press Finish -> see result below ---8<--- java.lang.ClassCastException: java.lang.String at org.eclipse.jdt.internal.ui.packageview.PackageExplorerActionGroup$1.propertyCha nge(PackageExplorerActionGroup.java:299) at org.eclipse.jdt.internal.ui.workingsets.WorkingSetFilterActionGroup$2.propertyCh ange(WorkingSetFilterActionGroup.java:223) at org.eclipse.ui.internal.WorkingSet.firePropertyChange (WorkingSet.java:74) at org.eclipse.ui.internal.WorkingSet.setName(WorkingSet.java:214) at org.eclipse.ui.internal.dialogs.ResourceWorkingSetPage.finish (ResourceWorkingSetPage.java:189) at org.eclipse.ui.internal.dialogs.WorkingSetEditWizard.performFinish (WorkingSetEditWizard.java:78) at org.eclipse.jface.wizard.WizardDialog.finishPressed (WizardDialog.java:577) at org.eclipse.jface.wizard.WizardDialog.buttonPressed (WizardDialog.java:312) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:379) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:85) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:75) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:637) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1412) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1208) at org.eclipse.jface.window.Window.runEventLoop(Window.java:538) at org.eclipse.jface.window.Window.open(Window.java:525) at org.eclipse.ui.internal.dialogs.WorkingSetSelectionDialog.editSelectedWorkingSet (WorkingSetSelectionDialog.java:246) at org.eclipse.ui.internal.dialogs.WorkingSetSelectionDialog.access$1 (WorkingSetSelectionDialog.java:214) at org.eclipse.ui.internal.dialogs.WorkingSetSelectionDialog$2.widgetSelected (WorkingSetSelectionDialog.java:110) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:85) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:75) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:637) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1412) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1208) at org.eclipse.jface.window.Window.runEventLoop(Window.java:538) at org.eclipse.jface.window.Window.open(Window.java:525) at org.eclipse.ui.internal.dialogs.WorkingSetSelectionDialog.open (WorkingSetSelectionDialog.java:297) at org.eclipse.jdt.internal.ui.workingsets.SelectWorkingSetAction.run (SelectWorkingSetAction.java:66) at org.eclipse.jface.action.Action.runWithEvent(Action.java:590) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java:361) at org.eclipse.jface.action.ActionContributionItem.access$0 (ActionContributionItem.java:352) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java:47) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:75) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:637) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1412) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1208) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:842) at org.eclipse.ui.internal.Workbench.run(Workbench.java:825) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:643) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:349) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:160) at org.eclipse.core.launcher.Main.run(Main.java:548) at org.eclipse.core.launcher.Main.main(Main.java:403)
|
resolved fixed
|
18ba29a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-30T14:37:43Z | 2002-04-30T12:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/packageview/PackageExplorerActionGroup.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.packageview;
import org.eclipse.core.resources.IContainer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkingSet;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.actions.NewWizardMenu;
import org.eclipse.ui.actions.OpenInNewWindowAction;
import org.eclipse.ui.actions.RefreshAction;
import org.eclipse.ui.views.framelist.BackAction;
import org.eclipse.ui.views.framelist.ForwardAction;
import org.eclipse.ui.views.framelist.FrameList;
import org.eclipse.ui.views.framelist.GoIntoAction;
import org.eclipse.ui.views.framelist.UpAction;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IOpenable;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.actions.BuildActionGroup;
import org.eclipse.jdt.ui.actions.CCPActionGroup;
import org.eclipse.jdt.ui.actions.GenerateActionGroup;
import org.eclipse.jdt.ui.actions.ImportActionGroup;
import org.eclipse.jdt.ui.actions.JavaSearchActionGroup;
import org.eclipse.jdt.ui.actions.JdtActionConstants;
import org.eclipse.jdt.ui.actions.MemberFilterActionGroup;
import org.eclipse.jdt.ui.actions.NavigateActionGroup;
import org.eclipse.jdt.ui.actions.OpenAction;
import org.eclipse.jdt.ui.actions.RefactorActionGroup;
import org.eclipse.jdt.ui.actions.ShowActionGroup;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.preferences.JavaBasePreferencePage;
import org.eclipse.jdt.internal.ui.workingsets.WorkingSetFilterActionGroup;
public class PackageExplorerActionGroup extends CompositeActionGroup {
private PackageExplorerPart fPart;
private GoIntoAction fZoomInAction;
private BackAction fBackAction;
private ForwardAction fForwardAction;
private UpAction fUpAction;
private GotoTypeAction fGotoTypeAction;
private GotoPackageAction fGotoPackageAction;
private NavigateActionGroup fNavigateActionGroup;
private BuildActionGroup fBuildActionGroup;
private CCPActionGroup fCCPActionGroup;
private WorkingSetFilterActionGroup fWorkingSetFilterActionGroup;
private MemberFilterActionGroup fMemberFilterActionGroup;
private ShowLibrariesAction fShowLibrariesAction;
private FilterSelectionAction fFilterAction;
public PackageExplorerActionGroup(PackageExplorerPart part) {
super();
fPart= part;
Shell shell= fPart.getSite().getShell();
setGroups(new ActionGroup[] {
fNavigateActionGroup= new NavigateActionGroup(fPart),
new ShowActionGroup(fPart),
fCCPActionGroup= new CCPActionGroup(fPart),
new RefactorActionGroup(fPart),
new ImportActionGroup(fPart),
new GenerateActionGroup(fPart),
fBuildActionGroup= new BuildActionGroup(fPart),
new JavaSearchActionGroup(fPart, fPart.getViewer()),
fWorkingSetFilterActionGroup= new WorkingSetFilterActionGroup(part.getViewer(), JavaUI.ID_PACKAGES, shell, createTitleUpdater())});
PackagesFrameSource frameSource= new PackagesFrameSource(fPart);
FrameList frameList= new FrameList(frameSource);
frameSource.connectTo(frameList);
fZoomInAction= new GoIntoAction(frameList);
fBackAction= new BackAction(frameList);
fForwardAction= new ForwardAction(frameList);
fUpAction= new UpAction(frameList);
fGotoTypeAction= new GotoTypeAction(fPart);
fGotoPackageAction= new GotoPackageAction(fPart);
fMemberFilterActionGroup= new MemberFilterActionGroup(fPart.getViewer(), "PackageView"); //$NON-NLS-1$
fShowLibrariesAction = new ShowLibrariesAction(fPart, PackagesMessages.getString("PackageExplorer.referencedLibs")); //$NON-NLS-1$
fFilterAction = new FilterSelectionAction(shell, fPart, PackagesMessages.getString("PackageExplorer.filters")); //$NON-NLS-1$
}
//---- Persistent state -----------------------------------------------------------------------
/* package */ void restoreState(IMemento memento) {
fMemberFilterActionGroup.restoreState(memento);
fWorkingSetFilterActionGroup.restoreState(memento);
}
/* package */ void saveState(IMemento memento) {
fMemberFilterActionGroup.saveState(memento);
fWorkingSetFilterActionGroup.saveState(memento);
}
//---- Action Bars ----------------------------------------------------------------------------
public void fillActionBars(IActionBars actionBars) {
super.fillActionBars(actionBars);
setGlobalActionHandlers(actionBars);
fillToolBar(actionBars.getToolBarManager());
fillViewMenu(actionBars.getMenuManager());
}
private void setGlobalActionHandlers(IActionBars actionBars) {
// Navigate Go Into and Go To actions.
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.GO_INTO, fZoomInAction);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.BACK, fBackAction);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.FORWARD, fForwardAction);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.UP, fUpAction);
actionBars.setGlobalActionHandler(JdtActionConstants.GOTO_TYPE, fGotoTypeAction);
actionBars.setGlobalActionHandler(JdtActionConstants.GOTO_PACKAGE, fGotoPackageAction);
}
/* package */ void fillToolBar(IToolBarManager toolBar) {
toolBar.removeAll();
toolBar.add(fBackAction);
toolBar.add(fForwardAction);
toolBar.add(fUpAction);
if (JavaBasePreferencePage.showCompilationUnitChildren()) {
toolBar.add(new Separator());
fMemberFilterActionGroup.contributeToToolBar(toolBar);
}
}
/* package */ void fillViewMenu(IMenuManager menu) {
menu.add(fFilterAction);
menu.add(fShowLibrariesAction);
menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS+"-end"));//$NON-NLS-1$
}
/* package */ void handleSelectionChanged(SelectionChangedEvent event) {
fZoomInAction.update();
}
//---- Context menu -------------------------------------------------------------------------
public void fillContextMenu(IMenuManager menu) {
IStructuredSelection selection= (IStructuredSelection)getContext().getSelection();
int size= selection.size();
Object element= selection.getFirstElement();
IJavaElement jElement= element instanceof IJavaElement ? (IJavaElement)element : null;
if (size == 1 && isNewTarget(jElement)) {
IMenuManager newMenu= new MenuManager(PackagesMessages.getString("PackageExplorer.new")); //$NON-NLS-1$
menu.appendToGroup(IContextMenuConstants.GROUP_NEW, newMenu);
new NewWizardMenu(newMenu, fPart.getSite().getWorkbenchWindow(), false);
}
addGotoMenu(menu, element, size);
addOpenNewWindowAction(menu, element);
super.fillContextMenu(menu);
}
private void addGotoMenu(IMenuManager menu, Object element, int size) {
if (size == 1 && fPart.getViewer().isExpandable(element) && isGoIntoTarget(element))
menu.appendToGroup(IContextMenuConstants.GROUP_GOTO, fZoomInAction);
/*
MenuManager gotoMenu= new MenuManager(PackagesMessages.getString("PackageExplorer.gotoTitle")); //$NON-NLS-1$
menu.appendToGroup(IContextMenuConstants.GROUP_GOTO, gotoMenu);
gotoMenu.add(fBackAction);
gotoMenu.add(fForwardAction);
gotoMenu.add(fUpAction);
gotoMenu.add(fGotoTypeAction);
gotoMenu.add(fGotoPackageAction);
*/
}
private boolean isNewTarget(IJavaElement element) {
if (element == null)
return false;
int type= element.getElementType();
return type == IJavaElement.JAVA_PROJECT ||
type == IJavaElement.PACKAGE_FRAGMENT_ROOT ||
type == IJavaElement.PACKAGE_FRAGMENT;
}
private boolean isGoIntoTarget(Object element) {
if (element == null)
return false;
if (element instanceof IJavaElement) {
int type= ((IJavaElement)element).getElementType();
return type == IJavaElement.JAVA_PROJECT ||
type == IJavaElement.PACKAGE_FRAGMENT_ROOT ||
type == IJavaElement.PACKAGE_FRAGMENT;
}
return false;
}
private void addOpenNewWindowAction(IMenuManager menu, Object element) {
if (element instanceof IJavaElement) {
try {
element= ((IJavaElement)element).getCorrespondingResource();
} catch(JavaModelException e) {
}
}
if (!(element instanceof IContainer))
return;
menu.appendToGroup(
IContextMenuConstants.GROUP_OPEN,
new OpenInNewWindowAction(fPart.getSite().getWorkbenchWindow(), (IContainer)element));
}
//---- Key board handling ------------------------------------------------------------
/* package*/ void handleDoubleClick(DoubleClickEvent event) {
OpenAction openAction= fNavigateActionGroup.getOpenAction();
if (openAction != null && openAction.isEnabled()) {
openAction.run();
return;
}
TreeViewer viewer= fPart.getViewer();
Object element= ((IStructuredSelection)event.getSelection()).getFirstElement();
if (viewer.isExpandable(element)) {
if (JavaBasePreferencePage.doubleClickGoesInto()) {
// don't zoom into compilation units and class files
if (element instanceof IOpenable &&
!(element instanceof ICompilationUnit) &&
!(element instanceof IClassFile)) {
fZoomInAction.run();
}
} else {
viewer.setExpandedState(element, !viewer.getExpandedState(element));
}
}
}
/* package */ void handleKeyEvent(KeyEvent event) {
if (event.stateMask != 0)
return;
if (event.keyCode == SWT.F5) {
RefreshAction action= fBuildActionGroup.getRefreshAction();
if (action.isEnabled())
action.run();
} else if (event.character == SWT.DEL) {
IAction delete= fCCPActionGroup.getDeleteAction();
if (delete.isEnabled())
delete.run();
}
}
private IPropertyChangeListener createTitleUpdater() {
return new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
String property= event.getProperty();
if (IWorkbenchPage.CHANGE_WORKING_SET_REPLACE.equals(property)
|| IWorkingSet.CHANGE_WORKING_SET_NAME_CHANGE.equals(property)) {
Object workingSet= (IWorkingSet)event.getNewValue();
String workingSetName= null;
if (workingSet instanceof IWorkingSet)
workingSetName= ((IWorkingSet)workingSet).getName();
fPart.setWorkingSetName(workingSetName);
fPart.updateTitle();
}
}
};
}
}
|
14,898 |
Bug 14898 working set class cast exception
|
20020425 with plugin export .5 on Linux-Motif and W2k: 1) Edit an existing working set from package view. 2) Select and Unselect a project -> Finish button is enabled now. 3) Press Finish -> see result below ---8<--- java.lang.ClassCastException: java.lang.String at org.eclipse.jdt.internal.ui.packageview.PackageExplorerActionGroup$1.propertyCha nge(PackageExplorerActionGroup.java:299) at org.eclipse.jdt.internal.ui.workingsets.WorkingSetFilterActionGroup$2.propertyCh ange(WorkingSetFilterActionGroup.java:223) at org.eclipse.ui.internal.WorkingSet.firePropertyChange (WorkingSet.java:74) at org.eclipse.ui.internal.WorkingSet.setName(WorkingSet.java:214) at org.eclipse.ui.internal.dialogs.ResourceWorkingSetPage.finish (ResourceWorkingSetPage.java:189) at org.eclipse.ui.internal.dialogs.WorkingSetEditWizard.performFinish (WorkingSetEditWizard.java:78) at org.eclipse.jface.wizard.WizardDialog.finishPressed (WizardDialog.java:577) at org.eclipse.jface.wizard.WizardDialog.buttonPressed (WizardDialog.java:312) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:379) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:85) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:75) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:637) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1412) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1208) at org.eclipse.jface.window.Window.runEventLoop(Window.java:538) at org.eclipse.jface.window.Window.open(Window.java:525) at org.eclipse.ui.internal.dialogs.WorkingSetSelectionDialog.editSelectedWorkingSet (WorkingSetSelectionDialog.java:246) at org.eclipse.ui.internal.dialogs.WorkingSetSelectionDialog.access$1 (WorkingSetSelectionDialog.java:214) at org.eclipse.ui.internal.dialogs.WorkingSetSelectionDialog$2.widgetSelected (WorkingSetSelectionDialog.java:110) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:85) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:75) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:637) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1412) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1208) at org.eclipse.jface.window.Window.runEventLoop(Window.java:538) at org.eclipse.jface.window.Window.open(Window.java:525) at org.eclipse.ui.internal.dialogs.WorkingSetSelectionDialog.open (WorkingSetSelectionDialog.java:297) at org.eclipse.jdt.internal.ui.workingsets.SelectWorkingSetAction.run (SelectWorkingSetAction.java:66) at org.eclipse.jface.action.Action.runWithEvent(Action.java:590) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java:361) at org.eclipse.jface.action.ActionContributionItem.access$0 (ActionContributionItem.java:352) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java:47) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:75) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:637) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1412) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1208) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:842) at org.eclipse.ui.internal.Workbench.run(Workbench.java:825) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:643) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:349) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:160) at org.eclipse.core.launcher.Main.run(Main.java:548) at org.eclipse.core.launcher.Main.main(Main.java:403)
|
resolved fixed
|
18ba29a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-30T14:37:43Z | 2002-04-30T12:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/workingsets/WorkingSetFilterActionGroup.java
| |
13,817 |
Bug 13817 Problems with Organize Imports
| null |
resolved fixed
|
f7a71f1
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-30T14:59:28Z | 2002-04-15T19:46:40Z |
org.eclipse.jdt.ui/core
| |
13,817 |
Bug 13817 Problems with Organize Imports
| null |
resolved fixed
|
f7a71f1
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-30T14:59:28Z | 2002-04-15T19:46:40Z |
extension/org/eclipse/jdt/internal/corext/codemanipulation/ImportsStructure.java
| |
14,409 |
Bug 14409 Hardcoded usage of \t for indent
|
Build 20020418 While fixing the indent problem for extract method I did a search for \t in JDT UI. The following classes are IMO suspicious regarding their usage of \t JavaAutoIndentStrategy.java NLSLine.java NLSRefactoring.java StubUtility.java SurroundWithTryCatchRefactoring.java
|
resolved fixed
|
67596b4
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-04-30T17:28:30Z | 2002-04-23T13:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/JavaAutoIndentStrategy.java
|
package org.eclipse.jdt.internal.ui.text.java;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DefaultAutoIndentStrategy;
import org.eclipse.jface.text.DocumentCommand;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentPartitioner;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jdt.internal.ui.preferences.CodeFormatterPreferencePage;
import org.eclipse.jdt.internal.ui.text.JavaPartitionScanner;
/**
* Auto indent strategy sensitive to brackets.
*/
public class JavaAutoIndentStrategy extends DefaultAutoIndentStrategy {
public JavaAutoIndentStrategy() {
}
// evaluate the line with the opening bracket that matches the closing bracket on the given line
protected int findMatchingOpenBracket(IDocument d, int line, int end, int closingBracketIncrease) throws BadLocationException {
int start= d.getLineOffset(line);
int brackcount= getBracketCount(d, start, end, false) - closingBracketIncrease;
// sum up the brackets counts of each line (closing brackets count negative,
// opening positive) until we find a line the brings the count to zero
while (brackcount < 0) {
line--;
if (line < 0) {
return -1;
}
start= d.getLineOffset(line);
end= start + d.getLineLength(line) - 1;
brackcount += getBracketCount(d, start, end, false);
}
return line;
}
private int getBracketCount(IDocument d, int start, int end, boolean ignoreCloseBrackets) throws BadLocationException {
int bracketcount= 0;
while (start < end) {
char curr= d.getChar(start);
start++;
switch (curr) {
case '/' :
if (start < end) {
char next= d.getChar(start);
if (next == '*') {
// a comment starts, advance to the comment end
start= getCommentEnd(d, start + 1, end);
} else if (next == '/') {
// '//'-comment: nothing to do anymore on this line
start= end;
}
}
break;
case '*' :
if (start < end) {
char next= d.getChar(start);
if (next == '/') {
// we have been in a comment: forget what we read before
bracketcount= 0;
start++;
}
}
break;
case '{' :
bracketcount++;
ignoreCloseBrackets= false;
break;
case '}' :
if (!ignoreCloseBrackets) {
bracketcount--;
}
break;
case '"' :
case '\'' :
start= getStringEnd(d, start, end, curr);
break;
default :
}
}
return bracketcount;
}
// ----------- bracket counting ------------------------------------------------------
private int getCommentEnd(IDocument d, int pos, int end) throws BadLocationException {
while (pos < end) {
char curr= d.getChar(pos);
pos++;
if (curr == '*') {
if (pos < end && d.getChar(pos) == '/') {
return pos + 1;
}
}
}
return end;
}
protected String getIndentOfLine(IDocument d, int line) throws BadLocationException {
if (line > -1) {
int start= d.getLineOffset(line);
int end= start + d.getLineLength(line) - 1;
int whiteend= findEndOfWhiteSpace(d, start, end);
return d.get(start, whiteend - start);
} else {
return ""; //$NON-NLS-1$
}
}
private int getStringEnd(IDocument d, int pos, int end, char ch) throws BadLocationException {
while (pos < end) {
char curr= d.getChar(pos);
pos++;
if (curr == '\\') {
// ignore escaped characters
pos++;
} else if (curr == ch) {
return pos;
}
}
return end;
}
protected void smartInsertAfterBracket(IDocument d, DocumentCommand c) {
if (c.offset == -1 || d.getLength() == 0)
return;
try {
int p= (c.offset == d.getLength() ? c.offset - 1 : c.offset);
int line= d.getLineOfOffset(p);
int start= d.getLineOffset(line);
int whiteend= findEndOfWhiteSpace(d, start, c.offset);
// shift only when line does not contain any text up to the closing bracket
if (whiteend == c.offset) {
// evaluate the line with the opening bracket that matches out closing bracket
int indLine= findMatchingOpenBracket(d, line, c.offset, 1);
if (indLine != -1 && indLine != line) {
// take the indent of the found line
StringBuffer replaceText= new StringBuffer(getIndentOfLine(d, indLine));
// add the rest of the current line including the just added close bracket
replaceText.append(d.get(whiteend, c.offset - whiteend));
replaceText.append(c.text);
// modify document command
c.length += c.offset - start;
c.offset= start;
c.text= replaceText.toString();
}
}
} catch (BadLocationException excp) {
System.out.println(JavaTextMessages.getString("AutoIndent.error.bad_location.message1")); //$NON-NLS-1$
}
}
protected void smartIndentAfterNewLine(IDocument d, DocumentCommand c) {
int docLength= d.getLength();
if (c.offset == -1 || docLength == 0)
return;
try {
int p= (c.offset == docLength ? c.offset - 1 : c.offset);
int line= d.getLineOfOffset(p);
StringBuffer buf= new StringBuffer(c.text);
if (c.offset < docLength && d.getChar(c.offset) == '}') {
int indLine= findMatchingOpenBracket(d, line, c.offset, 0);
if (indLine == -1) {
indLine= line;
}
buf.append(getIndentOfLine(d, indLine));
} else {
int start= d.getLineOffset(line);
// if line just ended a javadoc comment, take the indent from the comment's begin line
IDocumentPartitioner partitioner= d.getDocumentPartitioner();
if (partitioner != null) {
ITypedRegion region= partitioner.getPartition(start);
if (JavaPartitionScanner.JAVA_DOC.equals(region.getType()))
start= d.getLineInformationOfOffset(region.getOffset()).getOffset();
}
int whiteend= findEndOfWhiteSpace(d, start, c.offset);
buf.append(d.get(start, whiteend - start));
if (getBracketCount(d, start, c.offset, true) > 0) {
buf.append(getOneIndentLevel());
}
}
c.text= buf.toString();
} catch (BadLocationException excp) {
System.out.println(JavaTextMessages.getString("AutoIndent.error.bad_location.message2")); //$NON-NLS-1$
}
}
private String getOneIndentLevel() {
if (CodeFormatterPreferencePage.useSpaces()) {
StringBuffer buf= new StringBuffer();
for (int i= CodeFormatterPreferencePage.getTabSize() - 1; i >= 0; i--) {
buf.append(' ');
}
return buf.toString();
}
return String.valueOf('\t');
}
/**
* Returns whether the text ends with one of the given search strings.
*/
private boolean endsWithDelimiter(IDocument d, String txt) {
String[] delimiters= d.getLegalLineDelimiters();
for (int i= 0; i < delimiters.length; i++) {
if (txt.endsWith(delimiters[i]))
return true;
}
return false;
}
/**
* @see IAutoIndentStrategy#customizeDocumentCommand
*/
public void customizeDocumentCommand(IDocument d, DocumentCommand c) {
if (c.length == 0 && c.text != null && endsWithDelimiter(d, c.text))
smartIndentAfterNewLine(d, c);
else if ("}".equals(c.text)) { //$NON-NLS-1$
smartInsertAfterBracket(d, c);
}
}
}
|
14,975 |
Bug 14975 Resource exception while running plug-in import
|
Build 20020430 Started from a full-source Eclipse workspace 20020425, which I upgraded into a 20020430 one (first imported existing library projects - apache, xerces, etc) then selected all other projects (but jdt/core) as source ones). Got the following exception. !ENTRY org.eclipse.jdt.ui 4 1 Wed May 01 01:26:10 CEST 2002 !MESSAGE Internal Error !STACK org.eclipse.core.internal.resources.ResourceException: Resource /org.eclipse.core.resources/os does not exist. at org.eclipse.core.internal.resources.Resource.checkExists (Resource.java:174) at org.eclipse.core.internal.resources.Resource.checkAccessible (Resource.java:89) at org.eclipse.core.internal.resources.Resource.findMarkers (Resource.java:550) at org.eclipse.jdt.internal.ui.viewsupport.ErrorTickAdornmentProvider.getErrorTicks FromMarkers(ErrorTickAdornmentProvider.java:90) at org.eclipse.jdt.internal.ui.viewsupport.ErrorTickAdornmentProvider.computeAdornm entFlags(ErrorTickAdornmentProvider.java:70) at org.eclipse.jdt.internal.ui.viewsupport.JavaUILabelProvider.getImage (JavaUILabelProvider.java:82) at org.eclipse.jface.viewers.DecoratingLabelProvider.getImage (DecoratingLabelProvider.java:65) at org.eclipse.jface.viewers.StructuredViewer.getLabel (StructuredViewer.java:1089) at org.eclipse.jface.viewers.TreeViewer.doUpdateItem(TreeViewer.java:88) at org.eclipse.jface.viewers.AbstractTreeViewer.doUpdateItem (AbstractTreeViewer.java:352) at org.eclipse.jface.viewers.StructuredViewer.updateItem (StructuredViewer.java:1044) at org.eclipse.jface.viewers.AbstractTreeViewer.internalRefresh (AbstractTreeViewer.java:846) at org.eclipse.jface.viewers.AbstractTreeViewer.internalRefresh (AbstractTreeViewer.java:860) at org.eclipse.jface.viewers.AbstractTreeViewer.internalRefresh (AbstractTreeViewer.java:860) at org.eclipse.jface.viewers.AbstractTreeViewer.internalRefresh (AbstractTreeViewer.java:829) at org.eclipse.jface.viewers.StructuredViewer$1.run (StructuredViewer.java:676) at org.eclipse.jface.viewers.StructuredViewer.preservingSelection (StructuredViewer.java:616) at org.eclipse.jface.viewers.StructuredViewer.refresh (StructuredViewer.java:674) at org.eclipse.jdt.ui.JavaElementContentProvider$2.run (JavaElementContentProvider.java:255) at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:29) at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages (Synchronizer.java:93) at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:1389) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1211) at org.eclipse.jface.operation.ModalContext$ModalContextThread.block (ModalContext.java:133) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:258) at org.eclipse.jface.wizard.WizardDialog.run(WizardDialog.java:720) at org.eclipse.pde.internal.ui.wizards.imports.PluginImportWizard.performFinish (PluginImportWizard.java:100) at org.eclipse.jface.wizard.WizardDialog.finishPressed (WizardDialog.java:577) at org.eclipse.jface.wizard.WizardDialog.buttonPressed (WizardDialog.java:312) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:379) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:85) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:75) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:637) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1412) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1208) at org.eclipse.jface.window.Window.runEventLoop(Window.java:538) at org.eclipse.jface.window.Window.open(Window.java:525) at org.eclipse.ui.actions.ImportResourcesAction.run (ImportResourcesAction.java:117) at org.eclipse.jface.action.Action.runWithEvent(Action.java:590) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java:361) at org.eclipse.jface.action.ActionContributionItem.access$0 (ActionContributionItem.java:352) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java:47) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:75) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:637) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1412) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1208) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:883) at org.eclipse.ui.internal.Workbench.run(Workbench.java:866) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:733) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:349) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:162) at org.eclipse.core.launcher.Main.run(Main.java:588) at org.eclipse.core.launcher.UIMain.main(UIMain.java:52)
|
resolved fixed
|
de1d940
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-01T10:02:57Z | 2002-04-30T23:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/viewsupport/ErrorTickAdornmentProvider.java
|
package org.eclipse.jdt.internal.ui.viewsupport;
import java.util.Iterator;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.texteditor.MarkerAnnotation;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.ISourceReference;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
public class ErrorTickAdornmentProvider implements IAdornmentProvider {
private static final int ERRORTICK_WARNING= JavaElementImageProvider.OVERLAY_WARNING;
private static final int ERRORTICK_ERROR= JavaElementImageProvider.OVERLAY_ERROR;
/*
* @see IAdornmentProvider#computeAdornmentFlags(Object, int)
*/
public int computeAdornmentFlags(Object obj) {
try {
if (obj instanceof IJavaElement) {
IJavaElement element= (IJavaElement) obj;
if (!element.exists()) {
return 0;
}
int type= element.getElementType();
switch (type) {
case IJavaElement.JAVA_PROJECT:
case IJavaElement.PACKAGE_FRAGMENT_ROOT:
return getErrorTicksFromMarkers(element.getCorrespondingResource(), IResource.DEPTH_INFINITE, null);
case IJavaElement.PACKAGE_FRAGMENT:
case IJavaElement.CLASS_FILE:
return getErrorTicksFromMarkers(element.getCorrespondingResource(), IResource.DEPTH_ONE, null);
case IJavaElement.COMPILATION_UNIT:
case IJavaElement.PACKAGE_DECLARATION:
case IJavaElement.IMPORT_DECLARATION:
case IJavaElement.IMPORT_CONTAINER:
case IJavaElement.TYPE:
case IJavaElement.INITIALIZER:
case IJavaElement.METHOD:
case IJavaElement.FIELD:
ICompilationUnit cu= (ICompilationUnit) element.getAncestor(IJavaElement.COMPILATION_UNIT);
if (cu != null && cu.exists()) {
// I assume that only source elements in compilation unit can have markers
ISourceRange range= ((ISourceReference)element).getSourceRange();
// working copy: look at annotation model
if (cu.isWorkingCopy()) {
return getErrorTicksFromWorkingCopy((ICompilationUnit) cu.getOriginalElement(), range);
}
return getErrorTicksFromMarkers(cu.getCorrespondingResource(), IResource.DEPTH_ONE, range);
}
default:
}
} else if (obj instanceof IResource) {
return getErrorTicksFromMarkers((IResource) obj, IResource.DEPTH_INFINITE, null);
}
} catch (CoreException e) {
JavaPlugin.log(e);
}
return 0;
}
/*
* @see IAdornmentProvider#dispose()
*/
public void dispose() {
}
private int getErrorTicksFromMarkers(IResource res, int depth, ISourceRange range) throws CoreException {
if (res == null) { // for elements in archives
return 0;
}
int info= 0;
IMarker[] markers= res.findMarkers(IMarker.PROBLEM, true, depth);
if (markers != null) {
for (int i= 0; i < markers.length && (info != ERRORTICK_ERROR); i++) {
IMarker curr= markers[i];
if (range == null || isMarkerInRange(curr, range)) {
int priority= curr.getAttribute(IMarker.SEVERITY, -1);
if (priority == IMarker.SEVERITY_WARNING) {
info= ERRORTICK_WARNING;
} else if (priority == IMarker.SEVERITY_ERROR) {
info= ERRORTICK_ERROR;
}
}
}
}
return info;
}
private boolean isMarkerInRange(IMarker marker, ISourceRange range) throws CoreException {
if (marker.isSubtypeOf(IMarker.TEXT)) {
int pos= marker.getAttribute(IMarker.CHAR_START, -1);
int offset= range.getOffset();
return (offset <= pos && offset + range.getLength() > pos);
}
return false;
}
private int getErrorTicksFromWorkingCopy(ICompilationUnit original, ISourceRange range) throws CoreException {
int info= 0;
if (!original.exists()) {
return 0;
}
FileEditorInput editorInput= new FileEditorInput((IFile) original.getCorrespondingResource());
IAnnotationModel model= JavaPlugin.getDefault().getCompilationUnitDocumentProvider().getAnnotationModel(editorInput);
if (model != null) {
Iterator iter= model.getAnnotationIterator();
while ((info != ERRORTICK_ERROR) && iter.hasNext()) {
Annotation curr= (Annotation) iter.next();
IMarker marker= isAnnotationInRange(model, curr, range);
if (marker != null) {
int priority= marker.getAttribute(IMarker.SEVERITY, -1);
if (priority == IMarker.SEVERITY_WARNING) {
info= ERRORTICK_WARNING;
} else if (priority == IMarker.SEVERITY_ERROR) {
info= ERRORTICK_ERROR;
}
}
}
}
return info;
}
private IMarker isAnnotationInRange(IAnnotationModel model, Annotation annot, ISourceRange range) throws CoreException {
if (annot instanceof MarkerAnnotation) {
IMarker marker= ((MarkerAnnotation)annot).getMarker();
if (marker.exists() && marker.isSubtypeOf(IMarker.PROBLEM)) {
Position pos= model.getPosition(annot);
if (pos.overlapsWith(range.getOffset(), range.getLength())) {
return marker;
}
}
}
return null;
}
}
|
14,525 |
Bug 14525 Visual confirmation should be given when adding interfaces
|
BUILD: 20020412 When using the Interface Selection dialog, the user should be given some sort of visual confirmation that the interfaces they select have actually been added after hitting the Add button. Perhaps placing a check mark next to interfaces that have already been added, or keeping a separate list inside the dialog of previously added interfaces. The latter sugegstion opens up the possibility of removing interfaces from the list of currently selected ones.
|
resolved fixed
|
ec79c7f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-01T12:40:48Z | 2002-04-24T14:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/SuperInterfaceSelectionDialog.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.wizards;
import java.util.List;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.operation.IRunnableContext;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.search.IJavaSearchConstants;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.internal.corext.util.TypeInfo;
import org.eclipse.jdt.internal.ui.dialogs.TypeSelectionDialog;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField;
public class SuperInterfaceSelectionDialog extends TypeSelectionDialog {
private static final int ADD_ID= IDialogConstants.CLIENT_ID + 1;
private ListDialogField fList;
private List fOldContent;
public SuperInterfaceSelectionDialog(Shell parent, IRunnableContext context, ListDialogField list, IJavaProject p) {
super(parent, context, IJavaSearchConstants.INTERFACE, createSearchScope(p));
fList= list;
// to restore the content of the dialog field if the dialog is canceled
fOldContent= fList.getElements();
}
/*
* @see Dialog#createButtonsForButtonBar
*/
protected void createButtonsForButtonBar(Composite parent) {
createButton(parent, ADD_ID, NewWizardMessages.getString("SuperInterfaceSelectionDialog.addButton.label"), true); //$NON-NLS-1$
super.createButtonsForButtonBar(parent);
}
/*
* @see Dialog#cancelPressed
*/
protected void cancelPressed() {
fList.setElements(fOldContent);
super.cancelPressed();
}
/*
* @see Dialog#buttonPressed
*/
protected void buttonPressed(int buttonId) {
if (buttonId == ADD_ID){
addSelectedInterface();
}
super.buttonPressed(buttonId);
}
/*
* @see Dialog#okPressed
*/
protected void okPressed() {
addSelectedInterface();
super.okPressed();
}
private void addSelectedInterface(){
Object ref= getLowerSelectedElement();
if (ref instanceof TypeInfo)
fList.addElement(((TypeInfo)ref).getFullyQualifiedName());
}
private static IJavaSearchScope createSearchScope(IJavaProject p) {
return SearchEngine.createJavaSearchScope(new IJavaProject[] { p });
}
/*
* @see AbstractElementListSelectionDialog#handleDefaultSelected()
*/
protected void handleDefaultSelected() {
if (validateCurrentSelection())
buttonPressed(ADD_ID);
}
}
|
14,421 |
Bug 14421 Old .CLASS Files Are Not Deleted
|
When creating a project that does NOT use source folders (and does not use a bin directory for .class files) the .java and .class files are stored together in the Java package structure. When converting a project to use source folders (and the required bin directory for .class files), the old .class files stored in the Java package structure are NEVER DELETED by Eclipse. This is a bug for Eclipse 1.0 and 2.0. Since I use WSDD 4.0 (which is built on Eclipse 1.0), I've seen compilation errors due to the fact that the compiler/JDT is using old .class files rather than the new ones in the project's bin directory. I have not managed to reproduce the compile errors in build 20020416. But since the old .class files should have been deleted this is still a bug for the latest build.
|
resolved fixed
|
1b8c60b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-01T17:19:31Z | 2002-04-23T16:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/BuildPathsPropertyPage.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.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.core.resources.IProject;
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.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.ui.actions.WorkspaceModifyDelegatingOperation;
import org.eclipse.ui.dialogs.PropertyPage;
import org.eclipse.ui.help.DialogPageContextComputer;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
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.JavaUIMessages;
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.BuildPathsBlock;
/**
* Property page for configuring the Java build path
*/
public class BuildPathsPropertyPage extends PropertyPage implements IStatusChangeListener {
private BuildPathsBlock fBuildPathsBlock;
/*
* @see PreferencePage#createControl(Composite)
*/
protected Control createContents(Composite parent) {
WorkbenchHelp.setHelp(parent, IJavaHelpContextIds.BUILD_PATH_PROPERTY_PAGE);
// ensure the page has no special buttons
noDefaultAndApplyButton();
IProject project= getProject();
if (project == null || !isJavaProject(project)) {
return createWithoutJava(parent);
} else if (!project.isOpen()) {
return createForClosedProject(parent);
} else {
return createWithJava(parent, project);
}
}
/**
* Content for valid projects.
*/
private Control createWithJava(Composite parent, IProject project) {
IWorkspaceRoot root= JavaPlugin.getWorkspace().getRoot();
fBuildPathsBlock= new BuildPathsBlock(root, this, false);
fBuildPathsBlock.init(JavaCore.create(project), null, null);
return fBuildPathsBlock.createControl(parent);
}
/**
* Content for non-Java projects.
*/
private Control createWithoutJava(Composite parent) {
Label label= new Label(parent, SWT.LEFT);
label.setText(JavaUIMessages.getString("BuildPathsPropertyPage.no_java_project.message")); //$NON-NLS-1$
fBuildPathsBlock= null;
setValid(true);
return label;
}
/**
* Content for closed projects.
*/
private Control createForClosedProject(Composite parent) {
Label label= new Label(parent, SWT.LEFT);
label.setText(JavaUIMessages.getString("BuildPathsPropertyPage.closed_project.message")); //$NON-NLS-1$
fBuildPathsBlock= null;
setValid(true);
return label;
}
private IProject getProject() {
IAdaptable adaptable= getElement();
if (adaptable != null) {
IJavaElement elem= (IJavaElement) adaptable.getAdapter(IJavaElement.class);
if (elem instanceof IJavaProject) {
return ((IJavaProject) elem).getProject();
}
}
return null;
}
private boolean isJavaProject(IProject proj) {
try {
return proj.hasNature(JavaCore.NATURE_ID);
} catch (CoreException e) {
JavaPlugin.log(e);
}
return false;
}
/*
* @see IPreferencePage#performOk
*/
public boolean performOk() {
if (fBuildPathsBlock != null) {
IRunnableWithProgress runnable= fBuildPathsBlock.getRunnable();
IRunnableWithProgress op= new WorkspaceModifyDelegatingOperation(runnable);
Shell shell= getControl().getShell();
try {
new ProgressMonitorDialog(shell).run(true, true, op);
} catch (InvocationTargetException e) {
String title= JavaUIMessages.getString("BuildPathsPropertyPage.error.title"); //$NON-NLS-1$
String message= JavaUIMessages.getString("BuildPathsPropertyPage.error.message"); //$NON-NLS-1$
ExceptionHandler.handle(e, shell, title, message);
return false;
} catch (InterruptedException e) {
// cancelled
return false;
}
}
return true;
}
/**
* @see IStatusChangeListener#statusChanged
*/
public void statusChanged(IStatus status) {
setValid(!status.matches(IStatus.ERROR));
StatusUtil.applyToStatusLine(this, status);
}
}
|
14,421 |
Bug 14421 Old .CLASS Files Are Not Deleted
|
When creating a project that does NOT use source folders (and does not use a bin directory for .class files) the .java and .class files are stored together in the Java package structure. When converting a project to use source folders (and the required bin directory for .class files), the old .class files stored in the Java package structure are NEVER DELETED by Eclipse. This is a bug for Eclipse 1.0 and 2.0. Since I use WSDD 4.0 (which is built on Eclipse 1.0), I've seen compilation errors due to the fact that the compiler/JDT is using old .class files rather than the new ones in the project's bin directory. I have not managed to reproduce the compile errors in build 20020416. But since the old .class files should have been deleted this is still a bug for the latest build.
|
resolved fixed
|
1b8c60b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-01T17:19:31Z | 2002-04-23T16:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/NewSourceFolderWizardPage.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.wizards;
import java.lang.reflect.InvocationTargetException;
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.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.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.Shell;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.ui.actions.WorkspaceModifyDelegatingOperation;
import org.eclipse.ui.dialogs.ElementListSelectionDialog;
import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
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.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.JavaConventions;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.ui.wizards.NewElementWizardPage;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.dialogs.StatusDialog;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.util.CoreUtility;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.wizards.buildpaths.BuildPathsBlock;
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.Separator;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField;
public class NewSourceFolderWizardPage extends NewElementWizardPage {
private static final String PAGE_NAME= "NewSourceFolderWizardPage"; //$NON-NLS-1$
private StringButtonDialogField fProjectField;
private StatusInfo fProjectStatus;
private StringButtonDialogField fRootDialogField;
private StatusInfo fRootStatus;
private SelectionButtonDialogField fEditClassPathField;
private IWorkspaceRoot fWorkspaceRoot;
private IJavaProject fCurrJProject;
private IClasspathEntry[] fEntries;
private IPath fOutputLocation;
private IPackageFragmentRoot fCreatedRoot;
public NewSourceFolderWizardPage() {
super(PAGE_NAME);
setTitle(NewWizardMessages.getString("NewSourceFolderWizardPage.title")); //$NON-NLS-1$
setDescription(NewWizardMessages.getString("NewSourceFolderWizardPage.description")); //$NON-NLS-1$
fWorkspaceRoot= ResourcesPlugin.getWorkspace().getRoot();
RootFieldAdapter adapter= new RootFieldAdapter();
fProjectField= new StringButtonDialogField(adapter);
fProjectField.setDialogFieldListener(adapter);
fProjectField.setLabelText(NewWizardMessages.getString("NewSourceFolderWizardPage.project.label")); //$NON-NLS-1$
fProjectField.setButtonLabel(NewWizardMessages.getString("NewSourceFolderWizardPage.project.button")); //$NON-NLS-1$
fRootDialogField= new StringButtonDialogField(adapter);
fRootDialogField.setDialogFieldListener(adapter);
fRootDialogField.setLabelText(NewWizardMessages.getString("NewSourceFolderWizardPage.root.label")); //$NON-NLS-1$
fRootDialogField.setButtonLabel(NewWizardMessages.getString("NewSourceFolderWizardPage.root.button")); //$NON-NLS-1$
fEditClassPathField= new SelectionButtonDialogField(SWT.PUSH);
fEditClassPathField.setDialogFieldListener(adapter);
fEditClassPathField.setLabelText(NewWizardMessages.getString("NewSourceFolderWizardPage.editclasspath.button")); //$NON-NLS-1$
fRootStatus= new StatusInfo();
fProjectStatus= new StatusInfo();
}
// -------- Initialization ---------
public void init(IStructuredSelection selection) {
if (selection == null || selection.isEmpty()) {
setDefaultAttributes();
return;
}
Object selectedElement= selection.getFirstElement();
if (selectedElement == null) {
selectedElement= EditorUtility.getActiveEditorJavaInput();
}
String projPath= null;
if (selectedElement instanceof IResource) {
IProject proj= ((IResource)selectedElement).getProject();
if (proj != null) {
projPath= proj.getFullPath().makeRelative().toString();
}
} else if (selectedElement instanceof IJavaElement) {
IJavaProject jproject= ((IJavaElement)selectedElement).getJavaProject();
if (jproject != null) {
projPath= jproject.getProject().getFullPath().makeRelative().toString();
}
}
if (projPath != null) {
fProjectField.setText(projPath);
fRootDialogField.setText(""); //$NON-NLS-1$
} else {
setDefaultAttributes();
}
}
private void setDefaultAttributes() {
String projPath= ""; //$NON-NLS-1$
try {
// find the first java project
IProject[] projects= fWorkspaceRoot.getProjects();
for (int i= 0; i < projects.length; i++) {
IProject proj= projects[i];
if (proj.hasNature(JavaCore.NATURE_ID)) {
projPath= proj.getFullPath().makeRelative().toString();
break;
}
}
} catch (CoreException e) {
// ignore here
}
fProjectField.setText(projPath);
fRootDialogField.setText(""); //$NON-NLS-1$
}
// -------- UI Creation ---------
/**
* @see WizardPage#createControl
*/
public void createControl(Composite parent) {
initializeDialogUnits(parent);
Composite composite= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
layout.marginWidth= 0;
layout.marginHeight= 0;
layout.numColumns= 3;
composite.setLayout(layout);
fProjectField.doFillIntoGrid(composite, 3);
fRootDialogField.doFillIntoGrid(composite, 3);
fRootDialogField.setFocus();
int maxFieldWidth= convertWidthInCharsToPixels(40);
LayoutUtil.setWidthHint(fProjectField.getTextControl(null), maxFieldWidth);
LayoutUtil.setHorizontalGrabbing(fProjectField.getTextControl(null));
LayoutUtil.setWidthHint(fRootDialogField.getTextControl(null), maxFieldWidth);
(new Separator()).doFillIntoGrid(composite, 3);
fEditClassPathField.doFillIntoGrid(composite, 3);
Control control= fEditClassPathField.getSelectionButton(null);
GridData gd= (GridData) control.getLayoutData();
gd.verticalAlignment= GridData.END;
gd.horizontalAlignment= GridData.BEGINNING;
setControl(composite);
WorkbenchHelp.setHelp(composite, IJavaHelpContextIds.NEW_PACKAGEROOT_WIZARD_PAGE);
}
// -------- ContainerFieldAdapter --------
private class RootFieldAdapter implements IStringButtonAdapter, IDialogFieldListener {
// -------- IStringButtonAdapter
public void changeControlPressed(DialogField field) {
packRootChangeControlPressed(field);
}
// -------- IDialogFieldListener
public void dialogFieldChanged(DialogField field) {
packRootDialogFieldChanged(field);
}
}
private void packRootChangeControlPressed(DialogField field) {
if (field == fRootDialogField) {
IFolder folder= chooseFolder();
if (folder != null) {
IPath path= folder.getFullPath().removeFirstSegments(1);
fRootDialogField.setText(path.toString());
}
} else if (field == fProjectField) {
IJavaProject jproject= chooseProject();
if (jproject != null) {
IPath path= jproject.getProject().getFullPath().makeRelative();
fProjectField.setText(path.toString());
}
}
}
private void packRootDialogFieldChanged(DialogField field) {
if (field == fRootDialogField) {
updateRootStatus();
} else if (field == fProjectField) {
updateProjectStatus();
updateRootStatus();
} else if (field == fEditClassPathField) {
if (showClassPathPropertyPage()) {
updateProjectStatus();
updateRootStatus();
}
}
updateStatus(new IStatus[] { fProjectStatus, fRootStatus });
}
private void updateProjectStatus() {
fCurrJProject= null;
String str= fProjectField.getText();
if (str.length() == 0) {
fProjectStatus.setError(NewWizardMessages.getString("NewSourceFolderWizardPage.error.EnterProjectName")); //$NON-NLS-1$
return;
}
IPath path= new Path(str);
if (path.segmentCount() != 1) {
fProjectStatus.setError(NewWizardMessages.getString("NewSourceFolderWizardPage.error.InvalidProjectPath")); //$NON-NLS-1$
return;
}
IProject project= fWorkspaceRoot.getProject(path.toString());
if (!project.exists()) {
fProjectStatus.setError(NewWizardMessages.getString("NewSourceFolderWizardPage.error.ProjectNotExists")); //$NON-NLS-1$
return;
}
try {
if (project.hasNature(JavaCore.NATURE_ID)) {
fCurrJProject= JavaCore.create(project);
fEntries= fCurrJProject.getRawClasspath();
fOutputLocation= fCurrJProject.getOutputLocation();
fProjectStatus.setOK();
return;
}
} catch (CoreException e) {
JavaPlugin.log(e);
fCurrJProject= null;
}
fProjectStatus.setError(NewWizardMessages.getString("NewSourceFolderWizardPage.error.NotAJavaProject")); //$NON-NLS-1$
}
private void updateRootStatus() {
fRootDialogField.enableButton(fCurrJProject != null);
if (fCurrJProject == null) {
return;
}
String str= fRootDialogField.getText();
if (str.length() == 0) {
fRootStatus.setError(NewWizardMessages.getFormattedString("NewSourceFolderWizardPage.error.EnterRootName", fCurrJProject.getProject().getFullPath().toString())); //$NON-NLS-1$
} else {
IPath path= fCurrJProject.getProject().getFullPath().append(str);
if (!fWorkspaceRoot.getWorkspace().validatePath(path.toString(), IResource.FOLDER).isOK()) {
fRootStatus.setError(NewWizardMessages.getString("NewSourceFolderWizardPage.error.InvalidRootName")); //$NON-NLS-1$
} else {
IResource res= fWorkspaceRoot.findMember(path);
if (res != null) {
if (res.getType() != IResource.FOLDER) {
fRootStatus.setError(NewWizardMessages.getString("NewSourceFolderWizardPage.error.NotAFolder")); //$NON-NLS-1$
return;
}
}
IClasspathEntry[] newEntries= new IClasspathEntry[fEntries.length + 1];
for (int i= 0; i < fEntries.length; i++) {
IClasspathEntry curr= fEntries[i];
if (curr.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
if (path.equals(curr.getPath())) {
fRootStatus.setError(NewWizardMessages.getString("NewSourceFolderWizardPage.error.AlreadyExisting")); //$NON-NLS-1$
return;
}
}
newEntries[i]= curr;
}
newEntries[fEntries.length]= JavaCore.newSourceEntry(path);
IStatus status= JavaConventions.validateClasspath(fCurrJProject, newEntries, fOutputLocation);
if (!status.isOK()) {
fRootStatus.setError(status.getMessage());
return;
}
fRootStatus.setOK();
}
}
}
// ---- creation ----------------
/**
* @see NewElementWizardPage#getRunnable
*/
public IRunnableWithProgress getRunnable() {
return new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException {
try {
fCreatedRoot= createPackageFragmentRoot(monitor, getShell());
} catch (CoreException e) {
throw new InvocationTargetException(e);
}
}
};
}
protected IPackageFragmentRoot getNewPackageFragmentRoot() {
return fCreatedRoot;
}
protected IPackageFragmentRoot createPackageFragmentRoot(IProgressMonitor monitor, Shell shell) throws CoreException {
String relPath= fRootDialogField.getText();
IFolder folder= fCurrJProject.getProject().getFolder(relPath);
IPath path= folder.getFullPath();
if (!folder.exists()) {
CoreUtility.createFolder(folder, true, true, monitor);
}
IClasspathEntry[] entries= fCurrJProject.getRawClasspath();
IClasspathEntry[] newEntries= new IClasspathEntry[entries.length + 1];
for (int i= entries.length - 1, k= entries.length; i >= 0; i--) {
IClasspathEntry curr= entries[i];
if (k > i && curr.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
newEntries[k--]= JavaCore.newSourceEntry(path);
}
newEntries[k--]= curr;
}
fCurrJProject.setRawClasspath(newEntries, monitor);
return fCurrJProject.getPackageFragmentRoot(folder);
}
// ------------- choose dialogs
private IFolder chooseFolder() {
Class[] acceptedClasses= new Class[] { IFolder.class };
ISelectionStatusValidator validator= new TypedElementSelectionValidator(acceptedClasses, false);
Object[] notWanted= getFilteredExistingContainerEntries();
ViewerFilter filter= new TypedViewerFilter(acceptedClasses, notWanted);
ILabelProvider lp= new WorkbenchLabelProvider();
ITreeContentProvider cp= new WorkbenchContentProvider();
ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), lp, cp);
dialog.setValidator(validator);
dialog.setTitle(NewWizardMessages.getString("NewSourceFolderWizardPage.ChooseExistingRootDialog.title")); //$NON-NLS-1$
dialog.setMessage(NewWizardMessages.getString("NewSourceFolderWizardPage.ChooseExistingRootDialog.description")); //$NON-NLS-1$
dialog.addFilter(filter);
dialog.setInput(fCurrJProject.getProject());
IResource res= fWorkspaceRoot.findMember(new Path(fRootDialogField.getText()));
if (res != null) {
dialog.setInitialSelection(res);
}
if (dialog.open() == dialog.OK) {
return (IFolder) dialog.getFirstResult();
}
return null;
}
private IJavaProject chooseProject() {
IJavaProject[] projects;
try {
projects= JavaCore.create(fWorkspaceRoot).getJavaProjects();
} catch (JavaModelException e) {
JavaPlugin.log(e);
projects= new IJavaProject[0];
}
ILabelProvider labelProvider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT);
ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), labelProvider);
dialog.setTitle(NewWizardMessages.getString("NewSourceFolderWizardPage.ChooseProjectDialog.title")); //$NON-NLS-1$
dialog.setMessage(NewWizardMessages.getString("NewSourceFolderWizardPage.ChooseProjectDialog.description")); //$NON-NLS-1$
dialog.setElements(projects);
dialog.setInitialSelections(new Object[] { fCurrJProject });
if (dialog.open() == dialog.OK) {
return (IJavaProject) dialog.getFirstResult();
}
return null;
}
// a dialog containing the class path dialog
private class EditClassPathDialog extends StatusDialog implements IStatusChangeListener {
private BuildPathsBlock fBuildPathsBlock;
public EditClassPathDialog(Shell parent) {
super(parent);
fBuildPathsBlock= new BuildPathsBlock(fWorkspaceRoot, this, false);
}
public void create() {
super.create();
fBuildPathsBlock.init(fCurrJProject, null, null);
}
protected Control createDialogArea(Composite parent) {
Composite composite= (Composite)super.createDialogArea(parent);
Control inner= fBuildPathsBlock.createControl(composite);
inner.setLayoutData(new org.eclipse.swt.layout.GridData(org.eclipse.swt.layout.GridData.FILL_BOTH));
return composite;
}
public void statusChanged(IStatus status) {
updateStatus(status);
}
protected void buttonPressed(int buttonId) {
if (buttonId == IDialogConstants.OK_ID) {
IRunnableWithProgress runnable= fBuildPathsBlock.getRunnable();
if (invokeRunnable(runnable)) {
setReturnCode(OK);
} else {
setReturnCode(CANCEL);
}
}
close();
}
private boolean invokeRunnable(IRunnableWithProgress runnable) {
IRunnableWithProgress op= new WorkspaceModifyDelegatingOperation(runnable);
try {
getWizard().getContainer().run(false, true, op);
} catch (InvocationTargetException e) {
Shell shell= getShell();
String title= NewWizardMessages.getString("NewSourceFolderWizardPage.op_error.title"); //$NON-NLS-1$
String message= NewWizardMessages.getString("NewSourceFolderWizardPage.op_error.message"); //$NON-NLS-1$
ExceptionHandler.handle(e, shell, title, message);
return false;
} catch (InterruptedException e) {
return false;
}
return true;
}
}
private boolean showClassPathPropertyPage() {
EditClassPathDialog dialog= new EditClassPathDialog(getShell());
dialog.setTitle(NewWizardMessages.getString("NewSourceFolderWizardPage.EditClassPathDialog.title")); //$NON-NLS-1$
return (dialog.open() == EditClassPathDialog.OK);
}
private IContainer[] getFilteredExistingContainerEntries() {
if (fCurrJProject == null) {
return new IContainer[0];
}
List res= new ArrayList();
try {
IResource container= fWorkspaceRoot.findMember(fCurrJProject.getOutputLocation());
if (container != null) {
res.add(container);
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
for (int i= 0; i < fEntries.length; i++) {
IClasspathEntry elem= fEntries[i];
if (elem.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
IResource container= fWorkspaceRoot.findMember(elem.getPath());
if (container != null) {
res.add(container);
}
}
}
return (IContainer[]) res.toArray(new IContainer[res.size()]);
}
}
|
14,421 |
Bug 14421 Old .CLASS Files Are Not Deleted
|
When creating a project that does NOT use source folders (and does not use a bin directory for .class files) the .java and .class files are stored together in the Java package structure. When converting a project to use source folders (and the required bin directory for .class files), the old .class files stored in the Java package structure are NEVER DELETED by Eclipse. This is a bug for Eclipse 1.0 and 2.0. Since I use WSDD 4.0 (which is built on Eclipse 1.0), I've seen compilation errors due to the fact that the compiler/JDT is using old .class files rather than the new ones in the project's bin directory. I have not managed to reproduce the compile errors in build 20020416. But since the old .class files should have been deleted this is still a bug for the latest build.
|
resolved fixed
|
1b8c60b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-01T17:19:31Z | 2002-04-23T16: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.lang.reflect.InvocationTargetException;
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.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.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.operation.IRunnableWithProgress;
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.ElementTreeSelectionDialog;
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.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaConventions;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.launching.JavaRuntime;
import org.eclipse.jdt.internal.corext.javadoc.JavaDocLocations;
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.preferences.JavaBasePreferencePage;
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 {
private IWorkspaceRoot fWorkspaceRoot;
private CheckedListDialogField fClassPathList;
private StringButtonDialogField fBuildPathDialogField;
private StatusInfo fClassPathStatus;
private StatusInfo fBuildPathStatus;
private IJavaProject fCurrJProject;
private IPath fOutputLocationPath;
private IStatusChangeListener fContext;
private Control fSWTWidget;
private boolean fShowSourceFolderPage;
private SourceContainerWorkbookPage fSourceContainerPage;
private ProjectsWorkbookPage fProjectsPage;
private LibrariesWorkbookPage fLibrariesPage;
private BuildPathBasePage fCurrPage;
public BuildPathsBlock(IWorkspaceRoot root, IStatusChangeListener context, boolean showSourceFolders) {
fWorkspaceRoot= root;
fContext= context;
fShowSourceFolderPage= showSourceFolders;
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();
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));
folder.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
tabChanged(e.item);
}
});
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));
if (fShowSourceFolderPage) {
folder.setSelection(0);
fCurrPage= fSourceContainerPage;
} else {
folder.setSelection(3);
fCurrPage= ordpage;
fClassPathList.selectFirstElement();
}
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 projExists= false;
try {
IProject project= fCurrJProject.getProject();
projExists= (project.exists() && project.getFile(".classpath").exists()); //$NON-NLS-1$
if (projExists) {
if (outputLocation == null) {
outputLocation= fCurrJProject.getOutputLocation();
}
if (classpathEntries == null) {
classpathEntries= fCurrJProject.getRawClasspath();
}
}
} catch (CoreException e) {
JavaPlugin.log(e.getStatus());
}
if (outputLocation == null) {
outputLocation= getDefaultBuildPath(jproject);
}
List newClassPath;
if (classpathEntries == null) {
newClassPath= getDefaultClassPath(jproject);
} else {
newClassPath= new ArrayList();
for (int i= 0; i < classpathEntries.length; i++) {
IClasspathEntry curr= classpathEntries[i];
int entryKind= curr.getEntryKind();
IPath path= curr.getPath();
boolean isExported= curr.isExported();
// get the resource
IResource res= null;
boolean isMissing= false;
if (entryKind != IClasspathEntry.CPE_VARIABLE) {
res= fWorkspaceRoot.findMember(path);
if (res == null) {
isMissing= (entryKind != IClasspathEntry.CPE_LIBRARY || !path.toFile().isFile());
}
} else {
IPath resolvedPath= JavaCore.getResolvedVariablePath(path);
isMissing= (resolvedPath == null) || !resolvedPath.toFile().isFile();
}
CPListElement elem= new CPListElement(entryKind, path, res, curr.getSourceAttachmentPath(), curr.getSourceAttachmentRootPath(), isExported);
if (projExists) {
elem.setIsMissing(isMissing);
}
newClassPath.add(elem);
}
}
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());
fClassPathList.setElements(newClassPath);
fClassPathList.setCheckedElements(exportedEntries);
if (fSourceContainerPage != null) {
fSourceContainerPage.init(fCurrJProject);
fProjectsPage.init(fCurrJProject);
fLibrariesPage.init(fCurrJProject);
}
doStatusLineUpdate();
}
// -------- 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;
}
// -------- evaluate default settings --------
private List getDefaultClassPath(IJavaProject jproj) {
List list= new ArrayList();
IResource srcFolder;
if (JavaBasePreferencePage.useSrcAndBinFolders()) {
String sourceFolderName= JavaBasePreferencePage.getSourceFolderName();
srcFolder= jproj.getProject().getFolder(sourceFolderName);
} else {
srcFolder= jproj.getProject();
}
list.add(new CPListElement(IClasspathEntry.CPE_SOURCE, srcFolder.getFullPath(), srcFolder));
IPath libPath= new Path(JavaRuntime.JRELIB_VARIABLE);
IPath attachPath= new Path(JavaRuntime.JRESRC_VARIABLE);
IPath attachRoot= new Path(JavaRuntime.JRESRCROOT_VARIABLE);
CPListElement elem= new CPListElement(IClasspathEntry.CPE_VARIABLE, libPath, null, attachPath, attachRoot, false);
list.add(elem);
return list;
}
private IPath getDefaultBuildPath(IJavaProject jproj) {
if (JavaBasePreferencePage.useSrcAndBinFolders()) {
String outputLocationName= JavaBasePreferencePage.getOutputLocationName();
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();
updateBuildPathStatus();
} else if (field == fBuildPathDialogField) {
updateBuildPathStatus();
}
doStatusLineUpdate();
}
// -------- verification -------------------------------
private void doStatusLineUpdate() {
IStatus res= findMostSevereStatus();
fContext.statusChanged(res);
}
private IStatus findMostSevereStatus() {
return StatusUtil.getMoreSevere(fClassPathStatus, fBuildPathStatus);
}
/**
* Validates the build path.
*/
private void updateClassPathStatus() {
fClassPathStatus.setOK();
List elements= fClassPathList.getElements();
boolean entryMissing= false;
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();
entryMissing= entryMissing || currElement.isMissing();
}
if (entryMissing) {
fClassPathStatus.setWarning(NewWizardMessages.getString("BuildPathsBlock.warning.EntryMissing")); //$NON-NLS-1$
}
if (fCurrJProject.hasClasspathCycle(entries)) {
fClassPathStatus.setWarning(NewWizardMessages.getString("BuildPathsBlock.warning.CycleInClassPath")); //$NON-NLS-1$
}
}
/**
* Validates output location & build path.
*/
private void updateBuildPathStatus() {
fOutputLocationPath= null;
String text= fBuildPathDialogField.getText();
if ("".equals(text)) { //$NON-NLS-1$
fBuildPathStatus.setError(NewWizardMessages.getString("BuildPathsBlock.error.EnterBuildPath")); //$NON-NLS-1$
return;
}
IPath path= getOutputLocation();
IResource res= fWorkspaceRoot.findMember(path);
if (res != null) {
// if exists, must be a folder or project
if (res.getType() == IResource.FILE) {
fBuildPathStatus.setError(NewWizardMessages.getString("BuildPathsBlock.error.InvalidBuildPath")); //$NON-NLS-1$
return;
}
}
fOutputLocationPath= path;
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();
}
IStatus status= JavaConventions.validateClasspath(fCurrJProject, entries, path);
if (!status.isOK()) {
fBuildPathStatus.setError(status.getMessage());
return;
}
if (res != null && res.exists() && fCurrJProject.exists()) {
try {
IPath oldOutputLocation= fCurrJProject.getOutputLocation();
if (!oldOutputLocation.equals(fOutputLocationPath)) {
if (((IContainer)res).members().length > 0) {
fBuildPathStatus.setWarning(NewWizardMessages.getString("BuildPathsBlock.warning.OutputFolderNotEmpty")); //$NON-NLS-1$
return;
}
}
} catch (CoreException e) {
JavaPlugin.log(e);
}
}
fBuildPathStatus.setOK();
}
// -------- creation -------------------------------
/**
* Creates a runnable that sets the configured build paths.
*/
public IRunnableWithProgress getRunnable() {
final List classPathEntries= fClassPathList.getElements();
final IPath path= getOutputLocation();
return new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException {
if (monitor == null) {
monitor= new NullProgressMonitor();
}
monitor.beginTask(NewWizardMessages.getString("BuildPathsBlock.operationdesc"), 10); //$NON-NLS-1$
try {
createJavaProject(classPathEntries, path, monitor);
} catch (CoreException e) {
throw new InvocationTargetException(e);
} 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 createJavaProject(List classPathEntries, IPath buildPath, IProgressMonitor monitor) throws CoreException {
// 10 monitor steps to go
// create and set the output path first
if (!fWorkspaceRoot.exists(buildPath)) {
IFolder folder= fWorkspaceRoot.getFolder(buildPath);
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);
}
classpath[i]= entry.getClasspathEntry();
// set javadoc location
URL javadocLocation= entry.getJavadocLocation();
if (javadocLocation != null) {
IPath path= entry.getPath();
if (entry.getEntryKind() == IClasspathEntry.CPE_VARIABLE) {
path= JavaCore.getResolvedVariablePath(path);
}
if (path != null) {
JavaDocLocations.setLibraryJavadocLocation(path, javadocLocation);
}
}
}
monitor.worked(1);
fCurrJProject.setRawClasspath(classpath, buildPath, new SubProgressMonitor(monitor, 7));
}
// ---------- 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);
}
ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(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);
if (dialog.open() == dialog.OK) {
return (IContainer)dialog.getFirstResult();
}
return null;
}
// -------- tab switching ----------
private void tabChanged(Widget widget) {
if (widget instanceof TabItem) {
BuildPathBasePage newPage= (BuildPathBasePage) ((TabItem) widget).getData();
if (fCurrPage != null) {
List selection= fCurrPage.getSelection();
if (!selection.isEmpty()) {
newPage.setSelection(selection);
}
}
fCurrPage= newPage;
}
}
}
|
14,421 |
Bug 14421 Old .CLASS Files Are Not Deleted
|
When creating a project that does NOT use source folders (and does not use a bin directory for .class files) the .java and .class files are stored together in the Java package structure. When converting a project to use source folders (and the required bin directory for .class files), the old .class files stored in the Java package structure are NEVER DELETED by Eclipse. This is a bug for Eclipse 1.0 and 2.0. Since I use WSDD 4.0 (which is built on Eclipse 1.0), I've seen compilation errors due to the fact that the compiler/JDT is using old .class files rather than the new ones in the project's bin directory. I have not managed to reproduce the compile errors in build 20020416. But since the old .class files should have been deleted this is still a bug for the latest build.
|
resolved fixed
|
1b8c60b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-01T17:19:31Z | 2002-04-23T16:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/wizards/JavaCapabilityConfigurationPage.java
|
package org.eclipse.jdt.ui.wizards;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
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.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.core.JavaCore;
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;
/**
*/
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 controls 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(ResourcesPlugin.getWorkspace().getRoot(), listener, true);
}
/**
* 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 and any new
* folders that might be mentioned on the default classpath. The wizard will create the output folder 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 take the default
* @param path The folder to be taken as the default output path or <code>null</code> to take the default
* @return overrideExistingClasspath If set to true, an existing '.classpath' file is ignored. If set to <code>false</code>
* the default classpath 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;
defaultOutputLocation= 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 must not be valid.
*/
public IPath getOutputLocation() {
return fBuildPathsBlock.getOutputLocation();
}
/**
* Returns the currently configured class path. Note that the class path must not be valid.
*/
public IClasspathEntry[] getRawClassPath() {
return fBuildPathsBlock.getRawClassPath();
}
/**
* 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.
*
* @return the runnable
*/
public IRunnableWithProgress getRunnable() {
if (fJavaProject != null) {
return new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
if (monitor == null) {
monitor= new NullProgressMonitor();
}
int nSteps= 10;
monitor.beginTask(NewWizardMessages.getString("JavaCapabilityConfigurationPage.op_desc"), nSteps); //$NON-NLS-1$
try {
IProject project= fJavaProject.getProject();
if (!project.hasNature(JavaCore.NATURE_ID)) {
addNatureToProject(project, JavaCore.NATURE_ID, new SubProgressMonitor(monitor, 1));
nSteps--;
}
// configure the build paths
IRunnableWithProgress jrunnable= fBuildPathsBlock.getRunnable();
jrunnable.run(new SubProgressMonitor(monitor, nSteps));
} catch (CoreException e) {
throw new InvocationTargetException(e);
} finally {
monitor.done();
}
}
};
}
return null;
}
/**
* Adds a nature to a project
*/
private static void addNatureToProject(IProject proj, String natureId, IProgressMonitor monitor) throws CoreException {
IProjectDescription description = proj.getDescription();
String[] prevNatures= description.getNatureIds();
String[] newNatures= new String[prevNatures.length + 1];
System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length);
newNatures[prevNatures.length]= natureId;
description.setNatureIds(newNatures);
proj.setDescription(description, monitor);
}
}
|
14,421 |
Bug 14421 Old .CLASS Files Are Not Deleted
|
When creating a project that does NOT use source folders (and does not use a bin directory for .class files) the .java and .class files are stored together in the Java package structure. When converting a project to use source folders (and the required bin directory for .class files), the old .class files stored in the Java package structure are NEVER DELETED by Eclipse. This is a bug for Eclipse 1.0 and 2.0. Since I use WSDD 4.0 (which is built on Eclipse 1.0), I've seen compilation errors due to the fact that the compiler/JDT is using old .class files rather than the new ones in the project's bin directory. I have not managed to reproduce the compile errors in build 20020416. But since the old .class files should have been deleted this is still a bug for the latest build.
|
resolved fixed
|
1b8c60b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-01T17:19:31Z | 2002-04-23T16:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/wizards/NewJavaProjectWizardPage.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.ui.wizards;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Platform;
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.jface.util.Assert;
import org.eclipse.ui.dialogs.WizardNewProjectCreationPage;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.launching.JavaRuntime;
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 for projects and will configure the project with the
* Java nature. This page also allows the user to configure the Java project's
* output location for class files generated by the Java builder.
* <p>
*/
public class NewJavaProjectWizardPage extends NewElementWizardPage {
private static final String PAGE_NAME= "NewJavaProjectWizardPage"; //$NON-NLS-1$
private WizardNewProjectCreationPage fMainPage;
private IPath fOutputLocation;
private IClasspathEntry[] fClasspathEntries;
private boolean fAddJRE;
private BuildPathsBlock fBuildPathsBlock;
private boolean fProjectModified;
/**
* Creates a Java project wizard creation page.
* <p>
* The Java project wizard reads project name and location from the main page.
* </p>
*
* @param root the workspace root
* @param mainpage the main page of the wizard
*/
public NewJavaProjectWizardPage(IWorkspaceRoot root, WizardNewProjectCreationPage mainpage) {
super(PAGE_NAME);
setTitle(NewWizardMessages.getString("NewJavaProjectWizardPage.title")); //$NON-NLS-1$
setDescription(NewWizardMessages.getString("NewJavaProjectWizardPage.description")); //$NON-NLS-1$
fMainPage= mainpage;
IStatusChangeListener listener= new IStatusChangeListener() {
public void statusChanged(IStatus status) {
updateStatus(status);
}
};
fBuildPathsBlock= new BuildPathsBlock(root, listener, true);
fProjectModified= true;
fOutputLocation= null;
fClasspathEntries= null;
fAddJRE= false;
}
/**
* Sets the default output location to be used for the new Java project.
* This is the path of the folder (with the project) into which the Java builder
* will generate binary class files corresponding to the project's Java source
* files.
* <p>
* The wizard will create this folder if required.
* </p>
* <p>
* The default class path will be applied when <code>initBuildPaths</code> is
* called. This is done automatically when the page becomes visible and
* the project or the default paths have changed.
* </p>
*
* @param path the folder to be taken as the default output path
*/
public void setDefaultOutputFolder(IPath path) {
fOutputLocation= path;
setProjectModified();
}
/**
* Sets the default classpath to be used for the new Java project.
* <p>
* The caller of this method is responsible for creating the classpath entries
* for the <code>IJavaProject</code> that corresponds to the created project.
* The caller is responsible for creating any new folders that might be mentioned
* on the classpath.
* </p>
* <p>
* The default output location will be applied when <code>initBuildPaths</code> is
* called. This is done automatically when the page becomes visible and
* the project or the default paths have changed.
* </p>
*
* @param entries the default classpath entries
* @param appendDefaultJRE <code>true</code> a variable entry for the
* default JRE (specified in the preferences) will be added to the classpath.
*/
public void setDefaultClassPath(IClasspathEntry[] entries, boolean appendDefaultJRE) {
if (entries != null && appendDefaultJRE) {
IClasspathEntry[] newEntries= new IClasspathEntry[entries.length + 1];
System.arraycopy(entries, 0, newEntries, 0, entries.length);
newEntries[entries.length]= JavaRuntime.getJREVariableEntry();
entries= newEntries;
}
fClasspathEntries= entries;
fAddJRE= appendDefaultJRE;
setProjectModified();
}
/**
* Sets the project to modified. This will initialize the page when becomes visible.
*/
public void setProjectModified() {
fProjectModified= true;
}
/**
* Gets the project handle from the main page.
* Overwrite this method if you do not have a main page
*/
protected IProject getProjectHandle() {
Assert.isNotNull(fMainPage);
return fMainPage.getProjectHandle();
}
/**
* Gets the project location path from the main page
* Overwrite this method if you do not have a main page
*/
protected IPath getLocationPath() {
Assert.isNotNull(fMainPage);
return fMainPage.getLocationPath();
}
/**
* Returns the Java project handle corresponding to the project defined in
* in the main page.
*
* @returns the Java project
*/
public IJavaProject getNewJavaProject() {
return JavaCore.create(getProjectHandle());
}
/* (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);
}
/**
* Forces the initialization of the Java project page. Default classpath or buildpath
* will be used if set. The initialization should only be performed when the project
* changed or default paths have changed. Toggeling back and forward the
* pages without changes should not re-initialize the page, as changes
* from the user will be overwritten.
*/
protected void initBuildPaths() {
fBuildPathsBlock.init(getNewJavaProject(), fOutputLocation, fClasspathEntries);
}
/**
* Extend this method to set a user defined default class path or output location.
* <code>initBuildPaths</code> is called when the page becomes visible the first time
* or the project or the default paths have changed.
*/
public void setVisible(boolean visible) {
if (visible) {
// evaluate if a initialization is required
if (fProjectModified || isNewProjectHandle()) {
// only initialize the project when needed
initBuildPaths();
fProjectModified= false;
}
}
super.setVisible(visible);
}
private boolean isNewProjectHandle() {
IProject oldProject= fBuildPathsBlock.getJavaProject().getProject();
return !oldProject.equals(getProjectHandle());
}
/**
* Returns the currently configured output location. Note that the returned path must not be valid.
*/
public IPath getOutputLocation() {
return fBuildPathsBlock.getOutputLocation();
}
/**
* Returns the currently configured class path. Note that the class path must not be valid.
*/
public IClasspathEntry[] getRawClassPath() {
return fBuildPathsBlock.getRawClassPath();
}
/**
* Returns the runnable that will create the Java project.
* The runnable will create and open the project if needed. The runnable will
* add the Java nature to the project, and set the project's classpath and
* output location.
* <p>
* To create the new java project, execute this runnable
* </p>
*
* @return the runnable
*/
public IRunnableWithProgress getRunnable() {
return new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
if (monitor == null) {
monitor= new NullProgressMonitor();
}
monitor.beginTask(NewWizardMessages.getString("NewJavaProjectWizardPage.op_desc"), 10); //$NON-NLS-1$
int workLeft= 10;
// initialize if needed
if (fProjectModified || isNewProjectHandle()) {
initBuildPaths();
}
// create the project
IWorkspace workspace= ResourcesPlugin.getWorkspace();
IProject project= getProjectHandle();
try {
if (!project.exists()) {
IProjectDescription desc= workspace.newProjectDescription(project.getName());
IPath locationPath= getLocationPath();
if (Platform.getLocation().equals(locationPath)) {
locationPath= null;
}
desc.setLocation(locationPath);
project.create(desc, new SubProgressMonitor(monitor, 1));
workLeft--;
}
if (!project.isOpen()) {
project.open(new SubProgressMonitor(monitor, 1));
workLeft--;
}
if (!project.hasNature(JavaCore.NATURE_ID)) {
addNatureToProject(project, JavaCore.NATURE_ID, new SubProgressMonitor(monitor, 1));
workLeft--;
}
IRunnableWithProgress jrunnable= fBuildPathsBlock.getRunnable();
jrunnable.run(new SubProgressMonitor(monitor, workLeft));
} catch (CoreException e) {
throw new InvocationTargetException(e);
} finally {
monitor.done();
}
}
};
}
/**
* Adds a nature to a project
*/
private static void addNatureToProject(IProject proj, String natureId, IProgressMonitor monitor) throws CoreException {
IProjectDescription description = proj.getDescription();
String[] prevNatures= description.getNatureIds();
String[] newNatures= new String[prevNatures.length + 1];
System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length);
newNatures[prevNatures.length]= natureId;
description.setNatureIds(newNatures);
proj.setDescription(description, monitor);
}
}
|
9,159 |
Bug 9159 Classpath wizard should not complain when adding missing source folder
|
Build 20020125 - Define a project A with source folder 'src1'. - Go to the .classpath file and edit it to insert one extra line: <classpathentry kind="src" path="src2"/> below the line referring to first source folder: <classpathentry kind="src" path="src1"/>. - Now, try to add this missing source folder 'src2', it isn't allowed by the wizard, one has to add a basic folder instead. Note: It is not such an uncommon scenario, the classpath modification could simply occur by catching up with a shared classpath having one more source folder on it, and which is locally missing.
|
resolved fixed
|
52b834c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-01T18:04:03Z | 2002-02-06T12:53:20Z |
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.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
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.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.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.operation.IRunnableWithProgress;
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.ElementTreeSelectionDialog;
import org.eclipse.ui.dialogs.ISelectionStatusValidator;
import org.eclipse.ui.dialogs.ListSelectionDialog;
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.JavaConventions;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.launching.JavaRuntime;
import org.eclipse.jdt.internal.corext.javadoc.JavaDocLocations;
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.preferences.JavaBasePreferencePage;
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 {
public static int YES= 0;
public static int NO= 1;
public static int CANCEL= 2;
/**
* Do the callback. Returns YES, NO, CANCEL to decide if .class files should be removed from the
* old output location.
*/
int doQuery(IPath oldOutputLocation);
}
private IWorkspaceRoot fWorkspaceRoot;
private CheckedListDialogField fClassPathList;
private StringButtonDialogField fBuildPathDialogField;
private StatusInfo fClassPathStatus;
private StatusInfo fBuildPathStatus;
private IJavaProject fCurrJProject;
private IPath fOutputLocationPath;
private IStatusChangeListener fContext;
private Control fSWTWidget;
private boolean fShowSourceFolderPage;
private SourceContainerWorkbookPage fSourceContainerPage;
private ProjectsWorkbookPage fProjectsPage;
private LibrariesWorkbookPage fLibrariesPage;
private BuildPathBasePage fCurrPage;
public BuildPathsBlock(IWorkspaceRoot root, IStatusChangeListener context, boolean showSourceFolders) {
fWorkspaceRoot= root;
fContext= context;
fShowSourceFolderPage= showSourceFolders;
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();
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));
folder.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
tabChanged(e.item);
}
});
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));
if (fShowSourceFolderPage) {
folder.setSelection(0);
fCurrPage= fSourceContainerPage;
} else {
folder.setSelection(3);
fCurrPage= ordpage;
fClassPathList.selectFirstElement();
}
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;
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();
}
}
} catch (CoreException e) {
JavaPlugin.log(e.getStatus());
}
if (outputLocation == null) {
outputLocation= getDefaultBuildPath(jproject);
}
List newClassPath;
if (classpathEntries == null) {
newClassPath= getDefaultClassPath(jproject);
} else {
newClassPath= new ArrayList();
for (int i= 0; i < classpathEntries.length; i++) {
IClasspathEntry curr= classpathEntries[i];
int entryKind= curr.getEntryKind();
IPath path= curr.getPath();
boolean isExported= curr.isExported();
// get the resource
IResource res= null;
boolean isMissing= false;
if (entryKind != IClasspathEntry.CPE_VARIABLE) {
res= fWorkspaceRoot.findMember(path);
if (res == null) {
isMissing= (entryKind != IClasspathEntry.CPE_LIBRARY || !path.toFile().isFile());
}
} else {
IPath resolvedPath= JavaCore.getResolvedVariablePath(path);
isMissing= (resolvedPath == null) || !resolvedPath.toFile().isFile();
}
CPListElement elem= new CPListElement(entryKind, path, res, curr.getSourceAttachmentPath(), curr.getSourceAttachmentRootPath(), isExported);
if (projectExists) {
elem.setIsMissing(isMissing);
}
newClassPath.add(elem);
}
}
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());
fClassPathList.setElements(newClassPath);
fClassPathList.setCheckedElements(exportedEntries);
if (fSourceContainerPage != null) {
fSourceContainerPage.init(fCurrJProject);
fProjectsPage.init(fCurrJProject);
fLibrariesPage.init(fCurrJProject);
}
doStatusLineUpdate();
}
// -------- 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;
}
// -------- evaluate default settings --------
private List getDefaultClassPath(IJavaProject jproj) {
List list= new ArrayList();
IResource srcFolder;
if (JavaBasePreferencePage.useSrcAndBinFolders()) {
String sourceFolderName= JavaBasePreferencePage.getSourceFolderName();
srcFolder= jproj.getProject().getFolder(sourceFolderName);
} else {
srcFolder= jproj.getProject();
}
list.add(new CPListElement(IClasspathEntry.CPE_SOURCE, srcFolder.getFullPath(), srcFolder));
IPath libPath= new Path(JavaRuntime.JRELIB_VARIABLE);
IPath attachPath= new Path(JavaRuntime.JRESRC_VARIABLE);
IPath attachRoot= new Path(JavaRuntime.JRESRCROOT_VARIABLE);
CPListElement elem= new CPListElement(IClasspathEntry.CPE_VARIABLE, libPath, null, attachPath, attachRoot, false);
list.add(elem);
return list;
}
private IPath getDefaultBuildPath(IJavaProject jproj) {
if (JavaBasePreferencePage.useSrcAndBinFolders()) {
String outputLocationName= JavaBasePreferencePage.getOutputLocationName();
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();
updateBuildPathStatus();
} else if (field == fBuildPathDialogField) {
updateBuildPathStatus();
}
doStatusLineUpdate();
}
// -------- verification -------------------------------
private void doStatusLineUpdate() {
IStatus res= findMostSevereStatus();
fContext.statusChanged(res);
}
private IStatus findMostSevereStatus() {
return StatusUtil.getMoreSevere(fClassPathStatus, fBuildPathStatus);
}
/**
* Validates the build path.
*/
private void updateClassPathStatus() {
fClassPathStatus.setOK();
List elements= fClassPathList.getElements();
boolean entryMissing= false;
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();
entryMissing= entryMissing || currElement.isMissing();
}
if (entryMissing) {
fClassPathStatus.setWarning(NewWizardMessages.getString("BuildPathsBlock.warning.EntryMissing")); //$NON-NLS-1$
}
if (fCurrJProject.hasClasspathCycle(entries)) {
fClassPathStatus.setWarning(NewWizardMessages.getString("BuildPathsBlock.warning.CycleInClassPath")); //$NON-NLS-1$
}
}
/**
* Validates output location & build path.
*/
private void updateBuildPathStatus() {
fOutputLocationPath= null;
String text= fBuildPathDialogField.getText();
if ("".equals(text)) { //$NON-NLS-1$
fBuildPathStatus.setError(NewWizardMessages.getString("BuildPathsBlock.error.EnterBuildPath")); //$NON-NLS-1$
return;
}
IPath path= getOutputLocation();
IResource res= fWorkspaceRoot.findMember(path);
if (res != null) {
// if exists, must be a folder or project
if (res.getType() == IResource.FILE) {
fBuildPathStatus.setError(NewWizardMessages.getString("BuildPathsBlock.error.InvalidBuildPath")); //$NON-NLS-1$
return;
}
}
fOutputLocationPath= path;
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();
}
IStatus status= JavaConventions.validateClasspath(fCurrJProject, entries, path);
if (!status.isOK()) {
fBuildPathStatus.setError(status.getMessage());
return;
}
if (res != null && res.exists() && fCurrJProject.exists()) {
try {
IPath oldOutputLocation= fCurrJProject.getOutputLocation();
if (!oldOutputLocation.equals(fOutputLocationPath)) {
if (((IContainer)res).members().length > 0) {
fBuildPathStatus.setWarning(NewWizardMessages.getString("BuildPathsBlock.warning.OutputFolderNotEmpty")); //$NON-NLS-1$
return;
}
}
} catch (CoreException e) {
JavaPlugin.log(e);
}
}
fBuildPathStatus.setOK();
}
// -------- creation -------------------------------
/**
* Creates a runnable that sets the configured build paths.
*/
public IRunnableWithProgress getRunnable(final IRemoveOldBinariesQuery reorgQuery) {
final List classPathEntries= fClassPathList.getElements();
final IPath path= getOutputLocation();
return new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
if (monitor == null) {
monitor= new NullProgressMonitor();
}
monitor.beginTask(NewWizardMessages.getString("BuildPathsBlock.operationdesc"), 10); //$NON-NLS-1$
try {
createJavaProject(classPathEntries, path, reorgQuery, monitor);
} catch (CoreException e) {
throw new InvocationTargetException(e);
} finally {
monitor.done();
}
}
};
}
public IRemoveOldBinariesQuery getRemoveOldBinariesQuery(final Shell shell) {
return new IRemoveOldBinariesQuery() {
public int doQuery(final IPath oldOutputLocation) {
final int[] res= new int[] { IRemoveOldBinariesQuery.NO };
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(getShell(), title, null, message, MessageDialog.QUESTION, new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL }, 2);
int returnVal= dialog.open();
if (returnVal == 0) {
res[0]= IRemoveOldBinariesQuery.YES;
} else if (returnVal == 1) {
res[0]= IRemoveOldBinariesQuery.NO;
} else {
res[0]= IRemoveOldBinariesQuery.CANCEL;
}
}
});
return res[0];
}
};
}
/**
* 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 createJavaProject(List classPathEntries, IPath outputLocation, IRemoveOldBinariesQuery reorgQuery, IProgressMonitor monitor) throws CoreException, InterruptedException {
// 10 monitor steps to go
// reomve old .class files
if (reorgQuery != null) {
IPath oldOutputLocation= fCurrJProject.getOutputLocation();
if (fWorkspaceRoot.exists(oldOutputLocation)) {
int result= reorgQuery.doQuery(oldOutputLocation);
if (result == reorgQuery.CANCEL) {
throw new InterruptedException();
} else if (result == reorgQuery.YES) {
removeOldClassfiles(fWorkspaceRoot.findMember(oldOutputLocation));
}
}
}
// 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);
}
classpath[i]= entry.getClasspathEntry();
// set javadoc location
URL javadocLocation= entry.getJavadocLocation();
if (javadocLocation != null) {
IPath path= entry.getPath();
if (entry.getEntryKind() == IClasspathEntry.CPE_VARIABLE) {
path= JavaCore.getResolvedVariablePath(path);
}
if (path != null) {
JavaDocLocations.setLibraryJavadocLocation(path, javadocLocation);
}
}
}
monitor.worked(1);
fCurrJProject.setRawClasspath(classpath, outputLocation, new SubProgressMonitor(monitor, 7));
}
private void removeOldClassfiles(IResource resource) throws CoreException {
if (resource.isDerived() && "class".equals(resource.getFileExtension())) {
resource.delete(false, null);
}
if (resource instanceof IContainer) {
IResource[] members= ((IContainer) resource).members();
for (int i= 0; i < members.length; i++) {
removeOldClassfiles(members[i]);
}
}
}
// ---------- 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);
}
ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(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);
if (dialog.open() == dialog.OK) {
return (IContainer)dialog.getFirstResult();
}
return null;
}
// -------- tab switching ----------
private void tabChanged(Widget widget) {
if (widget instanceof TabItem) {
BuildPathBasePage newPage= (BuildPathBasePage) ((TabItem) widget).getData();
if (fCurrPage != null) {
List selection= fCurrPage.getSelection();
if (!selection.isEmpty()) {
newPage.setSelection(selection);
}
}
fCurrPage= newPage;
}
}
}
|
9,159 |
Bug 9159 Classpath wizard should not complain when adding missing source folder
|
Build 20020125 - Define a project A with source folder 'src1'. - Go to the .classpath file and edit it to insert one extra line: <classpathentry kind="src" path="src2"/> below the line referring to first source folder: <classpathentry kind="src" path="src1"/>. - Now, try to add this missing source folder 'src2', it isn't allowed by the wizard, one has to add a basic folder instead. Note: It is not such an uncommon scenario, the classpath modification could simply occur by catching up with a shared classpath having one more source folder on it, and which is locally missing.
|
resolved fixed
|
52b834c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-01T18:04:03Z | 2002-02-06T12:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/CPListLabelProvider.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.wizards.buildpaths;
import org.eclipse.swt.graphics.Image;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbench;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages;
class CPListLabelProvider extends LabelProvider {
private String fNewLabel, fClassLabel;
private Image fJarIcon, fExtJarIcon, fJarWSrcIcon, fExtJarWSrcIcon;
private Image fFolderImage, fProjectImage, fVariableImage;
private Image fMissingLibaryImage, fMissingVariableImage;
private Image fMissingFolderImage, fMissingProjectImage;
public CPListLabelProvider() {
fNewLabel= NewWizardMessages.getString("CPListLabelProvider.new"); //$NON-NLS-1$
fClassLabel= NewWizardMessages.getString("CPListLabelProvider.classcontainer"); //$NON-NLS-1$
ImageRegistry reg= JavaPlugin.getDefault().getImageRegistry();
fJarIcon= reg.get(JavaPluginImages.IMG_OBJS_JAR);
fExtJarIcon= reg.get(JavaPluginImages.IMG_OBJS_EXTJAR);
fJarWSrcIcon= reg.get(JavaPluginImages.IMG_OBJS_JAR_WSRC);
fExtJarWSrcIcon= reg.get(JavaPluginImages.IMG_OBJS_EXTJAR_WSRC);
fFolderImage= reg.get(JavaPluginImages.IMG_OBJS_PACKFRAG_ROOT);
fVariableImage= reg.get(JavaPluginImages.IMG_OBJS_ENV_VAR);
IWorkbench workbench= JavaPlugin.getDefault().getWorkbench();
fProjectImage= workbench.getSharedImages().getImage(ISharedImages.IMG_OBJ_PROJECT);
fMissingLibaryImage= reg.get(JavaPluginImages.IMG_OBJS_MISSING_JAR);
fMissingVariableImage= reg.get(JavaPluginImages.IMG_OBJS_MISSING_ENV_VAR);
fMissingFolderImage= reg.get(JavaPluginImages.IMG_OBJS_MISSING_PACKFRAG_ROOT);
fMissingProjectImage= workbench.getSharedImages().getImage(ISharedImages.IMG_OBJ_PROJECT_CLOSED);
}
public String getText(Object element) {
if (element instanceof CPListElement) {
CPListElement cpentry= (CPListElement)element;
IPath path= cpentry.getPath();
switch (cpentry.getEntryKind()) {
case IClasspathEntry.CPE_LIBRARY: {
IResource resource= cpentry.getResource();
if (resource instanceof IFolder) {
StringBuffer buf= new StringBuffer(path.makeRelative().toString());
buf.append(' ');
buf.append(fClassLabel);
if (!resource.exists()) {
buf.append(' ');
buf.append(fNewLabel);
}
return buf.toString();
} else if (resource instanceof IFile) {
if (ArchiveFileFilter.isArchivePath(path)) {
String[] args= new String[] { path.lastSegment(), path.removeLastSegments(1).makeRelative().toString() };
return NewWizardMessages.getFormattedString("CPListLabelProvider.twopart", args); //$NON-NLS-1$
}
} else {
if (ArchiveFileFilter.isArchivePath(path)) {
String[] args= new String[] { path.lastSegment(), path.removeLastSegments(1).toOSString() };
return NewWizardMessages.getFormattedString("CPListLabelProvider.twopart", args); //$NON-NLS-1$
}
}
// should not come here
return path.makeRelative().toString();
}
case IClasspathEntry.CPE_VARIABLE: {
String name= path.makeRelative().toString();
StringBuffer buf= new StringBuffer(name);
IPath entryPath= JavaCore.getClasspathVariable(path.segment(0));
if (entryPath != null) {
buf.append(" - "); //$NON-NLS-1$
buf.append(entryPath.append(path.removeFirstSegments(1)).toOSString());
}
return buf.toString();
}
case IClasspathEntry.CPE_PROJECT:
return path.lastSegment();
case IClasspathEntry.CPE_SOURCE: {
StringBuffer buf= new StringBuffer(path.makeRelative().toString());
IResource resource= cpentry.getResource();
if (resource != null && !resource.exists()) {
buf.append(' ');
buf.append(fNewLabel);
}
return buf.toString();
}
default:
// pass
}
}
return super.getText(element);
}
public Image getImage(Object element) {
if (element instanceof CPListElement) {
CPListElement cpentry= (CPListElement)element;
switch (cpentry.getEntryKind()) {
case IClasspathEntry.CPE_SOURCE:
if (!cpentry.isMissing()) {
return fFolderImage;
} else {
return fMissingFolderImage;
}
case IClasspathEntry.CPE_LIBRARY:
if (!cpentry.isMissing()) {
IResource res= cpentry.getResource();
if (res == null) {
if (cpentry.getSourceAttachmentPath() == null) {
return fExtJarIcon;
} else {
return fExtJarWSrcIcon;
}
} else if (res instanceof IFile) {
if (cpentry.getSourceAttachmentPath() == null) {
return fJarIcon;
} else {
return fJarWSrcIcon;
}
} else {
return fFolderImage;
}
} else {
return fMissingLibaryImage;
}
case IClasspathEntry.CPE_PROJECT:
if (!cpentry.isMissing()) {
return fProjectImage;
} else {
return fMissingProjectImage;
}
case IClasspathEntry.CPE_VARIABLE:
if (!cpentry.isMissing()) {
return fVariableImage;
} else {
return fMissingVariableImage;
}
default:
// pass
}
}
return null;
}
}
|
13,034 |
Bug 13034 Cannot create a Source Folder in a new Java Project
|
build 20020404 If you try and create a Source Folder in a Java Project you have just created you get an error preventing you from hitting finish. STEPS 1) Create Java Project Foo 2) Open New->Source Folder 3) Enter Bar as the name - you will get "Cannot nest entry Bar inside entry Foo/Bar" 4) Create a folder Bar. 5) Add it as a source folder in the Properties Dialog for Foo. No problem.
|
resolved fixed
|
1986114
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-02T16:39:00Z | 2002-04-08T21:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/dialogs/StatusUtil.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.dialogs;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.dialogs.DialogPage;
/**
* A utility class to work with IStatus.
*/
public class StatusUtil {
/**
* Compares two instances of <code>IStatus</code>. The more severe is returned:
* An error is more severe than a warning, and a warning is more severe
* than ok. If the two stati have the same severity, the second is returned.
*/
public static IStatus getMoreSevere(IStatus s1, IStatus s2) {
if (s1.getSeverity() > s2.getSeverity()) {
return s1;
} else {
return s2;
}
}
/**
* Finds the most severe status from a array of stati.
* An error is more severe than a warning, and a warning is more severe
* than ok.
*/
public static IStatus getMostSevere(IStatus[] status) {
IStatus max= null;
for (int i= 0; i < status.length; i++) {
IStatus curr= status[i];
if (curr.matches(IStatus.ERROR)) {
return curr;
}
if (max == null || curr.getSeverity() > max.getSeverity()) {
max= curr;
}
}
return max;
}
/**
* Applies the status to the status line of a dialog page.
*/
public static void applyToStatusLine(DialogPage page, IStatus status) {
String message= status.getMessage();
switch (status.getSeverity()) {
case IStatus.OK:
page.setErrorMessage(null);
page.setMessage(message, DialogPage.NONE);
break;
case IStatus.WARNING:
page.setErrorMessage(null);
page.setMessage(message, DialogPage.WARNING);
break;
case IStatus.INFO:
page.setErrorMessage(null);
page.setMessage(message, DialogPage.INFORMATION);
break;
default:
if (message.length() == 0) {
message= null;
}
page.setErrorMessage(message);
page.setMessage(null);
break;
}
}
}
|
13,034 |
Bug 13034 Cannot create a Source Folder in a new Java Project
|
build 20020404 If you try and create a Source Folder in a Java Project you have just created you get an error preventing you from hitting finish. STEPS 1) Create Java Project Foo 2) Open New->Source Folder 3) Enter Bar as the name - you will get "Cannot nest entry Bar inside entry Foo/Bar" 4) Create a folder Bar. 5) Add it as a source folder in the Properties Dialog for Foo. No problem.
|
resolved fixed
|
1986114
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-02T16:39:00Z | 2002-04-08T21:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/NewSourceFolderWizardPage.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.wizards;
import java.lang.reflect.InvocationTargetException;
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.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.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.Shell;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.ui.actions.WorkspaceModifyDelegatingOperation;
import org.eclipse.ui.dialogs.ElementListSelectionDialog;
import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
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.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.JavaConventions;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.ui.wizards.NewElementWizardPage;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.dialogs.StatusDialog;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.util.CoreUtility;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.wizards.buildpaths.BuildPathsBlock;
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.Separator;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField;
public class NewSourceFolderWizardPage extends NewElementWizardPage {
private static final String PAGE_NAME= "NewSourceFolderWizardPage"; //$NON-NLS-1$
private StringButtonDialogField fProjectField;
private StatusInfo fProjectStatus;
private StringButtonDialogField fRootDialogField;
private StatusInfo fRootStatus;
private SelectionButtonDialogField fEditClassPathField;
private IWorkspaceRoot fWorkspaceRoot;
private IJavaProject fCurrJProject;
private IClasspathEntry[] fEntries;
private IPath fOutputLocation;
private IPackageFragmentRoot fCreatedRoot;
public NewSourceFolderWizardPage() {
super(PAGE_NAME);
setTitle(NewWizardMessages.getString("NewSourceFolderWizardPage.title")); //$NON-NLS-1$
setDescription(NewWizardMessages.getString("NewSourceFolderWizardPage.description")); //$NON-NLS-1$
fWorkspaceRoot= ResourcesPlugin.getWorkspace().getRoot();
RootFieldAdapter adapter= new RootFieldAdapter();
fProjectField= new StringButtonDialogField(adapter);
fProjectField.setDialogFieldListener(adapter);
fProjectField.setLabelText(NewWizardMessages.getString("NewSourceFolderWizardPage.project.label")); //$NON-NLS-1$
fProjectField.setButtonLabel(NewWizardMessages.getString("NewSourceFolderWizardPage.project.button")); //$NON-NLS-1$
fRootDialogField= new StringButtonDialogField(adapter);
fRootDialogField.setDialogFieldListener(adapter);
fRootDialogField.setLabelText(NewWizardMessages.getString("NewSourceFolderWizardPage.root.label")); //$NON-NLS-1$
fRootDialogField.setButtonLabel(NewWizardMessages.getString("NewSourceFolderWizardPage.root.button")); //$NON-NLS-1$
fEditClassPathField= new SelectionButtonDialogField(SWT.PUSH);
fEditClassPathField.setDialogFieldListener(adapter);
fEditClassPathField.setLabelText(NewWizardMessages.getString("NewSourceFolderWizardPage.editclasspath.button")); //$NON-NLS-1$
fRootStatus= new StatusInfo();
fProjectStatus= new StatusInfo();
}
// -------- Initialization ---------
public void init(IStructuredSelection selection) {
if (selection == null || selection.isEmpty()) {
setDefaultAttributes();
return;
}
Object selectedElement= selection.getFirstElement();
if (selectedElement == null) {
selectedElement= EditorUtility.getActiveEditorJavaInput();
}
String projPath= null;
if (selectedElement instanceof IResource) {
IProject proj= ((IResource)selectedElement).getProject();
if (proj != null) {
projPath= proj.getFullPath().makeRelative().toString();
}
} else if (selectedElement instanceof IJavaElement) {
IJavaProject jproject= ((IJavaElement)selectedElement).getJavaProject();
if (jproject != null) {
projPath= jproject.getProject().getFullPath().makeRelative().toString();
}
}
if (projPath != null) {
fProjectField.setText(projPath);
fRootDialogField.setText(""); //$NON-NLS-1$
} else {
setDefaultAttributes();
}
}
private void setDefaultAttributes() {
String projPath= ""; //$NON-NLS-1$
try {
// find the first java project
IProject[] projects= fWorkspaceRoot.getProjects();
for (int i= 0; i < projects.length; i++) {
IProject proj= projects[i];
if (proj.hasNature(JavaCore.NATURE_ID)) {
projPath= proj.getFullPath().makeRelative().toString();
break;
}
}
} catch (CoreException e) {
// ignore here
}
fProjectField.setText(projPath);
fRootDialogField.setText(""); //$NON-NLS-1$
}
// -------- UI Creation ---------
/**
* @see WizardPage#createControl
*/
public void createControl(Composite parent) {
initializeDialogUnits(parent);
Composite composite= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
layout.marginWidth= 0;
layout.marginHeight= 0;
layout.numColumns= 3;
composite.setLayout(layout);
fProjectField.doFillIntoGrid(composite, 3);
fRootDialogField.doFillIntoGrid(composite, 3);
fRootDialogField.setFocus();
int maxFieldWidth= convertWidthInCharsToPixels(40);
LayoutUtil.setWidthHint(fProjectField.getTextControl(null), maxFieldWidth);
LayoutUtil.setHorizontalGrabbing(fProjectField.getTextControl(null));
LayoutUtil.setWidthHint(fRootDialogField.getTextControl(null), maxFieldWidth);
(new Separator()).doFillIntoGrid(composite, 3);
fEditClassPathField.doFillIntoGrid(composite, 3);
Control control= fEditClassPathField.getSelectionButton(null);
GridData gd= (GridData) control.getLayoutData();
gd.verticalAlignment= GridData.END;
gd.horizontalAlignment= GridData.BEGINNING;
setControl(composite);
WorkbenchHelp.setHelp(composite, IJavaHelpContextIds.NEW_PACKAGEROOT_WIZARD_PAGE);
}
// -------- ContainerFieldAdapter --------
private class RootFieldAdapter implements IStringButtonAdapter, IDialogFieldListener {
// -------- IStringButtonAdapter
public void changeControlPressed(DialogField field) {
packRootChangeControlPressed(field);
}
// -------- IDialogFieldListener
public void dialogFieldChanged(DialogField field) {
packRootDialogFieldChanged(field);
}
}
private void packRootChangeControlPressed(DialogField field) {
if (field == fRootDialogField) {
IFolder folder= chooseFolder();
if (folder != null) {
IPath path= folder.getFullPath().removeFirstSegments(1);
fRootDialogField.setText(path.toString());
}
} else if (field == fProjectField) {
IJavaProject jproject= chooseProject();
if (jproject != null) {
IPath path= jproject.getProject().getFullPath().makeRelative();
fProjectField.setText(path.toString());
}
}
}
private void packRootDialogFieldChanged(DialogField field) {
if (field == fRootDialogField) {
updateRootStatus();
} else if (field == fProjectField) {
updateProjectStatus();
updateRootStatus();
} else if (field == fEditClassPathField) {
if (showClassPathPropertyPage()) {
updateProjectStatus();
updateRootStatus();
}
}
updateStatus(new IStatus[] { fProjectStatus, fRootStatus });
}
private void updateProjectStatus() {
fCurrJProject= null;
String str= fProjectField.getText();
if (str.length() == 0) {
fProjectStatus.setError(NewWizardMessages.getString("NewSourceFolderWizardPage.error.EnterProjectName")); //$NON-NLS-1$
return;
}
IPath path= new Path(str);
if (path.segmentCount() != 1) {
fProjectStatus.setError(NewWizardMessages.getString("NewSourceFolderWizardPage.error.InvalidProjectPath")); //$NON-NLS-1$
return;
}
IProject project= fWorkspaceRoot.getProject(path.toString());
if (!project.exists()) {
fProjectStatus.setError(NewWizardMessages.getString("NewSourceFolderWizardPage.error.ProjectNotExists")); //$NON-NLS-1$
return;
}
try {
if (project.hasNature(JavaCore.NATURE_ID)) {
fCurrJProject= JavaCore.create(project);
fEntries= fCurrJProject.getRawClasspath();
fOutputLocation= fCurrJProject.getOutputLocation();
fProjectStatus.setOK();
return;
}
} catch (CoreException e) {
JavaPlugin.log(e);
fCurrJProject= null;
}
fProjectStatus.setError(NewWizardMessages.getString("NewSourceFolderWizardPage.error.NotAJavaProject")); //$NON-NLS-1$
}
private void updateRootStatus() {
fRootDialogField.enableButton(fCurrJProject != null);
if (fCurrJProject == null) {
return;
}
String str= fRootDialogField.getText();
if (str.length() == 0) {
fRootStatus.setError(NewWizardMessages.getFormattedString("NewSourceFolderWizardPage.error.EnterRootName", fCurrJProject.getProject().getFullPath().toString())); //$NON-NLS-1$
} else {
IPath path= fCurrJProject.getProject().getFullPath().append(str);
if (!fWorkspaceRoot.getWorkspace().validatePath(path.toString(), IResource.FOLDER).isOK()) {
fRootStatus.setError(NewWizardMessages.getString("NewSourceFolderWizardPage.error.InvalidRootName")); //$NON-NLS-1$
} else {
IResource res= fWorkspaceRoot.findMember(path);
if (res != null) {
if (res.getType() != IResource.FOLDER) {
fRootStatus.setError(NewWizardMessages.getString("NewSourceFolderWizardPage.error.NotAFolder")); //$NON-NLS-1$
return;
}
}
IClasspathEntry[] newEntries= new IClasspathEntry[fEntries.length + 1];
for (int i= 0; i < fEntries.length; i++) {
IClasspathEntry curr= fEntries[i];
if (curr.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
if (path.equals(curr.getPath())) {
fRootStatus.setError(NewWizardMessages.getString("NewSourceFolderWizardPage.error.AlreadyExisting")); //$NON-NLS-1$
return;
}
}
newEntries[i]= curr;
}
newEntries[fEntries.length]= JavaCore.newSourceEntry(path);
IStatus status= JavaConventions.validateClasspath(fCurrJProject, newEntries, fOutputLocation);
if (!status.isOK()) {
fRootStatus.setError(status.getMessage());
return;
}
fRootStatus.setOK();
}
}
}
// ---- creation ----------------
/**
* @see NewElementWizardPage#getRunnable
*/
public IRunnableWithProgress getRunnable() {
return new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException {
try {
fCreatedRoot= createPackageFragmentRoot(monitor, getShell());
} catch (CoreException e) {
throw new InvocationTargetException(e);
}
}
};
}
protected IPackageFragmentRoot getNewPackageFragmentRoot() {
return fCreatedRoot;
}
protected IPackageFragmentRoot createPackageFragmentRoot(IProgressMonitor monitor, Shell shell) throws CoreException {
String relPath= fRootDialogField.getText();
IFolder folder= fCurrJProject.getProject().getFolder(relPath);
IPath path= folder.getFullPath();
if (!folder.exists()) {
CoreUtility.createFolder(folder, true, true, monitor);
}
IClasspathEntry[] entries= fCurrJProject.getRawClasspath();
IClasspathEntry[] newEntries= new IClasspathEntry[entries.length + 1];
for (int i= entries.length - 1, k= entries.length; i >= 0; i--) {
IClasspathEntry curr= entries[i];
if (k > i && curr.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
newEntries[k--]= JavaCore.newSourceEntry(path);
}
newEntries[k--]= curr;
}
fCurrJProject.setRawClasspath(newEntries, monitor);
return fCurrJProject.getPackageFragmentRoot(folder);
}
// ------------- choose dialogs
private IFolder chooseFolder() {
Class[] acceptedClasses= new Class[] { IFolder.class };
ISelectionStatusValidator validator= new TypedElementSelectionValidator(acceptedClasses, false);
Object[] notWanted= getFilteredExistingContainerEntries();
ViewerFilter filter= new TypedViewerFilter(acceptedClasses, notWanted);
ILabelProvider lp= new WorkbenchLabelProvider();
ITreeContentProvider cp= new WorkbenchContentProvider();
ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), lp, cp);
dialog.setValidator(validator);
dialog.setTitle(NewWizardMessages.getString("NewSourceFolderWizardPage.ChooseExistingRootDialog.title")); //$NON-NLS-1$
dialog.setMessage(NewWizardMessages.getString("NewSourceFolderWizardPage.ChooseExistingRootDialog.description")); //$NON-NLS-1$
dialog.addFilter(filter);
dialog.setInput(fCurrJProject.getProject());
IResource res= fWorkspaceRoot.findMember(new Path(fRootDialogField.getText()));
if (res != null) {
dialog.setInitialSelection(res);
}
if (dialog.open() == dialog.OK) {
return (IFolder) dialog.getFirstResult();
}
return null;
}
private IJavaProject chooseProject() {
IJavaProject[] projects;
try {
projects= JavaCore.create(fWorkspaceRoot).getJavaProjects();
} catch (JavaModelException e) {
JavaPlugin.log(e);
projects= new IJavaProject[0];
}
ILabelProvider labelProvider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT);
ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), labelProvider);
dialog.setTitle(NewWizardMessages.getString("NewSourceFolderWizardPage.ChooseProjectDialog.title")); //$NON-NLS-1$
dialog.setMessage(NewWizardMessages.getString("NewSourceFolderWizardPage.ChooseProjectDialog.description")); //$NON-NLS-1$
dialog.setElements(projects);
dialog.setInitialSelections(new Object[] { fCurrJProject });
if (dialog.open() == dialog.OK) {
return (IJavaProject) dialog.getFirstResult();
}
return null;
}
// a dialog containing the class path dialog
private class EditClassPathDialog extends StatusDialog implements IStatusChangeListener {
private BuildPathsBlock fBuildPathsBlock;
public EditClassPathDialog(Shell parent) {
super(parent);
fBuildPathsBlock= new BuildPathsBlock(fWorkspaceRoot, this, false);
}
public void create() {
super.create();
fBuildPathsBlock.init(fCurrJProject, null, null);
}
protected Control createDialogArea(Composite parent) {
Composite composite= (Composite)super.createDialogArea(parent);
Control inner= fBuildPathsBlock.createControl(composite);
inner.setLayoutData(new org.eclipse.swt.layout.GridData(org.eclipse.swt.layout.GridData.FILL_BOTH));
return composite;
}
public void statusChanged(IStatus status) {
updateStatus(status);
}
protected void buttonPressed(int buttonId) {
if (buttonId == IDialogConstants.OK_ID) {
IRunnableWithProgress runnable= fBuildPathsBlock.getRunnable(fBuildPathsBlock.getRemoveOldBinariesQuery(getShell()));
if (invokeRunnable(runnable)) {
setReturnCode(OK);
} else {
setReturnCode(CANCEL);
}
}
close();
}
private boolean invokeRunnable(IRunnableWithProgress runnable) {
IRunnableWithProgress op= new WorkspaceModifyDelegatingOperation(runnable);
try {
getWizard().getContainer().run(false, true, op);
} catch (InvocationTargetException e) {
Shell shell= getShell();
String title= NewWizardMessages.getString("NewSourceFolderWizardPage.op_error.title"); //$NON-NLS-1$
String message= NewWizardMessages.getString("NewSourceFolderWizardPage.op_error.message"); //$NON-NLS-1$
ExceptionHandler.handle(e, shell, title, message);
return false;
} catch (InterruptedException e) {
return false;
}
return true;
}
}
private boolean showClassPathPropertyPage() {
EditClassPathDialog dialog= new EditClassPathDialog(getShell());
dialog.setTitle(NewWizardMessages.getString("NewSourceFolderWizardPage.EditClassPathDialog.title")); //$NON-NLS-1$
return (dialog.open() == EditClassPathDialog.OK);
}
private IContainer[] getFilteredExistingContainerEntries() {
if (fCurrJProject == null) {
return new IContainer[0];
}
List res= new ArrayList();
try {
IResource container= fWorkspaceRoot.findMember(fCurrJProject.getOutputLocation());
if (container != null) {
res.add(container);
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
for (int i= 0; i < fEntries.length; i++) {
IClasspathEntry elem= fEntries[i];
if (elem.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
IResource container= fWorkspaceRoot.findMember(elem.getPath());
if (container != null) {
res.add(container);
}
}
}
return (IContainer[]) res.toArray(new IContainer[res.size()]);
}
}
|
13,034 |
Bug 13034 Cannot create a Source Folder in a new Java Project
|
build 20020404 If you try and create a Source Folder in a Java Project you have just created you get an error preventing you from hitting finish. STEPS 1) Create Java Project Foo 2) Open New->Source Folder 3) Enter Bar as the name - you will get "Cannot nest entry Bar inside entry Foo/Bar" 4) Create a folder Bar. 5) Add it as a source folder in the Properties Dialog for Foo. No problem.
|
resolved fixed
|
1986114
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-02T16:39:00Z | 2002-04-08T21:06: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.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
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.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.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.operation.IRunnableWithProgress;
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.ElementTreeSelectionDialog;
import org.eclipse.ui.dialogs.ISelectionStatusValidator;
import org.eclipse.ui.dialogs.ListSelectionDialog;
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.JavaConventions;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.launching.JavaRuntime;
import org.eclipse.jdt.internal.corext.javadoc.JavaDocLocations;
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.preferences.JavaBasePreferencePage;
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 {
public static int YES= 0;
public static int NO= 1;
public static int CANCEL= 2;
/**
* Do the callback. Returns YES, NO, CANCEL to decide if .class files should be removed from the
* old output location.
*/
int doQuery(IPath oldOutputLocation);
}
private IWorkspaceRoot fWorkspaceRoot;
private CheckedListDialogField fClassPathList;
private StringButtonDialogField fBuildPathDialogField;
private StatusInfo fClassPathStatus;
private StatusInfo fBuildPathStatus;
private IJavaProject fCurrJProject;
private IPath fOutputLocationPath;
private IStatusChangeListener fContext;
private Control fSWTWidget;
private boolean fShowSourceFolderPage;
private SourceContainerWorkbookPage fSourceContainerPage;
private ProjectsWorkbookPage fProjectsPage;
private LibrariesWorkbookPage fLibrariesPage;
private BuildPathBasePage fCurrPage;
public BuildPathsBlock(IWorkspaceRoot root, IStatusChangeListener context, boolean showSourceFolders) {
fWorkspaceRoot= root;
fContext= context;
fShowSourceFolderPage= showSourceFolders;
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();
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));
folder.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
tabChanged(e.item);
}
});
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));
if (fShowSourceFolderPage) {
folder.setSelection(0);
fCurrPage= fSourceContainerPage;
} else {
folder.setSelection(3);
fCurrPage= ordpage;
fClassPathList.selectFirstElement();
}
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;
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();
}
}
} catch (CoreException e) {
JavaPlugin.log(e.getStatus());
}
if (outputLocation == null) {
outputLocation= getDefaultBuildPath(jproject);
}
List newClassPath;
if (classpathEntries == null) {
newClassPath= getDefaultClassPath(jproject);
} else {
newClassPath= new ArrayList();
for (int i= 0; i < classpathEntries.length; i++) {
IClasspathEntry curr= classpathEntries[i];
int entryKind= curr.getEntryKind();
IPath path= curr.getPath();
boolean isExported= curr.isExported();
// get the resource
IResource res= null;
boolean isMissing= false;
IPath resolvedPath= path;
if (entryKind == IClasspathEntry.CPE_VARIABLE) {
resolvedPath= JavaCore.getResolvedVariablePath(path);
}
res= fWorkspaceRoot.findMember(resolvedPath);
if (res == null) {
if (entryKind == IClasspathEntry.CPE_LIBRARY) {
isMissing= !resolvedPath.toFile().isFile(); // look for external JARs
if (!ArchiveFileFilter.isArchivePath(resolvedPath)) {
if (fWorkspaceRoot.getWorkspace().validatePath(resolvedPath.toString(), IResource.FOLDER).isOK()) {
res= fWorkspaceRoot.getFolder(resolvedPath);
}
}
} else if (entryKind == IClasspathEntry.CPE_SOURCE) {
isMissing= true;
if (fWorkspaceRoot.getWorkspace().validatePath(resolvedPath.toString(), IResource.FOLDER).isOK()) {
res= fWorkspaceRoot.getFolder(resolvedPath);
}
}
}
CPListElement elem= new CPListElement(entryKind, path, res, curr.getSourceAttachmentPath(), curr.getSourceAttachmentRootPath(), isExported);
if (projectExists) {
elem.setIsMissing(isMissing);
}
newClassPath.add(elem);
}
}
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());
fClassPathList.setElements(newClassPath);
fClassPathList.setCheckedElements(exportedEntries);
if (fSourceContainerPage != null) {
fSourceContainerPage.init(fCurrJProject);
fProjectsPage.init(fCurrJProject);
fLibrariesPage.init(fCurrJProject);
}
doStatusLineUpdate();
}
// -------- 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;
}
// -------- evaluate default settings --------
private List getDefaultClassPath(IJavaProject jproj) {
List list= new ArrayList();
IResource srcFolder;
if (JavaBasePreferencePage.useSrcAndBinFolders()) {
String sourceFolderName= JavaBasePreferencePage.getSourceFolderName();
srcFolder= jproj.getProject().getFolder(sourceFolderName);
} else {
srcFolder= jproj.getProject();
}
list.add(new CPListElement(IClasspathEntry.CPE_SOURCE, srcFolder.getFullPath(), srcFolder));
IPath libPath= new Path(JavaRuntime.JRELIB_VARIABLE);
IPath attachPath= new Path(JavaRuntime.JRESRC_VARIABLE);
IPath attachRoot= new Path(JavaRuntime.JRESRCROOT_VARIABLE);
CPListElement elem= new CPListElement(IClasspathEntry.CPE_VARIABLE, libPath, null, attachPath, attachRoot, false);
list.add(elem);
return list;
}
private IPath getDefaultBuildPath(IJavaProject jproj) {
if (JavaBasePreferencePage.useSrcAndBinFolders()) {
String outputLocationName= JavaBasePreferencePage.getOutputLocationName();
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();
updateBuildPathStatus();
} else if (field == fBuildPathDialogField) {
updateBuildPathStatus();
}
doStatusLineUpdate();
}
// -------- verification -------------------------------
private void doStatusLineUpdate() {
IStatus res= findMostSevereStatus();
fContext.statusChanged(res);
}
private IStatus findMostSevereStatus() {
return StatusUtil.getMoreSevere(fClassPathStatus, fBuildPathStatus);
}
/**
* Validates the build path.
*/
private void updateClassPathStatus() {
fClassPathStatus.setOK();
List elements= fClassPathList.getElements();
boolean entryMissing= false;
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();
entryMissing= entryMissing || currElement.isMissing();
}
if (entryMissing) {
fClassPathStatus.setWarning(NewWizardMessages.getString("BuildPathsBlock.warning.EntryMissing")); //$NON-NLS-1$
}
if (fCurrJProject.hasClasspathCycle(entries)) {
fClassPathStatus.setWarning(NewWizardMessages.getString("BuildPathsBlock.warning.CycleInClassPath")); //$NON-NLS-1$
}
}
/**
* Validates output location & build path.
*/
private void updateBuildPathStatus() {
fOutputLocationPath= null;
String text= fBuildPathDialogField.getText();
if ("".equals(text)) { //$NON-NLS-1$
fBuildPathStatus.setError(NewWizardMessages.getString("BuildPathsBlock.error.EnterBuildPath")); //$NON-NLS-1$
return;
}
IPath path= getOutputLocation();
IResource res= fWorkspaceRoot.findMember(path);
if (res != null) {
// if exists, must be a folder or project
if (res.getType() == IResource.FILE) {
fBuildPathStatus.setError(NewWizardMessages.getString("BuildPathsBlock.error.InvalidBuildPath")); //$NON-NLS-1$
return;
}
}
fOutputLocationPath= path;
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();
}
IStatus status= JavaConventions.validateClasspath(fCurrJProject, entries, path);
if (!status.isOK()) {
fBuildPathStatus.setError(status.getMessage());
return;
}
if (res != null && res.exists() && fCurrJProject.exists()) {
try {
IPath oldOutputLocation= fCurrJProject.getOutputLocation();
if (!oldOutputLocation.equals(fOutputLocationPath)) {
if (((IContainer)res).members().length > 0) {
fBuildPathStatus.setWarning(NewWizardMessages.getString("BuildPathsBlock.warning.OutputFolderNotEmpty")); //$NON-NLS-1$
return;
}
}
} catch (CoreException e) {
JavaPlugin.log(e);
}
}
fBuildPathStatus.setOK();
}
// -------- creation -------------------------------
/**
* Creates a runnable that sets the configured build paths.
*/
public IRunnableWithProgress getRunnable(final IRemoveOldBinariesQuery reorgQuery) {
final List classPathEntries= fClassPathList.getElements();
final IPath path= getOutputLocation();
return new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
if (monitor == null) {
monitor= new NullProgressMonitor();
}
monitor.beginTask(NewWizardMessages.getString("BuildPathsBlock.operationdesc"), 10); //$NON-NLS-1$
try {
createJavaProject(classPathEntries, path, reorgQuery, monitor);
} catch (CoreException e) {
throw new InvocationTargetException(e);
} finally {
monitor.done();
}
}
};
}
public IRemoveOldBinariesQuery getRemoveOldBinariesQuery(final Shell shell) {
return new IRemoveOldBinariesQuery() {
public int doQuery(final IPath oldOutputLocation) {
final int[] res= new int[] { IRemoveOldBinariesQuery.NO };
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(getShell(), title, null, message, MessageDialog.QUESTION, new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL }, 2);
int returnVal= dialog.open();
if (returnVal == 0) {
res[0]= IRemoveOldBinariesQuery.YES;
} else if (returnVal == 1) {
res[0]= IRemoveOldBinariesQuery.NO;
} else {
res[0]= IRemoveOldBinariesQuery.CANCEL;
}
}
});
return res[0];
}
};
}
/**
* 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 createJavaProject(List classPathEntries, IPath outputLocation, IRemoveOldBinariesQuery reorgQuery, IProgressMonitor monitor) throws CoreException, InterruptedException {
// 10 monitor steps to go
// 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)) {
int result= reorgQuery.doQuery(oldOutputLocation);
if (result == reorgQuery.CANCEL) {
throw new InterruptedException();
} else if (result == reorgQuery.YES) {
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);
}
classpath[i]= entry.getClasspathEntry();
// set javadoc location
URL javadocLocation= entry.getJavadocLocation();
if (javadocLocation != null) {
IPath path= entry.getPath();
if (entry.getEntryKind() == IClasspathEntry.CPE_VARIABLE) {
path= JavaCore.getResolvedVariablePath(path);
}
if (path != null) {
JavaDocLocations.setLibraryJavadocLocation(path, javadocLocation);
}
}
}
monitor.worked(1);
fCurrJProject.setRawClasspath(classpath, outputLocation, new SubProgressMonitor(monitor, 7));
}
private boolean hasClassfiles(IResource resource) throws CoreException {
if (resource.isDerived() && "class".equals(resource.getFileExtension())) {
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;
}
private void removeOldClassfiles(IResource resource) throws CoreException {
if (resource.isDerived() && "class".equals(resource.getFileExtension())) {
resource.delete(false, null);
}
if (resource instanceof IContainer) {
IResource[] members= ((IContainer) resource).members();
for (int i= 0; i < members.length; i++) {
removeOldClassfiles(members[i]);
}
}
}
// ---------- 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);
}
ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(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);
if (dialog.open() == dialog.OK) {
return (IContainer)dialog.getFirstResult();
}
return null;
}
// -------- tab switching ----------
private void tabChanged(Widget widget) {
if (widget instanceof TabItem) {
BuildPathBasePage newPage= (BuildPathBasePage) ((TabItem) widget).getData();
if (fCurrPage != null) {
List selection= fCurrPage.getSelection();
if (!selection.isEmpty()) {
newPage.setSelection(selection);
}
}
fCurrPage= newPage;
}
}
}
|
15,152 |
Bug 15152 Java Editor no longer displays external source
|
When I set a source lookup path to lookup source for a Junit test in "junit3.7src.zip", the java editor is not properly created: To recreate: (1) Create a launch config for "VectorTests" (2) On the "Source" tab of the launch config, remove the "JUnit" project and add an external jar. Select "junit3.7src.zip" in the file system. (3) Debug to a breakpoint - get the following error: !MESSAGE Problems occurred when invoking code from plug-in: org.eclipse.ui. !STACK java.lang.NullPointerException at org.eclipse.jdt.internal.corext.util.JavaModelUtil.isEditable (JavaModelUtil.java:461) at org.eclipse.jdt.ui.actions.OrganizeImportsAction.selectionChanged (OrganizeImportsAction.java:114) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchSelectionChanged (SelectionDispatchAction.java:125) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.update (SelectionDispatchAction.java:118) at org.eclipse.jdt.ui.actions.GenerateActionGroup.<init> (GenerateActionGroup.java:74) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor.createActions (CompilationUnitEditor.java:500) at org.eclipse.ui.texteditor.AbstractTextEditor.createPartControl (AbstractTextEditor.java:1265) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor.createPartControl (CompilationUnitEditor.java:1105) at org.eclipse.ui.internal.PartPane$4.run(PartPane.java:128) at org.eclipse.core.internal.runtime.InternalPlatform.run (InternalPlatform.java:791) at org.eclipse.core.runtime.Platform.run(Platform.java:411) at org.eclipse.ui.internal.PartPane.createChildControl (PartPane.java:126) at org.eclipse.ui.internal.PartPane.createControl(PartPane.java:168) at org.eclipse.ui.internal.EditorWorkbook.createPage (EditorWorkbook.java:229) at org.eclipse.ui.internal.EditorWorkbook.add(EditorWorkbook.java:84) at org.eclipse.ui.internal.EditorArea.addEditor(EditorArea.java:43) at org.eclipse.ui.internal.EditorPresentation.openEditor (EditorPresentation.java:309) at org.eclipse.ui.internal.EditorManager$2.run(EditorManager.java:468) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:56) at org.eclipse.ui.internal.EditorManager.openInternalEditor (EditorManager.java:460) at org.eclipse.ui.internal.EditorManager.openInternalEditor (EditorManager.java:529) at org.eclipse.ui.internal.EditorManager.openEditor (EditorManager.java:361) at org.eclipse.ui.internal.EditorManager.openEditor (EditorManager.java:264) at org.eclipse.ui.internal.WorkbenchPage.openEditor (WorkbenchPage.java:1617) at org.eclipse.ui.internal.WorkbenchPage.openEditor (WorkbenchPage.java:1587) at org.eclipse.debug.internal.ui.views.LaunchView.openEditor (LaunchView.java:589) at org.eclipse.debug.internal.ui.views.LaunchView.openEditorAndSetMarker (LaunchView.java:564) at org.eclipse.debug.internal.ui.views.LaunchView.showMarkerForCurrentSelection (LaunchView.java:458) at org.eclipse.debug.internal.ui.views.LaunchView.selectionChanged (LaunchView.java:295) at org.eclipse.jface.viewers.Viewer.fireSelectionChanged (Viewer.java:147) at org.eclipse.jface.viewers.StructuredViewer.updateSelection (StructuredViewer.java:1064) at org.eclipse.jface.viewers.StructuredViewer.setSelection (StructuredViewer.java:813) at org.eclipse.debug.internal.ui.views.LaunchView.autoExpand (LaunchView.java:729) at org.eclipse.debug.internal.ui.views.LaunchViewEventHandler.doHandleSuspendThread Event(LaunchViewEventHandler.java:220) at org.eclipse.debug.internal.ui.views.LaunchViewEventHandler.doHandleSuspendEvent (LaunchViewEventHandler.java:175) at org.eclipse.debug.internal.ui.views.LaunchViewEventHandler.doHandleDebugEvents (LaunchViewEventHandler.java:95) at org.eclipse.debug.internal.ui.views.AbstractDebugEventHandler$1.run (AbstractDebugEventHandler.java:49) at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:29) at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages (Synchronizer.java:93) at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:1389) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1211) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:883) at org.eclipse.ui.internal.Workbench.run(Workbench.java:866) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:733) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at EclipseRuntimeLauncher.main(EclipseRuntimeLauncher.java:16) !ENTRY org.eclipse.core.resources 1 4 Thu May 02 16:45:57 CDT 2002 !MESSAGE Unhandled exception caught in event loop. !ENTRY org.eclipse.ui 4 0 Thu May 02 16:45:57 CDT 2002 !MESSAGE Failed to execute runnable (java.lang.NullPointerException) !STACK org.eclipse.swt.SWTException: Failed to execute runnable (java.lang.NullPointerException) at org.eclipse.swt.SWT.error(SWT.java:1887) at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages (Synchronizer.java:96) at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:1389) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1211) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:883) at org.eclipse.ui.internal.Workbench.run(Workbench.java:866) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:733) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at EclipseRuntimeLauncher.main(EclipseRuntimeLauncher.java:16) !ENTRY org.eclipse.core.resources 1 4 Thu May 02 16:45:57 CDT 2002 !MESSAGE *** Stack trace of contained exception *** !ENTRY org.eclipse.ui 4 0 Thu May 02 16:45:57 CDT 2002 !MESSAGE java.lang.NullPointerException !STACK java.lang.NullPointerException at org.eclipse.ui.texteditor.AbstractTextEditor.selectAndReveal (AbstractTextEditor.java:2749) at org.eclipse.ui.texteditor.AbstractTextEditor.gotoMarker (AbstractTextEditor.java:2633) at org.eclipse.debug.internal.ui.views.LaunchView.openEditorAndSetMarker (LaunchView.java:583) at org.eclipse.debug.internal.ui.views.LaunchView.showMarkerForCurrentSelection (LaunchView.java:458) at org.eclipse.debug.internal.ui.views.LaunchView.selectionChanged (LaunchView.java:295) at org.eclipse.jface.viewers.Viewer.fireSelectionChanged (Viewer.java:147) at org.eclipse.jface.viewers.StructuredViewer.updateSelection (StructuredViewer.java:1064) at org.eclipse.jface.viewers.StructuredViewer.setSelection (StructuredViewer.java:813) at org.eclipse.debug.internal.ui.views.LaunchView.autoExpand (LaunchView.java:729) at org.eclipse.debug.internal.ui.views.LaunchViewEventHandler.doHandleSuspendThread Event(LaunchViewEventHandler.java:220) at org.eclipse.debug.internal.ui.views.LaunchViewEventHandler.doHandleSuspendEvent (LaunchViewEventHandler.java:175) at org.eclipse.debug.internal.ui.views.LaunchViewEventHandler.doHandleDebugEvents (LaunchViewEventHandler.java:95) at org.eclipse.debug.internal.ui.views.AbstractDebugEventHandler$1.run (AbstractDebugEventHandler.java:49) at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:29) at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages (Synchronizer.java:93) at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:1389) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1211) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:883) at org.eclipse.ui.internal.Workbench.run(Workbench.java:866) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:733) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at EclipseRuntimeLauncher.main(EclipseRuntimeLauncher.java:16)
|
resolved fixed
|
e5eda0b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-03T07:19:50Z | 2002-05-02T22:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/AddImportOnSelectionAction.java
|
package org.eclipse.jdt.internal.ui.javaeditor;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.dialogs.ElementListSelectionDialog;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.ui.texteditor.IUpdate;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.core.search.IJavaSearchConstants;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.ITypeNameRequestor;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.ui.IWorkingCopyManager;
import org.eclipse.jdt.internal.corext.codemanipulation.AddImportsOperation;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.corext.util.TypeInfo;
import org.eclipse.jdt.internal.corext.util.TypeInfoRequestor;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.util.TypeInfoLabelProvider;
public class AddImportOnSelectionAction extends Action implements IUpdate {
private ITextEditor fEditor;
public AddImportOnSelectionAction(ITextEditor editor) {
super(JavaEditorMessages.getString("AddImportOnSelection.label")); //$NON-NLS-1$
setToolTipText(JavaEditorMessages.getString("AddImportOnSelection.tooltip")); //$NON-NLS-1$
setDescription(JavaEditorMessages.getString("AddImportOnSelection.description")); //$NON-NLS-1$
fEditor= editor;
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.ADD_IMPORT_ON_SELECTION_ACTION);
}
public AddImportOnSelectionAction() {
this(null);
}
public void setContentEditor(ITextEditor editor) {
fEditor= editor;
}
public void update() {
boolean isEnabled= false;
try {
ISelection selection= fEditor.getSelectionProvider().getSelection();
isEnabled= (selection instanceof ITextSelection && JavaModelUtil.isEditable(getCompilationUnit()));
} catch(JavaModelException e) {
}
setEnabled(isEnabled);
}
private ICompilationUnit getCompilationUnit () {
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
return manager.getWorkingCopy(fEditor.getEditorInput());
}
/**
* @see IAction#actionPerformed
*/
public void run() {
ICompilationUnit cu= getCompilationUnit();
if (cu != null) {
ISelection s= fEditor.getSelectionProvider().getSelection();
IDocument doc= fEditor.getDocumentProvider().getDocument(fEditor.getEditorInput());
ITextSelection selection= (ITextSelection) s;
if (doc != null) {
try {
int nameStart= getNameStart(doc, selection.getOffset());
int nameEnd= getNameEnd(doc, selection.getOffset() + selection.getLength());
int len= nameEnd - nameStart;
String name= doc.get(nameStart, len).trim();
String simpleName= Signature.getSimpleName(name);
String containerName= Signature.getQualifier(name);
IImportDeclaration existingImport= JavaModelUtil.findImport(cu, simpleName);
if (existingImport != null) {
if (!existingImport.getElementName().equals(name)) {
getShell().getDisplay().beep();
}
return;
}
IJavaSearchScope searchScope= SearchEngine.createJavaSearchScope(new IJavaElement[] { cu.getJavaProject() });
TypeInfo[] types= findAllTypes(simpleName, searchScope, null);
if (types.length== 0) {
getShell().getDisplay().beep();
return;
}
TypeInfo chosen= selectResult(types, containerName, getShell());
if (chosen == null) {
return;
}
IType type= chosen.resolveType(searchScope);
if (type == null) {
JavaPlugin.logErrorMessage("AddImportOnSelectionAction: Failed to resolve TypeRef: " + chosen.toString()); //$NON-NLS-1$
MessageDialog.openError(getShell(), JavaEditorMessages.getString("AddImportOnSelection.error.title"), JavaEditorMessages.getString("AddImportOnSelection.error.notresolved.message")); //$NON-NLS-1$ //$NON-NLS-2$
return;
}
removeQualification(doc, nameStart, chosen);
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
AddImportsOperation op= new AddImportsOperation(cu, new IJavaElement[] { type }, settings, false);
ProgressMonitorDialog dialog= new ProgressMonitorDialog(getShell());
try {
dialog.run(false, true, new WorkbenchRunnableAdapter(op));
} catch (InvocationTargetException e) {
JavaPlugin.log(e);
MessageDialog.openError(getShell(), JavaEditorMessages.getString("AddImportOnSelection.error.title"), e.getTargetException().getMessage()); //$NON-NLS-1$
} catch (InterruptedException e) {
// Do nothing. Operation has been canceled.
}
return;
} catch (CoreException e) {
JavaPlugin.log(e);
ErrorDialog.openError(getShell(), JavaEditorMessages.getString("AddImportOnSelection.error.title"), null, e.getStatus()); //$NON-NLS-1$
} catch (BadLocationException e) {
JavaPlugin.log(e);
MessageDialog.openError(getShell(), JavaEditorMessages.getString("AddImportOnSelection.error.title"), e.getMessage()); //$NON-NLS-1$
}
}
}
}
private int getNameStart(IDocument doc, int pos) throws BadLocationException {
while (pos > 0) {
char ch= doc.getChar(pos - 1);
if (!Character.isJavaIdentifierPart(ch) && ch != '.') {
return pos;
}
pos--;
}
return pos;
}
private int getNameEnd(IDocument doc, int pos) throws BadLocationException {
int len= doc.getLength();
while (pos < len) {
char ch= doc.getChar(pos);
if (!Character.isJavaIdentifierPart(ch)) {
return pos;
}
pos++;
}
return pos;
}
private void removeQualification(IDocument doc, int nameStart, TypeInfo typeInfo) throws BadLocationException {
String containerName= typeInfo.getTypeContainerName();
int containerLen= containerName.length();
if (containerLen > 0) {
for (int k= 0; k < containerLen; k++) {
if (doc.getChar(nameStart + k) != containerName.charAt(k)) {
return;
}
}
doc.replace(nameStart, containerLen + 1, ""); //$NON-NLS-1$
}
}
/**
* Finds a type by the simple name.
*/
private static TypeInfo[] findAllTypes(String simpleTypeName, IJavaSearchScope searchScope, IProgressMonitor monitor) throws CoreException {
SearchEngine searchEngine= new SearchEngine();
ArrayList typeRefsFound= new ArrayList(10);
ITypeNameRequestor requestor= new TypeInfoRequestor(typeRefsFound);
searchEngine.searchAllTypeNames(
JavaPlugin.getWorkspace(),
null,
simpleTypeName.toCharArray(),
IJavaSearchConstants.EXACT_MATCH,
IJavaSearchConstants.CASE_SENSITIVE,
IJavaSearchConstants.TYPE,
searchScope,
requestor,
IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH,
monitor);
return (TypeInfo[]) typeRefsFound.toArray(new TypeInfo[typeRefsFound.size()]);
}
private Shell getShell() {
return fEditor.getSite().getShell();
}
private TypeInfo selectResult(TypeInfo[] results, String containerName, Shell shell) {
int nResults= results.length;
if (nResults == 0) {
return null;
} else if (nResults == 1) {
return results[0];
}
if (containerName.length() != 0) {
for (int i= 0; i < nResults; i++) {
TypeInfo curr= (TypeInfo) results[i];
if (containerName.equals(curr.getTypeContainerName())) {
return curr;
}
}
}
ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), new TypeInfoLabelProvider(TypeInfoLabelProvider.SHOW_FULLYQUALIFIED));
dialog.setTitle(JavaEditorMessages.getString("AddImportOnSelection.dialog.title")); //$NON-NLS-1$
dialog.setMessage(JavaEditorMessages.getString("AddImportOnSelection.dialog.message")); //$NON-NLS-1$
dialog.setElements(results);
if (dialog.open() == dialog.OK) {
return (TypeInfo) dialog.getFirstResult();
}
return null;
}
}
|
15,152 |
Bug 15152 Java Editor no longer displays external source
|
When I set a source lookup path to lookup source for a Junit test in "junit3.7src.zip", the java editor is not properly created: To recreate: (1) Create a launch config for "VectorTests" (2) On the "Source" tab of the launch config, remove the "JUnit" project and add an external jar. Select "junit3.7src.zip" in the file system. (3) Debug to a breakpoint - get the following error: !MESSAGE Problems occurred when invoking code from plug-in: org.eclipse.ui. !STACK java.lang.NullPointerException at org.eclipse.jdt.internal.corext.util.JavaModelUtil.isEditable (JavaModelUtil.java:461) at org.eclipse.jdt.ui.actions.OrganizeImportsAction.selectionChanged (OrganizeImportsAction.java:114) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchSelectionChanged (SelectionDispatchAction.java:125) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.update (SelectionDispatchAction.java:118) at org.eclipse.jdt.ui.actions.GenerateActionGroup.<init> (GenerateActionGroup.java:74) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor.createActions (CompilationUnitEditor.java:500) at org.eclipse.ui.texteditor.AbstractTextEditor.createPartControl (AbstractTextEditor.java:1265) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor.createPartControl (CompilationUnitEditor.java:1105) at org.eclipse.ui.internal.PartPane$4.run(PartPane.java:128) at org.eclipse.core.internal.runtime.InternalPlatform.run (InternalPlatform.java:791) at org.eclipse.core.runtime.Platform.run(Platform.java:411) at org.eclipse.ui.internal.PartPane.createChildControl (PartPane.java:126) at org.eclipse.ui.internal.PartPane.createControl(PartPane.java:168) at org.eclipse.ui.internal.EditorWorkbook.createPage (EditorWorkbook.java:229) at org.eclipse.ui.internal.EditorWorkbook.add(EditorWorkbook.java:84) at org.eclipse.ui.internal.EditorArea.addEditor(EditorArea.java:43) at org.eclipse.ui.internal.EditorPresentation.openEditor (EditorPresentation.java:309) at org.eclipse.ui.internal.EditorManager$2.run(EditorManager.java:468) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:56) at org.eclipse.ui.internal.EditorManager.openInternalEditor (EditorManager.java:460) at org.eclipse.ui.internal.EditorManager.openInternalEditor (EditorManager.java:529) at org.eclipse.ui.internal.EditorManager.openEditor (EditorManager.java:361) at org.eclipse.ui.internal.EditorManager.openEditor (EditorManager.java:264) at org.eclipse.ui.internal.WorkbenchPage.openEditor (WorkbenchPage.java:1617) at org.eclipse.ui.internal.WorkbenchPage.openEditor (WorkbenchPage.java:1587) at org.eclipse.debug.internal.ui.views.LaunchView.openEditor (LaunchView.java:589) at org.eclipse.debug.internal.ui.views.LaunchView.openEditorAndSetMarker (LaunchView.java:564) at org.eclipse.debug.internal.ui.views.LaunchView.showMarkerForCurrentSelection (LaunchView.java:458) at org.eclipse.debug.internal.ui.views.LaunchView.selectionChanged (LaunchView.java:295) at org.eclipse.jface.viewers.Viewer.fireSelectionChanged (Viewer.java:147) at org.eclipse.jface.viewers.StructuredViewer.updateSelection (StructuredViewer.java:1064) at org.eclipse.jface.viewers.StructuredViewer.setSelection (StructuredViewer.java:813) at org.eclipse.debug.internal.ui.views.LaunchView.autoExpand (LaunchView.java:729) at org.eclipse.debug.internal.ui.views.LaunchViewEventHandler.doHandleSuspendThread Event(LaunchViewEventHandler.java:220) at org.eclipse.debug.internal.ui.views.LaunchViewEventHandler.doHandleSuspendEvent (LaunchViewEventHandler.java:175) at org.eclipse.debug.internal.ui.views.LaunchViewEventHandler.doHandleDebugEvents (LaunchViewEventHandler.java:95) at org.eclipse.debug.internal.ui.views.AbstractDebugEventHandler$1.run (AbstractDebugEventHandler.java:49) at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:29) at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages (Synchronizer.java:93) at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:1389) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1211) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:883) at org.eclipse.ui.internal.Workbench.run(Workbench.java:866) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:733) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at EclipseRuntimeLauncher.main(EclipseRuntimeLauncher.java:16) !ENTRY org.eclipse.core.resources 1 4 Thu May 02 16:45:57 CDT 2002 !MESSAGE Unhandled exception caught in event loop. !ENTRY org.eclipse.ui 4 0 Thu May 02 16:45:57 CDT 2002 !MESSAGE Failed to execute runnable (java.lang.NullPointerException) !STACK org.eclipse.swt.SWTException: Failed to execute runnable (java.lang.NullPointerException) at org.eclipse.swt.SWT.error(SWT.java:1887) at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages (Synchronizer.java:96) at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:1389) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1211) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:883) at org.eclipse.ui.internal.Workbench.run(Workbench.java:866) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:733) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at EclipseRuntimeLauncher.main(EclipseRuntimeLauncher.java:16) !ENTRY org.eclipse.core.resources 1 4 Thu May 02 16:45:57 CDT 2002 !MESSAGE *** Stack trace of contained exception *** !ENTRY org.eclipse.ui 4 0 Thu May 02 16:45:57 CDT 2002 !MESSAGE java.lang.NullPointerException !STACK java.lang.NullPointerException at org.eclipse.ui.texteditor.AbstractTextEditor.selectAndReveal (AbstractTextEditor.java:2749) at org.eclipse.ui.texteditor.AbstractTextEditor.gotoMarker (AbstractTextEditor.java:2633) at org.eclipse.debug.internal.ui.views.LaunchView.openEditorAndSetMarker (LaunchView.java:583) at org.eclipse.debug.internal.ui.views.LaunchView.showMarkerForCurrentSelection (LaunchView.java:458) at org.eclipse.debug.internal.ui.views.LaunchView.selectionChanged (LaunchView.java:295) at org.eclipse.jface.viewers.Viewer.fireSelectionChanged (Viewer.java:147) at org.eclipse.jface.viewers.StructuredViewer.updateSelection (StructuredViewer.java:1064) at org.eclipse.jface.viewers.StructuredViewer.setSelection (StructuredViewer.java:813) at org.eclipse.debug.internal.ui.views.LaunchView.autoExpand (LaunchView.java:729) at org.eclipse.debug.internal.ui.views.LaunchViewEventHandler.doHandleSuspendThread Event(LaunchViewEventHandler.java:220) at org.eclipse.debug.internal.ui.views.LaunchViewEventHandler.doHandleSuspendEvent (LaunchViewEventHandler.java:175) at org.eclipse.debug.internal.ui.views.LaunchViewEventHandler.doHandleDebugEvents (LaunchViewEventHandler.java:95) at org.eclipse.debug.internal.ui.views.AbstractDebugEventHandler$1.run (AbstractDebugEventHandler.java:49) at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:29) at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages (Synchronizer.java:93) at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:1389) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1211) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:883) at org.eclipse.ui.internal.Workbench.run(Workbench.java:866) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:733) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at EclipseRuntimeLauncher.main(EclipseRuntimeLauncher.java:16)
|
resolved fixed
|
e5eda0b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-03T07:19:50Z | 2002-05-02T22:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/OrganizeImportsAction.java
|
package org.eclipse.jdt.ui.actions;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.HashSet;
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.operation.IRunnableWithProgress;
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.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.IPackageFragment;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.IWorkingCopyManager;
import org.eclipse.jdt.ui.JavaUI;
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.ImportOrganizePreferencePage;
import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.util.TypeInfoLabelProvider;
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);
}
}
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);
}
/**
* Creates a new <code>OrganizeImportsAction</code>.
* <p>
* Note: This constructor is for internal use only. Clients should not call this constructor.
* </p>
*/
public OrganizeImportsAction(JavaEditor editor) {
this(editor.getEditorSite());
fEditor= editor;
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
protected void selectionChanged(ITextSelection selection) {
boolean isEnabled= false;
try {
if (fEditor != null) {
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
ICompilationUnit cu= manager.getWorkingCopy(fEditor.getEditorInput());
isEnabled= JavaModelUtil.isEditable(cu);
}
} catch (JavaModelException e) {
}
setEnabled(isEnabled);
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
protected void selectionChanged(IStructuredSelection selection) {
ICompilationUnit[] cus= getCompilationUnits(selection);
boolean isEnabled= cus.length > 0;
try {
for (int i= 0; i < cus.length; i++) {
if (!JavaModelUtil.isEditable(cus[i])) {
isEnabled= false;
break;
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
setEnabled(isEnabled);
}
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:
IPackageFragment pack= (IPackageFragment) elem;
result.addAll(Arrays.asList(pack.getCompilationUnits()));
break;
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
return (ICompilationUnit[]) result.toArray(new ICompilationUnit[result.size()]);
}
/* (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);
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
protected void run(IStructuredSelection selection) {
ICompilationUnit[] cus= getCompilationUnits(selection);
if (cus.length == 1) {
runOnSingle(cus[0], true);
} 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 IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
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 InterruptedException {
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 {
String[] prefOrder= ImportOrganizePreferencePage.getImportOrderPreference();
int threshold= ImportOrganizePreferencePage.getImportNumberThreshold();
boolean ignoreLowerCaseNames= ImportOrganizePreferencePage.doIgnoreLowerCaseNames();
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];
try {
if (!cu.isWorkingCopy()) {
ICompilationUnit workingCopy= EditorUtility.getWorkingCopy(cu);
if (workingCopy != null) {
cu= workingCopy;
}
}
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, prefOrder, threshold, ignoreLowerCaseNames, !cu.isWorkingCopy(), doResolve, query);
op.run(new SubProgressMonitor(monitor, 1));
ISourceRange errorRange= op.getErrorSourceRange();
if (errorRange != null) {
String message= ActionMessages.getFormattedString("OrganizeImportsAction.multi.error.parse", cu.getElementName()); //$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", cu.getElementName()); //$NON-NLS-1$
status.add(new Status(Status.INFO, JavaUI.ID_PLUGIN, Status.ERROR, message, null));
} catch (CoreException e) {
JavaPlugin.log(e);
String message= ActionMessages.getFormattedString("OrganizeImportsAction.multi.error.unexpected", e.getMessage()); //$NON-NLS-1$
status.add(new Status(Status.ERROR, JavaUI.ID_PLUGIN, Status.ERROR, message, null));
} catch (OperationCanceledException e) {
throw new InterruptedException();
}
}
} finally {
monitor.done();
}
}
private void runOnSingle(ICompilationUnit cu, boolean doResolve) {
try {
String[] prefOrder= ImportOrganizePreferencePage.getImportOrderPreference();
int threshold= ImportOrganizePreferencePage.getImportNumberThreshold();
boolean ignoreLowerCaseNames= ImportOrganizePreferencePage.doIgnoreLowerCaseNames();
if (!cu.isWorkingCopy()) {
IEditorPart editor= EditorUtility.openInEditor(cu);
if (editor instanceof JavaEditor) {
fEditor= (JavaEditor) editor;
}
ICompilationUnit workingCopy= EditorUtility.getWorkingCopy(cu);
if (workingCopy != null) {
cu= workingCopy;
}
}
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() == dialog.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);
}
}
}
|
14,531 |
Bug 14531 Unable to use JarPackager headless
|
Beginning with the 04/23 Integration build, I am unable to utilize the JarPackager in a headless environment. Specifically, I have defined my own Ant tasks which perform operations including jar packaging. The problem is in JarFileExportOperation.getDirtyEditors(Shell parent). Is it possible to accept null for parent and have the method just return an empty array?
|
resolved fixed
|
5188c99
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-03T07:26:44Z | 2002-04-24T17:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/jarpackager/JarFileExportOperation.java
|
/*
* (c) Copyright IBM Corp. 2000, 2002.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.jarpackager;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.Manifest;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceDescription;
import org.eclipse.core.resources.IncrementalProjectBuilder;
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.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.operation.ModalContext;
import org.eclipse.jface.util.Assert;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaModelMarker;
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.JavaModelException;
import org.eclipse.jdt.ui.jarpackager.IJarDescriptionWriter;
import org.eclipse.jdt.ui.jarpackager.IJarExportRunnable;
import org.eclipse.jdt.ui.jarpackager.JarPackageData;
import org.eclipse.jdt.ui.jarpackager.JarWriter;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaStatusConstants;
import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext;
/**
* Operation for exporting a resource and its children to a new JAR file.
*/
public class JarFileExportOperation implements IJarExportRunnable {
private static class MessageMultiStatus extends MultiStatus {
MessageMultiStatus(String pluginId, int code, String message, Throwable exception) {
super(pluginId, code, message, exception);
}
/*
* allows to change the message
*/
protected void setMessage(String message) {
super.setMessage(message);
}
}
private static final String COMPILER_SOURCE_FILE_ATTR = "org.eclipse.jdt.core.compiler.debug.sourceFile"; //$NON-NLS-1$
private JarWriter fJarWriter;
private JarPackageData fJarPackage;
private JarPackageData[] fJarPackages;
private Shell fParentShell;
private Map fJavaNameToClassFilesMap;
private IContainer fClassFilesMapContainer;
private Set fExportedClassContainers;
private MessageMultiStatus fStatus;
/**
* Creates an instance of this class.
*
* @param jarPackage the JAR package specification
* @param parent the parent for the dialog,
* or <code>null</code> if no dialog should be presented
*/
public JarFileExportOperation(JarPackageData jarPackage, Shell parent) {
this(new JarPackageData[] {jarPackage}, parent);
}
/**
* Creates an instance of this class.
*
* @param jarPackages an array with JAR package data objects
* @param parent the parent for the dialog,
* or <code>null</code> if no dialog should be presented
*/
public JarFileExportOperation(JarPackageData[] jarPackages, Shell parent) {
this(parent);
fJarPackages= jarPackages;
}
private JarFileExportOperation(Shell parent) {
fParentShell= parent;
fStatus= new MessageMultiStatus(JavaPlugin.getPluginId(), IStatus.OK, "", null); //$NON-NLS-1$
}
protected void addToStatus(CoreException ex) {
IStatus status= ex.getStatus();
String message= ex.getLocalizedMessage();
if (message == null || message.length() < 1) {
message= JarPackagerMessages.getString("JarFileExportOperation.coreErrorDuringExport"); //$NON-NLS-1$
status= new Status(status.getSeverity(), status.getPlugin(), status.getCode(), message, ex);
}
fStatus.add(status);
}
/**
* Adds a new warning to the list with the passed information.
* Normally the export operation continues after a warning.
* @param message the message
* @param exception the throwable that caused the warning, or <code>null</code>
*/
protected void addWarning(String message, Throwable error) {
fStatus.add(new Status(IStatus.WARNING, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, message, error));
}
/**
* Adds a new error to the list with the passed information.
* Normally an error terminates the export operation.
* @param message the message
* @param exception the throwable that caused the error, or <code>null</code>
*/
protected void addError(String message, Throwable error) {
fStatus.add(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, message, error));
}
/**
* Answers the number of file resources specified by the JAR package.
*
* @return int
*/
protected int countSelectedElements() {
int count= 0;
int n= fJarPackage.getElements().length;
for (int i= 0; i < n; i++) {
Object element= fJarPackage.getElements()[i];
IResource resource= null;
if (element instanceof IJavaElement) {
IJavaElement je= (IJavaElement)element;
try {
resource= je.getUnderlyingResource();
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.underlyingResourceNotFound", je.getElementName()), ex); //$NON-NLS-1$
return count;
}
}
else
resource= (IResource)element;
if (resource.getType() == IResource.FILE)
count++;
else
count += getTotalChildCount((IContainer)resource);
}
return count;
}
private int getTotalChildCount(IContainer container) {
IResource[] members;
try {
members= container.members();
} catch (CoreException ex) {
return 0;
}
int count= 0;
for (int i= 0; i < members.length; i++) {
if (members[i].getType() == IResource.FILE)
count++;
else
count += getTotalChildCount((IContainer)members[i]);
}
return count;
}
/**
* Exports the passed resource to the JAR file
*
* @param element the resource or JavaElement to export
*/
protected void exportElement(Object element, IProgressMonitor progressMonitor) throws InterruptedException {
int leadSegmentsToRemove= 1;
IPackageFragmentRoot pkgRoot= null;
boolean isInJavaProject= false;
IResource resource= null;
IJavaProject jProject= null;
if (element instanceof IJavaElement) {
isInJavaProject= true;
IJavaElement je= (IJavaElement)element;
try {
resource= je.getUnderlyingResource();
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.underlyingResourceNotFound", je.getElementName()), ex); //$NON-NLS-1$
return;
}
jProject= je.getJavaProject();
pkgRoot= JavaModelUtil.getPackageFragmentRoot(je);
}
else
resource= (IResource)element;
if (!resource.isAccessible()) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.resourceNotFound", resource.getFullPath()), null); //$NON-NLS-1$
return;
}
if (resource.getType() == IResource.FILE) {
if (!resource.isLocal(IResource.DEPTH_ZERO))
try {
resource.setLocal(true , IResource.DEPTH_ZERO, progressMonitor);
} catch (CoreException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.resourceNotLocal", resource.getFullPath()), ex); //$NON-NLS-1$
return;
}
if (!isInJavaProject) {
// check if it's a Java resource
try {
isInJavaProject= resource.getProject().hasNature(JavaCore.NATURE_ID);
} catch (CoreException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.projectNatureNotDeterminable", resource.getFullPath()), ex); //$NON-NLS-1$
return;
}
if (isInJavaProject) {
jProject= JavaCore.create(resource.getProject());
try {
IPackageFragment pkgFragment= jProject.findPackageFragment(resource.getFullPath().removeLastSegments(1));
if (pkgFragment != null)
pkgRoot= JavaModelUtil.getPackageFragmentRoot(pkgFragment);
else
pkgRoot= findPackageFragmentRoot(jProject, resource.getFullPath().removeLastSegments(1));
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.javaPackageNotDeterminable", resource.getFullPath()), ex); //$NON-NLS-1$
return;
}
}
}
if (pkgRoot != null) {
leadSegmentsToRemove= pkgRoot.getPath().segmentCount();
if (mustUseSourceFolderHierarchy() && !pkgRoot.getElementName().equals(pkgRoot.DEFAULT_PACKAGEROOT_PATH))
leadSegmentsToRemove--;
}
IPath destinationPath= resource.getFullPath().removeFirstSegments(leadSegmentsToRemove);
boolean isInOutputFolder= false;
if (isInJavaProject) {
try {
isInOutputFolder= jProject.getOutputLocation().isPrefixOf(resource.getFullPath());
} catch (JavaModelException ex) {
isInOutputFolder= false;
}
}
exportClassFiles(progressMonitor, pkgRoot, resource, jProject, destinationPath);
exportResource(progressMonitor, pkgRoot, isInJavaProject, resource, destinationPath, isInOutputFolder);
progressMonitor.worked(1);
ModalContext.checkCanceled(progressMonitor);
} else if (element instanceof IPackageFragment)
exportPackageFragment(progressMonitor, (IPackageFragment)element);
else
exportContainer(progressMonitor, (IContainer)resource);
}
private void exportPackageFragment(IProgressMonitor progressMonitor, IPackageFragment pkgFragment) throws java.lang.InterruptedException {
Object[] children;
try {
children= pkgFragment.getChildren();
for (int i= 0; i < children.length; i++)
exportElement(children[i], progressMonitor);
children= pkgFragment.getNonJavaResources();
for (int i= 0; i < children.length; i++)
exportElement(children[i], progressMonitor);
} catch (CoreException e) {
// this should never happen because an #isAccessible check is done before #members is invoked
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.errorDuringExport", pkgFragment.toString()), e); //$NON-NLS-1$
}
}
private void exportContainer(IProgressMonitor progressMonitor, IContainer container) throws java.lang.InterruptedException {
if (container.getType() == IResource.FOLDER && isOutputFolder((IFolder)container))
return;
IResource[] children= null;
try {
children= container.members();
} catch (CoreException e) {
// this should never happen because an #isAccessible check is done before #members is invoked
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.errorDuringExport", container.getFullPath()), e); //$NON-NLS-1$
}
for (int i= 0; i < children.length; i++)
exportElement(children[i], progressMonitor);
}
private IPackageFragmentRoot findPackageFragmentRoot(IJavaProject jProject, IPath path) throws JavaModelException {
if (jProject == null || path == null || path.segmentCount() <= 0)
return null;
IPackageFragmentRoot pkgRoot= jProject.findPackageFragmentRoot(path);
if (pkgRoot != null)
return pkgRoot;
else
return findPackageFragmentRoot(jProject, path.removeLastSegments(1));
}
private void exportResource(IProgressMonitor progressMonitor, IPackageFragmentRoot pkgRoot, boolean isInJavaProject, IResource resource, IPath destinationPath, boolean isInOutputFolder) {
boolean isNonJavaResource= !isInJavaProject || pkgRoot == null;
boolean isInClassFolder= false;
try {
isInClassFolder= pkgRoot != null && !pkgRoot.isArchive() && pkgRoot.getKind() == pkgRoot.K_BINARY;
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.cantGetRootKind", resource.getFullPath()), ex); //$NON-NLS-1$
}
if ((fJarPackage.areClassFilesExported() &&
((isNonJavaResource || (pkgRoot != null && !isJavaFile(resource) && !isClassFile(resource)))
|| isInClassFolder && isClassFile(resource)))
|| (fJarPackage.areJavaFilesExported() && (isNonJavaResource || (pkgRoot != null && !isClassFile(resource))))) {
try {
progressMonitor.subTask(JarPackagerMessages.getFormattedString("JarFileExportOperation.exporting", destinationPath.toString())); //$NON-NLS-1$
fJarWriter.write((IFile) resource, destinationPath);
} catch (CoreException ex) {
addToStatus(ex);
}
}
}
private boolean isOutputFolder(IFolder folder) {
try {
IJavaProject javaProject= JavaCore.create(folder.getProject());
IPath outputFolderPath= javaProject.getOutputLocation();
return folder.getFullPath().equals(outputFolderPath);
} catch (JavaModelException ex) {
return false;
}
}
private void exportClassFiles(IProgressMonitor progressMonitor, IPackageFragmentRoot pkgRoot, IResource resource, IJavaProject jProject, IPath destinationPath) {
if (fJarPackage.areClassFilesExported() && isJavaFile(resource) && pkgRoot != null) {
try {
// find corresponding file(s) on classpath and export
Iterator iter= filesOnClasspath((IFile)resource, destinationPath, jProject, progressMonitor);
IPath baseDestinationPath= destinationPath.removeLastSegments(1);
while (iter.hasNext()) {
IFile file= (IFile)iter.next();
if (!resource.isLocal(IResource.DEPTH_ZERO))
file.setLocal(true , IResource.DEPTH_ZERO, progressMonitor);
IPath classFilePath= baseDestinationPath.append(file.getName());
progressMonitor.subTask(JarPackagerMessages.getFormattedString("JarFileExportOperation.exporting", classFilePath.toString())); //$NON-NLS-1$
fJarWriter.write(file, classFilePath);
}
} catch (CoreException ex) {
addToStatus(ex);
}
}
}
/**
* Exports the resources as specified by the JAR package.
*/
protected void exportSelectedElements(IProgressMonitor progressMonitor) throws InterruptedException {
fExportedClassContainers= new HashSet(10);
int n= fJarPackage.getElements().length;
for (int i= 0; i < n; i++)
exportElement(fJarPackage.getElements()[i], progressMonitor);
}
/**
* Returns an iterator on a list with files that correspond to the
* passed file and that are on the classpath of its project.
*
* @param file the file for which to find the corresponding classpath resources
* @param pathInJar the path that the file has in the JAR (i.e. project and source folder segments removed)
* @param javaProject the javaProject that contains the file
* @return the iterator over the corresponding classpath files for the given file
*/
protected Iterator filesOnClasspath(IFile file, IPath pathInJar, IJavaProject javaProject, IProgressMonitor progressMonitor) throws CoreException {
// Allow JAR Package to provide its own strategy
IFile[] classFiles= fJarPackage.findClassfilesFor(file);
if (classFiles != null)
return Arrays.asList(classFiles).iterator();
if (!isJavaFile(file))
return Collections.EMPTY_LIST.iterator();
IPath outputPath= javaProject.getOutputLocation();
IContainer outputContainer;
if (javaProject.getProject().getFullPath().equals(outputPath))
outputContainer= javaProject.getProject();
else {
outputContainer= createFolderHandle(outputPath);
if (outputContainer == null || !outputContainer.isAccessible()) {
String msg= JarPackagerMessages.getString("JarFileExportOperation.outputContainerNotAccessible"); //$NON-NLS-1$
throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, msg, null));
}
}
// Java CU - search files with .class ending
boolean hasErrors= hasCompileErrors(file);
boolean hasWarnings= hasCompileWarnings(file);
boolean canBeExported= canBeExported(hasErrors, hasWarnings);
if (!canBeExported)
return Collections.EMPTY_LIST.iterator();
reportPossibleCompileProblems(file, hasErrors, hasWarnings, canBeExported);
IContainer classContainer= outputContainer;
if (pathInJar.segmentCount() > 1)
classContainer= outputContainer.getFolder(pathInJar.removeLastSegments(1));
if (fExportedClassContainers.contains(classContainer))
return Collections.EMPTY_LIST.iterator();
if (fClassFilesMapContainer == null || !fClassFilesMapContainer.equals(classContainer)) {
fJavaNameToClassFilesMap= buildJavaToClassMap(classContainer);
if (fJavaNameToClassFilesMap == null) {
// Could not fully build map. fallback is to export whole directory
String msg= JarPackagerMessages.getFormattedString("JarFileExportOperation.missingSourceFileAttributeExportedAll", classContainer.getLocation().toFile()); //$NON-NLS-1$
addWarning(msg, null);
fExportedClassContainers.add(classContainer);
return getClassesIn(classContainer);
}
fClassFilesMapContainer= classContainer;
}
ArrayList classFileList= (ArrayList)fJavaNameToClassFilesMap.get(file.getName());
if (classFileList == null || classFileList.isEmpty()) {
String msg= JarPackagerMessages.getFormattedString("JarFileExportOperation.classFileOnClasspathNotAccessible", file.getFullPath()); //$NON-NLS-1$
throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, msg, null));
}
return classFileList.iterator();
}
private Iterator getClassesIn(IContainer classContainer) throws CoreException {
IResource[] resources= classContainer.members();
List files= new ArrayList(resources.length);
for (int i= 0; i < resources.length; i++)
if (resources[i].getType() == IResource.FILE && isClassFile(resources[i]))
files.add(resources[i]);
return files.iterator();
}
/**
* Answers whether the given resource is a Java file.
* The resource must be a file whose file name ends with ".java".
*
* @return a <code>true<code> if the given resource is a Java file
*/
boolean isJavaFile(IResource file) {
return file != null
&& file.getType() == IFile.FILE
&& file.getFileExtension() != null
&& file.getFileExtension().equalsIgnoreCase("java"); //$NON-NLS-1$
}
/**
* Answers whether the given resource is a class file.
* The resource must be a file whose file name ends with ".class".
*
* @return a <code>true<code> if the given resource is a class file
*/
boolean isClassFile(IResource file) {
return file != null
&& file.getType() == IFile.FILE
&& file.getFileExtension() != null
&& file.getFileExtension().equalsIgnoreCase("class"); //$NON-NLS-1$
}
/*
* Builds and returns a map that has the class files
* for each java file in a given directory
*/
private Map buildJavaToClassMap(IContainer container) throws CoreException {
if (!isCompilerGeneratingSourceFileAttribute())
return null;
if (container == null || !container.isAccessible())
return new HashMap(0);
/*
* XXX: Bug 6584: Need a way to get class files for a java file (or CU)
*/
org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader cfReader;
IResource[] members= container.members();
Map map= new HashMap(members.length);
for (int i= 0; i < members.length; i++) {
if (isClassFile(members[i])) {
IFile classFile= (IFile)members[i];
try {
cfReader= org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader.read(classFile.getLocation().toFile());
} catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.invalidClassFileFormat", classFile.getLocation().toFile()), ex); //$NON-NLS-1$
continue;
} catch (IOException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.ioErrorDuringClassFileLookup", classFile.getLocation().toFile()), ex); //$NON-NLS-1$
continue;
}
if (cfReader != null) {
if (cfReader.sourceFileName() == null) {
/*
* Can't fully build the map because one or more
* class file does not contain the name of its
* source file.
*/
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.classFileWithoutSourceFileAttribute", classFile.getLocation().toFile()), null); //$NON-NLS-1$
return null;
}
String javaName= new String(cfReader.sourceFileName());
Object classFiles= map.get(javaName);
if (classFiles == null) {
classFiles= new ArrayList(3);
map.put(javaName, classFiles);
}
((ArrayList)classFiles).add(classFile);
}
}
}
return map;
}
/**
* Creates a file resource handle for the file with the given workspace path.
* This method does not create the file resource; this is the responsibility
* of <code>createFile</code>.
*
* @param filePath the path of the file resource to create a handle for
* @return the new file resource handle
* @see #createFile
*/
protected IFile createFileHandle(IPath filePath) {
if (filePath.isValidPath(filePath.toString()) && filePath.segmentCount() >= 2)
return JavaPlugin.getWorkspace().getRoot().getFile(filePath);
else
return null;
}
/**
* Creates a folder resource handle for the folder with the given workspace path.
*
* @param folderPath the path of the folder to create a handle for
* @return the new folder resource handle
*/
protected IFolder createFolderHandle(IPath folderPath) {
if (folderPath.isValidPath(folderPath.toString()) && folderPath.segmentCount() >= 2)
return JavaPlugin.getWorkspace().getRoot().getFolder(folderPath);
else
return null;
}
/**
* Returns the status of this operation.
* The result is a status object containing individual
* status objects.
*
* @return the status of this operation
*/
public IStatus getStatus() {
String message= null;
switch (fStatus.getSeverity()) {
case IStatus.OK:
message= ""; //$NON-NLS-1$
break;
case IStatus.INFO:
message= JarPackagerMessages.getString("JarFileExportOperation.exportFinishedWithInfo"); //$NON-NLS-1$
break;
case IStatus.WARNING:
message= JarPackagerMessages.getString("JarFileExportOperation.exportFinishedWithWarnings"); //$NON-NLS-1$
break;
case IStatus.ERROR:
if (fJarPackages.length > 1)
message= JarPackagerMessages.getString("JarFileExportOperation.creationOfSomeJARsFailed"); //$NON-NLS-1$
else
message= JarPackagerMessages.getString("JarFileExportOperation.jarCreationFailed"); //$NON-NLS-1$
break;
default:
// defensive code in case new severity is defined
message= ""; //$NON-NLS-1$
break;
}
fStatus.setMessage(message);
return fStatus;
}
/**
* Answer a boolean indicating whether the passed child is a descendant
* of one or more members of the passed resources collection
*
* @param resources a List contain potential parents
* @param child the resource to test
* @return a <code>boolean</code> indicating if the child is a descendant
*/
protected boolean isDescendant(List resources, IResource child) {
if (child.getType() == IResource.PROJECT)
return false;
IResource parent= child.getParent();
if (resources.contains(parent))
return true;
return isDescendant(resources, parent);
}
protected boolean canBeExported(boolean hasErrors, boolean hasWarnings) throws CoreException {
return (!hasErrors && !hasWarnings)
|| (hasErrors && fJarPackage.areErrorsExported())
|| (hasWarnings && fJarPackage.exportWarnings());
}
protected void reportPossibleCompileProblems(IFile file, boolean hasErrors, boolean hasWarnings, boolean canBeExported) {
if (hasErrors) {
if (canBeExported)
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.exportedWithCompileErrors", file.getFullPath()), null); //$NON-NLS-1$
else
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.notExportedDueToCompileErrors", file.getFullPath()), null); //$NON-NLS-1$
}
if (hasWarnings) {
if (canBeExported)
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.exportedWithCompileWarnings", file.getFullPath()), null); //$NON-NLS-1$
else
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.notExportedDueToCompileWarnings", file.getFullPath()), null); //$NON-NLS-1$
}
}
/**
* Exports the resources as specified by the JAR package.
*
* @param progressMonitor the progress monitor that displays the progress
* @see #getStatus()
*/
public void run(IProgressMonitor progressMonitor) throws InvocationTargetException, InterruptedException {
int count= fJarPackages.length;
progressMonitor.beginTask("", count); //$NON-NLS-1$
try {
for (int i= 0; i < count; i++) {
SubProgressMonitor subProgressMonitor= new SubProgressMonitor(progressMonitor, 1);
fJarPackage= fJarPackages[i];
if (fJarPackage != null)
singleRun(subProgressMonitor);
}
} finally {
progressMonitor.done();
}
}
public void singleRun(IProgressMonitor progressMonitor) throws InvocationTargetException, InterruptedException {
try {
if (!preconditionsOK())
throw new InvocationTargetException(null, JarPackagerMessages.getString("JarFileExportOperation.jarCreationFailedSeeDetails")); //$NON-NLS-1$
int totalWork= countSelectedElements();
if (!isAutoBuilding() && fJarPackage.isBuildingIfNeeded()) {
int subMonitorTicks= totalWork/10;
totalWork += subMonitorTicks;
progressMonitor.beginTask("", totalWork); //$NON-NLS-1$
SubProgressMonitor subProgressMonitor= new SubProgressMonitor(progressMonitor, subMonitorTicks, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK);
buildProjects(subProgressMonitor);
} else
progressMonitor.beginTask("", totalWork); //$NON-NLS-1$
fJarWriter= fJarPackage.createJarWriter(fParentShell);
exportSelectedElements(progressMonitor);
if (getStatus().getSeverity() != IStatus.ERROR) {
progressMonitor.subTask(JarPackagerMessages.getString("JarFileExportOperation.savingFiles")); //$NON-NLS-1$
saveFiles();
}
} catch (CoreException ex) {
addToStatus(ex);
} finally {
try {
if (fJarWriter != null)
fJarWriter.close();
} catch (CoreException ex) {
addToStatus(ex);
}
progressMonitor.done();
}
}
protected boolean preconditionsOK() {
if (!fJarPackage.areClassFilesExported() && !fJarPackage.areJavaFilesExported()) {
addError(JarPackagerMessages.getString("JarFileExportOperation.noExportTypeChosen"), null); //$NON-NLS-1$
return false;
}
if (fJarPackage.getElements() == null || fJarPackage.getElements().length == 0) {
addError(JarPackagerMessages.getString("JarFileExportOperation.noResourcesSelected"), null); //$NON-NLS-1$
return false;
}
if (fJarPackage.getJarLocation() == null) {
addError(JarPackagerMessages.getString("JarFileExportOperation.invalidJarLocation"), null); //$NON-NLS-1$
return false;
}
if (!fJarPackage.isManifestAccessible()) {
addError(JarPackagerMessages.getString("JarFileExportOperation.manifestDoesNotExist"), null); //$NON-NLS-1$
return false;
}
if (!fJarPackage.isMainClassValid(new BusyIndicatorRunnableContext())) {
addError(JarPackagerMessages.getString("JarFileExportOperation.invalidMainClass"), null); //$NON-NLS-1$
return false;
}
IFile[] unsavedFiles= getUnsavedFiles();
if (unsavedFiles.length > 0)
return saveModifiedResourcesIfUserConfirms(unsavedFiles);
return true;
}
/**
* Returns the files which are not saved and which are
* part of the files being exported.
*
* @return an array of unsaved files
*/
private IFile[] getUnsavedFiles() {
IEditorPart[] dirtyEditors= getDirtyEditors(fParentShell);
Set unsavedFiles= new HashSet(dirtyEditors.length);
if (dirtyEditors.length > 0) {
List selection= JarPackagerUtil.asResources(fJarPackage.getElements());
for (int i= 0; i < dirtyEditors.length; i++) {
if (dirtyEditors[i].getEditorInput() instanceof IFileEditorInput) {
IFile dirtyFile= ((IFileEditorInput)dirtyEditors[i].getEditorInput()).getFile();
if (JarPackagerUtil.contains(selection, dirtyFile)) {
unsavedFiles.add(dirtyFile);
}
}
}
}
return (IFile[])unsavedFiles.toArray(new IFile[unsavedFiles.size()]);
}
/**
* Asks the user to confirm to save the modified resources.
*
* @return true if user pressed OK.
*/
private boolean confirmSaveModifiedResources(IFile[] dirtyFiles) {
if (dirtyFiles == null || dirtyFiles.length == 0)
return true;
// Get display for further UI operations
Display display= fParentShell.getDisplay();
if (display == null || display.isDisposed())
return false;
// Ask user to confirm saving of all files
final ConfirmSaveModifiedResourcesDialog dlg= new ConfirmSaveModifiedResourcesDialog(fParentShell, dirtyFiles);
final int[] intResult= new int[1];
Runnable runnable= new Runnable() {
public void run() {
intResult[0]= dlg.open();
}
};
display.syncExec(runnable);
return intResult[0] == IDialogConstants.OK_ID;
}
/**
* Asks to confirm to save the modified resources
* and save them if OK is pressed.
*
* @return true if user pressed OK and save was successful.
*/
private boolean saveModifiedResourcesIfUserConfirms(IFile[] dirtyFiles) {
if (confirmSaveModifiedResources(dirtyFiles))
return saveModifiedResources(dirtyFiles);
// Report unsaved files
for (int i= 0; i < dirtyFiles.length; i++)
addError(JarPackagerMessages.getFormattedString("JarFileExportOperation.fileUnsaved", dirtyFiles[i].getFullPath()), null); //$NON-NLS-1$
return false;
}
/**
* Save all of the editors in the workbench.
*
* @return true if successful.
*/
private boolean saveModifiedResources(final IFile[] dirtyFiles) {
// Get display for further UI operations
Display display= fParentShell.getDisplay();
if (display == null || display.isDisposed())
return false;
final boolean[] retVal= new boolean[1];
Runnable runnable= new Runnable() {
public void run() {
IWorkspace workspace= ResourcesPlugin.getWorkspace();
IWorkspaceDescription description= workspace.getDescription();
boolean autoBuild= description.isAutoBuilding();
description.setAutoBuilding(false);
try {
workspace.setDescription(description);
// This save operation can not be canceled.
try {
new ProgressMonitorDialog(fParentShell).run(false, false, createSaveModifiedResourcesRunnable(dirtyFiles));
retVal[0]= true;
} finally {
description.setAutoBuilding(autoBuild);
workspace.setDescription(description);
}
} catch (InvocationTargetException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingModifiedResources"), ex); //$NON-NLS-1$
JavaPlugin.log(ex);
retVal[0]= false;
} catch (InterruptedException ex) {
Assert.isTrue(false); // Can't happen. Operation isn't cancelable.
retVal[0]= false;
} catch (CoreException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingModifiedResources"), ex); //$NON-NLS-1$
JavaPlugin.log(ex);
retVal[0]= false;
}
}
};
display.syncExec(runnable);
return retVal[0];
}
private IRunnableWithProgress createSaveModifiedResourcesRunnable(final IFile[] dirtyFiles) {
return new IRunnableWithProgress() {
public void run(final IProgressMonitor pm) {
IEditorPart[] editorsToSave= getDirtyEditors(fParentShell);
pm.beginTask(JarPackagerMessages.getString("JarFileExportOperation.savingModifiedResources"), editorsToSave.length); //$NON-NLS-1$
try {
List dirtyFilesList= Arrays.asList(dirtyFiles);
for (int i= 0; i < editorsToSave.length; i++) {
if (editorsToSave[i].getEditorInput() instanceof IFileEditorInput) {
IFile dirtyFile= ((IFileEditorInput)editorsToSave[i].getEditorInput()).getFile();
if (dirtyFilesList.contains((dirtyFile)))
editorsToSave[i].doSave(new SubProgressMonitor(pm, 1));
}
pm.worked(1);
}
} finally {
pm.done();
}
}
};
}
protected void saveFiles() {
// Save the manifest
if (fJarPackage.isManifestGenerated() && fJarPackage.isManifestSaved()) {
try {
saveManifest();
} catch (CoreException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingManifest"), ex); //$NON-NLS-1$
} catch (IOException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingManifest"), ex); //$NON-NLS-1$
}
}
// Save the description
if (fJarPackage.isDescriptionSaved()) {
try {
saveDescription();
} catch (CoreException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingDescription"), ex); //$NON-NLS-1$
} catch (IOException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingDescription"), ex); //$NON-NLS-1$
}
}
}
private IEditorPart[] getDirtyEditors(Shell parent) {
Display display= parent.getDisplay();
final Object[] result= new Object[1];
display.syncExec(
new Runnable() {
public void run() {
result[0]= JavaPlugin.getDirtyEditors();
}
}
);
return (IEditorPart[])result[0];
}
protected void saveDescription() throws CoreException, IOException {
// Adjust JAR package attributes
if (fJarPackage.isManifestReused())
fJarPackage.setGenerateManifest(false);
ByteArrayOutputStream objectStreamOutput= new ByteArrayOutputStream();
IJarDescriptionWriter writer= fJarPackage.createJarDescriptionWriter(objectStreamOutput);
ByteArrayInputStream fileInput= null;
try {
writer.write(fJarPackage);
fileInput= new ByteArrayInputStream(objectStreamOutput.toByteArray());
IFile descriptionFile= fJarPackage.getDescriptionFile();
if (descriptionFile.isAccessible()) {
if (fJarPackage.allowOverwrite() || JarPackagerUtil.askForOverwritePermission(fParentShell, descriptionFile.getFullPath().toString()))
descriptionFile.setContents(fileInput, true, true, null);
} else
descriptionFile.create(fileInput, true, null);
} finally {
if (fileInput != null)
fileInput.close();
if (writer != null)
writer.close();
}
}
protected void saveManifest() throws CoreException, IOException {
ByteArrayOutputStream manifestOutput= new ByteArrayOutputStream();
ByteArrayInputStream fileInput= null;
try {
Manifest manifest= fJarPackage.getManifestProvider().create(fJarPackage);
manifest.write(manifestOutput);
fileInput= new ByteArrayInputStream(manifestOutput.toByteArray());
IFile manifestFile= fJarPackage.getManifestFile();
if (manifestFile.isAccessible()) {
if (fJarPackage.allowOverwrite() || JarPackagerUtil.askForOverwritePermission(fParentShell, manifestFile.getFullPath().toString()))
manifestFile.setContents(fileInput, true, true, null);
} else
manifestFile.create(fileInput, true, null);
} finally {
if (manifestOutput != null)
manifestOutput.close();
if (fileInput != null)
fileInput.close();
}
}
private boolean isAutoBuilding() {
return ResourcesPlugin.getWorkspace().getDescription().isAutoBuilding();
}
private boolean isCompilerGeneratingSourceFileAttribute() {
Object value= JavaCore.getOptions().get(COMPILER_SOURCE_FILE_ATTR);
if (value instanceof String)
return "generate".equalsIgnoreCase((String)value); //$NON-NLS-1$
else
return true; // default
}
private void buildProjects(IProgressMonitor progressMonitor) {
Set builtProjects= new HashSet(10);
Object[] elements= fJarPackage.getElements();
for (int i= 0; i < elements.length; i++) {
IProject project= null;
Object element= elements[i];
if (element instanceof IResource)
project= ((IResource)element).getProject();
else if (element instanceof IJavaElement)
project= ((IJavaElement)element).getJavaProject().getProject();
if (project != null && !builtProjects.contains(project)) {
try {
project.build(IncrementalProjectBuilder.INCREMENTAL_BUILD, progressMonitor);
} catch (CoreException ex) {
String message= JarPackagerMessages.getFormattedString("JarFileExportOperation.errorDuringProjectBuild", project.getFullPath()); //$NON-NLS-1$
addError(message, ex);
} finally {
// don't try to build same project a second time even if it failed
builtProjects.add(project);
}
}
}
}
/**
* Tells whether the given resource (or its children) have compile errors.
* The method acts on the current build state and does not recompile.
*
* @param resource the resource to check for errors
* @return <code>true</code> if the resource (and its children) are error free
* @throws import org.eclipse.core.runtime.CoreException if there's a marker problem
*/
private boolean hasCompileErrors(IResource resource) throws CoreException {
IMarker[] problemMarkers= resource.findMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, true, IResource.DEPTH_INFINITE);
for (int i= 0; i < problemMarkers.length; i++) {
if (problemMarkers[i].getAttribute(IMarker.SEVERITY, -1) == IMarker.SEVERITY_ERROR)
return true;
}
return false;
}
/**
* Tells whether the given resource (or its children) have compile errors.
* The method acts on the current build state and does not recompile.
*
* @param resource the resource to check for errors
* @return <code>true</code> if the resource (and its children) are error free
* @throws import org.eclipse.core.runtime.CoreException if there's a marker problem
*/
private boolean hasCompileWarnings(IResource resource) throws CoreException {
IMarker[] problemMarkers= resource.findMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, true, IResource.DEPTH_INFINITE);
for (int i= 0; i < problemMarkers.length; i++) {
if (problemMarkers[i].getAttribute(IMarker.SEVERITY, -1) == IMarker.SEVERITY_WARNING)
return true;
}
return false;
}
private boolean mustUseSourceFolderHierarchy() {
return fJarPackage.useSourceFolderHierarchy() && fJarPackage.areJavaFilesExported() && !fJarPackage.areClassFilesExported();
}
}
|
15,108 |
Bug 15108 Add import deletes code
|
Build 20020501 1) Create a class "TestingFoo" in package "Testing". 2) In another package, create a class and method and type "TestingFoo". 3) With the cursor at the end of "TestingFoo", hit Ctrl+Shift+M to add the import. It deletes part of the class name, and all that's left is "oo". I guess it does a match against the package name, and since the package name is a prefix of the class name, it incorrectly deletes part of the class name.
|
resolved fixed
|
b8eeaa0
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-03T07:29:34Z | 2002-05-02T14:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/AddImportOnSelectionAction.java
|
package org.eclipse.jdt.internal.ui.javaeditor;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.dialogs.ElementListSelectionDialog;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.ui.texteditor.IUpdate;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.core.search.IJavaSearchConstants;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.ITypeNameRequestor;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.ui.IWorkingCopyManager;
import org.eclipse.jdt.internal.corext.codemanipulation.AddImportsOperation;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.corext.util.TypeInfo;
import org.eclipse.jdt.internal.corext.util.TypeInfoRequestor;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.util.TypeInfoLabelProvider;
public class AddImportOnSelectionAction extends Action implements IUpdate {
private ITextEditor fEditor;
public AddImportOnSelectionAction(ITextEditor editor) {
super(JavaEditorMessages.getString("AddImportOnSelection.label")); //$NON-NLS-1$
setToolTipText(JavaEditorMessages.getString("AddImportOnSelection.tooltip")); //$NON-NLS-1$
setDescription(JavaEditorMessages.getString("AddImportOnSelection.description")); //$NON-NLS-1$
fEditor= editor;
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.ADD_IMPORT_ON_SELECTION_ACTION);
}
public AddImportOnSelectionAction() {
this(null);
}
public void setContentEditor(ITextEditor editor) {
fEditor= editor;
}
public void update() {
boolean isEnabled= false;
try {
ISelection selection= fEditor.getSelectionProvider().getSelection();
if (selection instanceof ITextSelection) {
ICompilationUnit cu= getCompilationUnit();
isEnabled= (cu != null) && JavaModelUtil.isEditable(cu);
}
} catch(JavaModelException e) {
}
setEnabled(isEnabled);
}
private ICompilationUnit getCompilationUnit () {
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
return manager.getWorkingCopy(fEditor.getEditorInput());
}
/**
* @see IAction#actionPerformed
*/
public void run() {
ICompilationUnit cu= getCompilationUnit();
if (cu != null) {
ISelection s= fEditor.getSelectionProvider().getSelection();
IDocument doc= fEditor.getDocumentProvider().getDocument(fEditor.getEditorInput());
ITextSelection selection= (ITextSelection) s;
if (doc != null) {
try {
int nameStart= getNameStart(doc, selection.getOffset());
int nameEnd= getNameEnd(doc, selection.getOffset() + selection.getLength());
int len= nameEnd - nameStart;
String name= doc.get(nameStart, len).trim();
String simpleName= Signature.getSimpleName(name);
String containerName= Signature.getQualifier(name);
IImportDeclaration existingImport= JavaModelUtil.findImport(cu, simpleName);
if (existingImport != null) {
if (!existingImport.getElementName().equals(name)) {
getShell().getDisplay().beep();
}
return;
}
IJavaSearchScope searchScope= SearchEngine.createJavaSearchScope(new IJavaElement[] { cu.getJavaProject() });
TypeInfo[] types= findAllTypes(simpleName, searchScope, null);
if (types.length== 0) {
getShell().getDisplay().beep();
return;
}
TypeInfo chosen= selectResult(types, containerName, getShell());
if (chosen == null) {
return;
}
IType type= chosen.resolveType(searchScope);
if (type == null) {
JavaPlugin.logErrorMessage("AddImportOnSelectionAction: Failed to resolve TypeRef: " + chosen.toString()); //$NON-NLS-1$
MessageDialog.openError(getShell(), JavaEditorMessages.getString("AddImportOnSelection.error.title"), JavaEditorMessages.getString("AddImportOnSelection.error.notresolved.message")); //$NON-NLS-1$ //$NON-NLS-2$
return;
}
removeQualification(doc, nameStart, chosen);
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
AddImportsOperation op= new AddImportsOperation(cu, new IJavaElement[] { type }, settings, false);
ProgressMonitorDialog dialog= new ProgressMonitorDialog(getShell());
try {
dialog.run(false, true, new WorkbenchRunnableAdapter(op));
} catch (InvocationTargetException e) {
JavaPlugin.log(e);
MessageDialog.openError(getShell(), JavaEditorMessages.getString("AddImportOnSelection.error.title"), e.getTargetException().getMessage()); //$NON-NLS-1$
} catch (InterruptedException e) {
// Do nothing. Operation has been canceled.
}
return;
} catch (CoreException e) {
JavaPlugin.log(e);
ErrorDialog.openError(getShell(), JavaEditorMessages.getString("AddImportOnSelection.error.title"), null, e.getStatus()); //$NON-NLS-1$
} catch (BadLocationException e) {
JavaPlugin.log(e);
MessageDialog.openError(getShell(), JavaEditorMessages.getString("AddImportOnSelection.error.title"), e.getMessage()); //$NON-NLS-1$
}
}
}
}
private int getNameStart(IDocument doc, int pos) throws BadLocationException {
while (pos > 0) {
char ch= doc.getChar(pos - 1);
if (!Character.isJavaIdentifierPart(ch) && ch != '.') {
return pos;
}
pos--;
}
return pos;
}
private int getNameEnd(IDocument doc, int pos) throws BadLocationException {
int len= doc.getLength();
while (pos < len) {
char ch= doc.getChar(pos);
if (!Character.isJavaIdentifierPart(ch)) {
return pos;
}
pos++;
}
return pos;
}
private void removeQualification(IDocument doc, int nameStart, TypeInfo typeInfo) throws BadLocationException {
String containerName= typeInfo.getTypeContainerName();
int containerLen= containerName.length();
if (containerLen > 0) {
for (int k= 0; k < containerLen; k++) {
if (doc.getChar(nameStart + k) != containerName.charAt(k)) {
return;
}
}
doc.replace(nameStart, containerLen + 1, ""); //$NON-NLS-1$
}
}
/**
* Finds a type by the simple name.
*/
private static TypeInfo[] findAllTypes(String simpleTypeName, IJavaSearchScope searchScope, IProgressMonitor monitor) throws CoreException {
SearchEngine searchEngine= new SearchEngine();
ArrayList typeRefsFound= new ArrayList(10);
ITypeNameRequestor requestor= new TypeInfoRequestor(typeRefsFound);
searchEngine.searchAllTypeNames(
JavaPlugin.getWorkspace(),
null,
simpleTypeName.toCharArray(),
IJavaSearchConstants.EXACT_MATCH,
IJavaSearchConstants.CASE_SENSITIVE,
IJavaSearchConstants.TYPE,
searchScope,
requestor,
IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH,
monitor);
return (TypeInfo[]) typeRefsFound.toArray(new TypeInfo[typeRefsFound.size()]);
}
private Shell getShell() {
return fEditor.getSite().getShell();
}
private TypeInfo selectResult(TypeInfo[] results, String containerName, Shell shell) {
int nResults= results.length;
if (nResults == 0) {
return null;
} else if (nResults == 1) {
return results[0];
}
if (containerName.length() != 0) {
for (int i= 0; i < nResults; i++) {
TypeInfo curr= (TypeInfo) results[i];
if (containerName.equals(curr.getTypeContainerName())) {
return curr;
}
}
}
ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), new TypeInfoLabelProvider(TypeInfoLabelProvider.SHOW_FULLYQUALIFIED));
dialog.setTitle(JavaEditorMessages.getString("AddImportOnSelection.dialog.title")); //$NON-NLS-1$
dialog.setMessage(JavaEditorMessages.getString("AddImportOnSelection.dialog.message")); //$NON-NLS-1$
dialog.setElements(results);
if (dialog.open() == dialog.OK) {
return (TypeInfo) dialog.getFirstResult();
}
return null;
}
}
|
12,683 |
Bug 12683 Invalid Thread Access self hosting using Java Search
|
The Java Search causes an Invalid Thread Access when you are self hosting. This will also occur if you use search in a JUnit test or if I run Eclipse using the following options: eclipse -ws win32 -debug -dev bin The problem is a call to Display.getCurrent() in the initialization code for the JavaEditorPreferencePage which is called the first time you do a search. STEPS 1) Self host Eclipse 2) Select Java Search 3) Enter the name of a class 4) Hit Search - Invalid Thread Access Log: Wed Apr 03 08:57:31 EST 2002 4 org.eclipse.jdt.ui 1 Internal Error java.lang.reflect.InvocationTargetException: org.eclipse.swt.SWTException: Invalid thread access at org.eclipse.swt.SWT.error(SWT.java:1887) at org.eclipse.swt.SWT.error(SWT.java:1819) at org.eclipse.swt.widgets.Display.checkDevice(Display.java(Compiled Code)) at org.eclipse.swt.widgets.Display.checkDevice(Display.java(Compiled Code)) at org.eclipse.swt.widgets.Display.getSystemColor(Display.java:965) at org.eclipse.jdt.internal.ui.preferences.JavaEditorPreferencePage.initDefaults (JavaEditorPreferencePage.java:209) at org.eclipse.jdt.internal.ui.JavaPlugin.initializeDefaultPreferences (JavaPlugin.java:320) at org.eclipse.ui.plugin.AbstractUIPlugin.getPreferenceStore (AbstractUIPlugin.java(Compiled Code)) at org.eclipse.jdt.internal.ui.preferences.AppearancePreferencePage.showMethodRetur nType(AppearancePreferencePage.java:40) at org.eclipse.jdt.internal.ui.viewsupport.StandardJavaUILabelProvider.initMasks (StandardJavaUILabelProvider.java:43) at org.eclipse.jdt.internal.ui.viewsupport.StandardJavaUILabelProvider.<init> (StandardJavaUILabelProvider.java:29) at org.eclipse.jdt.internal.ui.search.JavaSearchResultLabelProvider.<init> (JavaSearchResultLabelProvider.java:39) at org.eclipse.jdt.internal.ui.search.JavaSearchResultCollector.aboutToStart (JavaSearchResultCollector.java:104) at org.eclipse.jdt.core.search.SearchEngine.search (SearchEngine.java:376) at org.eclipse.jdt.internal.ui.search.JavaSearchOperation.execute (JavaSearchOperation.java:84) at org.eclipse.ui.actions.WorkspaceModifyOperation$1.run (WorkspaceModifyOperation.java:64) at org.eclipse.core.internal.resources.Workspace.run (Workspace.java:1343) at org.eclipse.ui.actions.WorkspaceModifyOperation.run (WorkspaceModifyOperation.java:78) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:98)
|
resolved fixed
|
3775393
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-03T13:51:48Z | 2002-04-03T13:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/JavaEditorPreferencePage.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
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.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.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.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.List;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.core.runtime.IStatus;
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.DialogPageContextComputer;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.texteditor.AbstractTextEditor;
import org.eclipse.ui.texteditor.WorkbenchChainedTextFontFieldEditor;
import org.eclipse.jdt.ui.text.IJavaColorConstants;
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.JavaPluginImages;
import org.eclipse.jdt.internal.ui.JavaUIMessages;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.dialogs.StatusUtil;
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitDocumentProvider;
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor;
import org.eclipse.jdt.internal.ui.text.ContentAssistPreference;
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= "_bold"; //$NON-NLS-1$
public final OverlayPreferenceStore.OverlayKey[] fKeys= new OverlayPreferenceStore.OverlayKey[] {
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND_SYSTEM_DEFAULT),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.INT, JavaSourceViewerConfiguration.PREFERENCE_TAB_WIDTH),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IJavaColorConstants.JAVA_MULTI_LINE_COMMENT),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IJavaColorConstants.JAVA_MULTI_LINE_COMMENT + BOLD),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IJavaColorConstants.JAVA_SINGLE_LINE_COMMENT),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IJavaColorConstants.JAVA_SINGLE_LINE_COMMENT + BOLD),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IJavaColorConstants.JAVA_KEYWORD),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IJavaColorConstants.JAVA_KEYWORD + BOLD),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IJavaColorConstants.JAVA_STRING),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IJavaColorConstants.JAVA_STRING + BOLD),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IJavaColorConstants.JAVA_DEFAULT),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IJavaColorConstants.JAVA_DEFAULT + BOLD),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IJavaColorConstants.JAVADOC_KEYWORD),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IJavaColorConstants.JAVADOC_KEYWORD + BOLD),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IJavaColorConstants.JAVADOC_TAG),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IJavaColorConstants.JAVADOC_TAG + BOLD),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IJavaColorConstants.JAVADOC_LINK),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IJavaColorConstants.JAVADOC_LINK + BOLD),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, IJavaColorConstants.JAVADOC_DEFAULT),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, IJavaColorConstants.JAVADOC_DEFAULT + BOLD),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, CompilationUnitEditor.MATCHING_BRACKETS_COLOR),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, CompilationUnitEditor.MATCHING_BRACKETS),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, CompilationUnitEditor.CURRENT_LINE_COLOR),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, CompilationUnitEditor.CURRENT_LINE),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, CompilationUnitEditor.PRINT_MARGIN_COLOR),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.INT, CompilationUnitEditor.PRINT_MARGIN_COLUMN),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, CompilationUnitEditor.PRINT_MARGIN),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, AbstractTextEditor.PREFERENCE_COLOR_FIND_SCOPE),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, CompilationUnitEditor.LINKED_POSITION_COLOR),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, CompilationUnitEditor.PROBLEM_INDICATION_COLOR),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, CompilationUnitEditor.PROBLEM_INDICATION),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, CompilationUnitDocumentProvider.HANDLE_TEMPRARY_PROBELMS),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, CompilationUnitEditor.OVERVIEW_RULER),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, CompilationUnitEditor.SPACES_FOR_TABS),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, ContentAssistPreference.AUTOACTIVATION),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.INT, ContentAssistPreference.AUTOACTIVATION_DELAY),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, ContentAssistPreference.AUTOINSERT),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, ContentAssistPreference.PROPOSALS_BACKGROUND),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, ContentAssistPreference.PROPOSALS_FOREGROUND),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, ContentAssistPreference.PARAMETERS_BACKGROUND),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, ContentAssistPreference.PARAMETERS_FOREGROUND),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, ContentAssistPreference.AUTOACTIVATION_TRIGGERS_JAVA),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.STRING, ContentAssistPreference.AUTOACTIVATION_TRIGGERS_JAVADOC),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, ContentAssistPreference.SHOW_VISIBLE_PROPOSALS),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, ContentAssistPreference.ORDER_PROPOSALS),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, ContentAssistPreference.CASE_SENSITIVITY),
new OverlayPreferenceStore.OverlayKey(OverlayPreferenceStore.BOOLEAN, ContentAssistPreference.ADD_IMPORT)
};
private final String[][] fListModel= new String[][] {
{ JavaUIMessages.getString("JavaEditorPreferencePage.multiLineComment"), IJavaColorConstants.JAVA_MULTI_LINE_COMMENT }, //$NON-NLS-1$
{ JavaUIMessages.getString("JavaEditorPreferencePage.singleLineComment"), IJavaColorConstants.JAVA_SINGLE_LINE_COMMENT }, //$NON-NLS-1$
{ JavaUIMessages.getString("JavaEditorPreferencePage.keywords"), IJavaColorConstants.JAVA_KEYWORD }, //$NON-NLS-1$
{ JavaUIMessages.getString("JavaEditorPreferencePage.strings"), IJavaColorConstants.JAVA_STRING }, //$NON-NLS-1$
{ JavaUIMessages.getString("JavaEditorPreferencePage.others"), IJavaColorConstants.JAVA_DEFAULT }, //$NON-NLS-1$
{ JavaUIMessages.getString("JavaEditorPreferencePage.javaDocKeywords"), IJavaColorConstants.JAVADOC_KEYWORD }, //$NON-NLS-1$
{ JavaUIMessages.getString("JavaEditorPreferencePage.javaDocHtmlTags"), IJavaColorConstants.JAVADOC_TAG }, //$NON-NLS-1$
{ JavaUIMessages.getString("JavaEditorPreferencePage.javaDocLinks"), IJavaColorConstants.JAVADOC_LINK }, //$NON-NLS-1$
{ JavaUIMessages.getString("JavaEditorPreferencePage.javaDocOthers"), IJavaColorConstants.JAVADOC_DEFAULT } //$NON-NLS-1$
};
private OverlayPreferenceStore fOverlayStore;
private JavaTextTools fJavaTextTools;
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 ArrayList fNumberFields= new ArrayList();
private ModifyListener fTextFieldListener= new ModifyListener() {
public void modifyText(ModifyEvent e) {
if (!e.widget.isDisposed())
textChanged((Text) e.widget);
}
};
private WorkbenchChainedTextFontFieldEditor fFontEditor;
private List fList;
private ColorEditor fForegroundColorEditor;
private ColorEditor fBackgroundColorEditor;
private Button fBackgroundDefaultRadioButton;
private Button fBackgroundCustomRadioButton;
private Button fBackgroundColorButton;
private Button fBoldCheckBox;
private SourceViewer fPreviewViewer;
private Button fBracketHighlightButton;
private Control fBracketHighlightColor;
private Button fLineHighlightButton;
private Control fLineHighlightColor;
private Button fPrintMarginButton;
private Control fPrintMarginColor;
private Control fPrintMarginColumn;
private Button fProblemIndicationButton;
private Control fProblemIndicationColor;
private Control fFindScopeColor;
private Control fLinkedPositionColor;
public JavaEditorPreferencePage() {
setDescription(JavaUIMessages.getString("JavaEditorPreferencePage.description")); //$NON-NLS-1$
setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore());
fOverlayStore= new OverlayPreferenceStore(getPreferenceStore(), fKeys);
}
public static void initDefaults(IPreferenceStore store) {
Color color;
Display display= Display.getDefault();
store.setDefault(CompilationUnitEditor.MATCHING_BRACKETS, true);
color= display.getSystemColor(SWT.COLOR_GRAY);
PreferenceConverter.setDefault(store, CompilationUnitEditor.MATCHING_BRACKETS_COLOR, color.getRGB());
store.setDefault(CompilationUnitEditor.CURRENT_LINE, true);
PreferenceConverter.setDefault(store, CompilationUnitEditor.CURRENT_LINE_COLOR, new RGB(225, 235, 224));
store.setDefault(CompilationUnitEditor.PRINT_MARGIN, false);
store.setDefault(CompilationUnitEditor.PRINT_MARGIN_COLUMN, 80);
PreferenceConverter.setDefault(store, CompilationUnitEditor.PRINT_MARGIN_COLOR, new RGB(176, 180 , 185));
PreferenceConverter.setDefault(store, AbstractTextEditor.PREFERENCE_COLOR_FIND_SCOPE, new RGB(185, 176 , 180));
store.setDefault(CompilationUnitEditor.PROBLEM_INDICATION, true);
PreferenceConverter.setDefault(store, CompilationUnitEditor.PROBLEM_INDICATION_COLOR, new RGB(255, 0 , 128));
store.setDefault(CompilationUnitDocumentProvider.HANDLE_TEMPRARY_PROBELMS, true);
PreferenceConverter.setDefault(store, CompilationUnitEditor.LINKED_POSITION_COLOR, new RGB(0, 200 , 100));
store.setDefault(CompilationUnitEditor.OVERVIEW_RULER, true);
WorkbenchChainedTextFontFieldEditor.startPropagate(store, JFaceResources.TEXT_FONT);
color= display.getSystemColor(SWT.COLOR_LIST_FOREGROUND);
PreferenceConverter.setDefault(store, AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND, color.getRGB());
store.setDefault(AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND_SYSTEM_DEFAULT, true);
color= display.getSystemColor(SWT.COLOR_LIST_BACKGROUND);
PreferenceConverter.setDefault(store, AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND, color.getRGB());
store.setDefault(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT, true);
store.setDefault(JavaSourceViewerConfiguration.PREFERENCE_TAB_WIDTH, 4);
store.setDefault(CompilationUnitEditor.SPACES_FOR_TABS, false);
PreferenceConverter.setDefault(store, IJavaColorConstants.JAVA_MULTI_LINE_COMMENT, new RGB(63, 127, 95));
store.setDefault(IJavaColorConstants.JAVA_MULTI_LINE_COMMENT + BOLD, false);
PreferenceConverter.setDefault(store, IJavaColorConstants.JAVA_SINGLE_LINE_COMMENT, new RGB(63, 127, 95));
store.setDefault(IJavaColorConstants.JAVA_SINGLE_LINE_COMMENT + BOLD, false);
PreferenceConverter.setDefault(store, IJavaColorConstants.JAVA_KEYWORD, new RGB(127, 0, 85));
store.setDefault(IJavaColorConstants.JAVA_KEYWORD + BOLD, true);
PreferenceConverter.setDefault(store, IJavaColorConstants.JAVA_STRING, new RGB(42, 0, 255));
store.setDefault(IJavaColorConstants.JAVA_STRING + BOLD, false);
PreferenceConverter.setDefault(store, IJavaColorConstants.JAVA_DEFAULT, new RGB(0, 0, 0));
store.setDefault(IJavaColorConstants.JAVA_DEFAULT + BOLD, false);
PreferenceConverter.setDefault(store, IJavaColorConstants.JAVADOC_KEYWORD, new RGB(127, 159, 191));
store.setDefault(IJavaColorConstants.JAVADOC_KEYWORD + BOLD, true);
PreferenceConverter.setDefault(store, IJavaColorConstants.JAVADOC_TAG, new RGB(127, 127, 159));
store.setDefault(IJavaColorConstants.JAVADOC_TAG + BOLD, false);
PreferenceConverter.setDefault(store, IJavaColorConstants.JAVADOC_LINK, new RGB(63, 63, 191));
store.setDefault(IJavaColorConstants.JAVADOC_LINK + BOLD, false);
PreferenceConverter.setDefault(store, IJavaColorConstants.JAVADOC_DEFAULT, new RGB(63, 95, 191));
store.setDefault(IJavaColorConstants.JAVADOC_DEFAULT + BOLD, false);
store.setDefault(ContentAssistPreference.AUTOACTIVATION, true);
store.setDefault(ContentAssistPreference.AUTOACTIVATION_DELAY, 500);
store.setDefault(ContentAssistPreference.AUTOINSERT, true);
PreferenceConverter.setDefault(store, ContentAssistPreference.PROPOSALS_BACKGROUND, new RGB(254, 241, 233));
PreferenceConverter.setDefault(store, ContentAssistPreference.PROPOSALS_FOREGROUND, new RGB(0, 0, 0));
PreferenceConverter.setDefault(store, ContentAssistPreference.PARAMETERS_BACKGROUND, new RGB(254, 241, 233));
PreferenceConverter.setDefault(store, ContentAssistPreference.PARAMETERS_FOREGROUND, new RGB(0, 0, 0));
store.setDefault(ContentAssistPreference.AUTOACTIVATION_TRIGGERS_JAVA, "."); //$NON-NLS-1$
store.setDefault(ContentAssistPreference.AUTOACTIVATION_TRIGGERS_JAVADOC, "@"); //$NON-NLS-1$
store.setDefault(ContentAssistPreference.SHOW_VISIBLE_PROPOSALS, true);
store.setDefault(ContentAssistPreference.CASE_SENSITIVITY, false);
store.setDefault(ContentAssistPreference.ORDER_PROPOSALS, false);
store.setDefault(ContentAssistPreference.ADD_IMPORT, true);
}
/*
* @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 handleListSelection() {
int i= fList.getSelectionIndex();
String key= fListModel[i][1];
RGB rgb= PreferenceConverter.getColor(fOverlayStore, key);
fForegroundColorEditor.setColorValue(rgb);
fBoldCheckBox.setSelection(fOverlayStore.getBoolean(key + BOLD));
}
private Control createColorPage(Composite parent) {
Composite colorComposite= new Composite(parent, SWT.NULL);
colorComposite.setLayout(new GridLayout());
Composite backgroundComposite= new Composite(colorComposite, SWT.NULL);
GridLayout layout= new GridLayout();
layout.marginHeight= 0;
layout.marginWidth= 0;
layout.numColumns= 2;
backgroundComposite.setLayout(layout);
Label label= new Label(backgroundComposite, SWT.NULL);
label.setText(JavaUIMessages.getString("JavaEditorPreferencePage.backgroundColor")); //$NON-NLS-1$
GridData gd= new GridData();
gd.horizontalSpan= 2;
label.setLayoutData(gd);
SelectionListener backgroundSelectionListener= new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
boolean custom= fBackgroundCustomRadioButton.getSelection();
fBackgroundColorButton.setEnabled(custom);
fOverlayStore.setValue(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT, !custom);
}
public void widgetDefaultSelected(SelectionEvent e) {}
};
fBackgroundDefaultRadioButton= new Button(backgroundComposite, SWT.RADIO | SWT.LEFT);
fBackgroundDefaultRadioButton.setText(JavaUIMessages.getString("JavaEditorPreferencePage.systemDefault")); //$NON-NLS-1$
gd= new GridData();
gd.horizontalSpan= 2;
fBackgroundDefaultRadioButton.setLayoutData(gd);
fBackgroundDefaultRadioButton.addSelectionListener(backgroundSelectionListener);
fBackgroundCustomRadioButton= new Button(backgroundComposite, SWT.RADIO | SWT.LEFT);
fBackgroundCustomRadioButton.setText(JavaUIMessages.getString("JavaEditorPreferencePage.custom")); //$NON-NLS-1$
fBackgroundCustomRadioButton.addSelectionListener(backgroundSelectionListener);
fBackgroundColorEditor= new ColorEditor(backgroundComposite);
fBackgroundColorButton= fBackgroundColorEditor.getButton();
gd= new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalAlignment= GridData.BEGINNING;
fBackgroundColorButton.setLayoutData(gd);
label= new Label(colorComposite, SWT.LEFT);
label.setText(JavaUIMessages.getString("JavaEditorPreferencePage.foreground")); //$NON-NLS-1$
label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Composite editorComposite= new Composite(colorComposite, SWT.NULL);
layout= new GridLayout();
layout.numColumns= 2;
layout.marginHeight= 0;
layout.marginWidth= 0;
editorComposite.setLayout(layout);
gd= new GridData(GridData.FILL_BOTH);
editorComposite.setLayoutData(gd);
fList= new List(editorComposite, SWT.SINGLE | SWT.V_SCROLL);
gd= new GridData(GridData.FILL_BOTH);
gd.heightHint= convertHeightInCharsToPixels(5);
fList.setLayoutData(gd);
Composite stylesComposite= new Composite(editorComposite, SWT.NULL);
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(JavaUIMessages.getString("JavaEditorPreferencePage.color")); //$NON-NLS-1$
gd= new GridData();
gd.horizontalAlignment= GridData.BEGINNING;
label.setLayoutData(gd);
fForegroundColorEditor= new ColorEditor(stylesComposite);
Button foregroundColorButton= fForegroundColorEditor.getButton();
gd= new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalAlignment= GridData.BEGINNING;
foregroundColorButton.setLayoutData(gd);
label= new Label(stylesComposite, SWT.LEFT);
label.setText(JavaUIMessages.getString("JavaEditorPreferencePage.bold")); //$NON-NLS-1$
gd= new GridData();
gd.horizontalAlignment= GridData.BEGINNING;
label.setLayoutData(gd);
fBoldCheckBox= new Button(stylesComposite, SWT.CHECK);
gd= new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalAlignment= GridData.BEGINNING;
fBoldCheckBox.setLayoutData(gd);
label= new Label(colorComposite, SWT.LEFT);
label.setText(JavaUIMessages.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(80);
gd.heightHint= convertHeightInCharsToPixels(15);
previewer.setLayoutData(gd);
fList.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
// do nothing
}
public void widgetSelected(SelectionEvent e) {
handleListSelection();
}
});
foregroundColorButton.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
// do nothing
}
public void widgetSelected(SelectionEvent e) {
int i= fList.getSelectionIndex();
String key= fListModel[i][1];
PreferenceConverter.setValue(fOverlayStore, key, fForegroundColorEditor.getColorValue());
}
});
fBackgroundColorButton.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
// do nothing
}
public void widgetSelected(SelectionEvent e) {
PreferenceConverter.setValue(fOverlayStore, AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND, fBackgroundColorEditor.getColorValue());
}
});
fBoldCheckBox.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
// do nothing
}
public void widgetSelected(SelectionEvent e) {
int i= fList.getSelectionIndex();
String key= fListModel[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);
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(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND) ||
p.equals(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT))
{
initializeViewerColors(fPreviewViewer);
}
fPreviewViewer.invalidateTextPresentation();
}
});
return fPreviewViewer.getControl();
}
private Color fBackgroundColor;
/**
* 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(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT)
? null
: createColor(store, AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND, 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 createBehaviorPage(Composite parent) {
Composite behaviorComposite= new Composite(parent, SWT.NULL);
GridLayout layout= new GridLayout(); layout.numColumns= 2;
behaviorComposite.setLayout(layout);
String label= JavaUIMessages.getString("JavaEditorPreferencePage.textFont"); //$NON-NLS-1$
addTextFontEditor(behaviorComposite, label, AbstractTextEditor.PREFERENCE_FONT);
label= JavaUIMessages.getString("JavaEditorPreferencePage.displayedTabWidth"); //$NON-NLS-1$
addTextField(behaviorComposite, label, JavaSourceViewerConfiguration.PREFERENCE_TAB_WIDTH, 2, 0, true);
label= JavaUIMessages.getString("JavaEditorPreferencePage.insertSpaceForTabs"); //$NON-NLS-1$
addCheckBox(behaviorComposite, label, CompilationUnitEditor.SPACES_FOR_TABS, 0);
label= JavaUIMessages.getString("JavaEditorPreferencePage.showProblemsBeforeCompiling"); //$NON-NLS-1$
addCheckBox(behaviorComposite, label, CompilationUnitDocumentProvider.HANDLE_TEMPRARY_PROBELMS, 0);
label= JavaUIMessages.getString("JavaEditorPreferencePage.showOverviewRuler"); //$NON-NLS-1$
addCheckBox(behaviorComposite, label, CompilationUnitEditor.OVERVIEW_RULER, 0);
label= JavaUIMessages.getString("JavaEditorPreferencePage.highlightMatchingBrackets"); //$NON-NLS-1$
fBracketHighlightButton= addCheckBox(behaviorComposite, label, CompilationUnitEditor.MATCHING_BRACKETS, 0);
label= JavaUIMessages.getString("JavaEditorPreferencePage.matchingBracketsHighlightColor"); //$NON-NLS-1$
fBracketHighlightColor= addColorButton(behaviorComposite, label, CompilationUnitEditor.MATCHING_BRACKETS_COLOR, 0);
fBracketHighlightButton.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
setEnabled(fBracketHighlightColor, fBracketHighlightButton.getSelection());
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
label= JavaUIMessages.getString("JavaEditorPreferencePage.highlightCurrentLine"); //$NON-NLS-1$
fLineHighlightButton= addCheckBox(behaviorComposite, label, CompilationUnitEditor.CURRENT_LINE, 0);
label= JavaUIMessages.getString("JavaEditorPreferencePage.currentLineHighlightColor"); //$NON-NLS-1$
fLineHighlightColor= addColorButton(behaviorComposite, label, CompilationUnitEditor.CURRENT_LINE_COLOR, 0);
fLineHighlightButton.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
setEnabled(fLineHighlightColor, fLineHighlightButton.getSelection());
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
label= JavaUIMessages.getString("JavaEditorPreferencePage.highlightProblems"); //$NON-NLS-1$
fProblemIndicationButton= addCheckBox(behaviorComposite, label, CompilationUnitEditor.PROBLEM_INDICATION, 0);
label= JavaUIMessages.getString("JavaEditorPreferencePage.problemHighlightColor"); //$NON-NLS-1$
fProblemIndicationColor= addColorButton(behaviorComposite, label, CompilationUnitEditor.PROBLEM_INDICATION_COLOR, 0);
fProblemIndicationButton.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
setEnabled(fProblemIndicationColor, fProblemIndicationButton.getSelection());
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
label= JavaUIMessages.getString("JavaEditorPreferencePage.showPrintMargin"); //$NON-NLS-1$
fPrintMarginButton= addCheckBox(behaviorComposite, label, CompilationUnitEditor.PRINT_MARGIN, 0);
label= JavaUIMessages.getString("JavaEditorPreferencePage.printMarginColor"); //$NON-NLS-1$
fPrintMarginColor= addColorButton(behaviorComposite, label, CompilationUnitEditor.PRINT_MARGIN_COLOR, 0);
label= JavaUIMessages.getString("JavaEditorPreferencePage.printMarginColumn"); //$NON-NLS-1$
fPrintMarginColumn= addTextField(behaviorComposite, label, CompilationUnitEditor.PRINT_MARGIN_COLUMN, 4, 0, true);
fPrintMarginButton.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
boolean enabled= fPrintMarginButton.getSelection();
setEnabled(fPrintMarginColor, enabled);
setEnabled(fPrintMarginColumn, enabled);
}
public void widgetDefaultSelected(SelectionEvent e) {
}
});
label= JavaUIMessages.getString("JavaEditorPreferencePage.findScopeColor"); //$NON-NLS-1$
fFindScopeColor= addColorButton(behaviorComposite, label, AbstractTextEditor.PREFERENCE_COLOR_FIND_SCOPE, 0);
label= JavaUIMessages.getString("JavaEditorPreferencePage.linkedPositionColor"); //$NON-NLS-1$
fLinkedPositionColor= addColorButton(behaviorComposite, label, CompilationUnitEditor.LINKED_POSITION_COLOR, 0);
return behaviorComposite;
}
private Control createContentAssistPage(Composite parent) {
Composite contentAssistComposite= new Composite(parent, SWT.NULL);
GridLayout layout= new GridLayout(); layout.numColumns= 2;
contentAssistComposite.setLayout(layout);
String label= JavaUIMessages.getString("JavaEditorPreferencePage.insertSingleProposalsAutomatically"); //$NON-NLS-1$
addCheckBox(contentAssistComposite, label, ContentAssistPreference.AUTOINSERT, 0);
label= JavaUIMessages.getString("JavaEditorPreferencePage.showOnlyProposalsVisibleInTheInvocationContext"); //$NON-NLS-1$
addCheckBox(contentAssistComposite, label, ContentAssistPreference.SHOW_VISIBLE_PROPOSALS, 0);
// label= "Show only proposals with &matching cases";
// addCheckBox(contentAssistComposite, label, ContentAssistPreference.CASE_SENSITIVITY, 0);
label= JavaUIMessages.getString("JavaEditorPreferencePage.presentProposalsInAlphabeticalOrder"); //$NON-NLS-1$
addCheckBox(contentAssistComposite, label, ContentAssistPreference.ORDER_PROPOSALS, 0);
label= JavaUIMessages.getString("JavaEditorPreferencePage.enableAutoActivation"); //$NON-NLS-1$
addCheckBox(contentAssistComposite, label, ContentAssistPreference.AUTOACTIVATION, 0);
label= JavaUIMessages.getString("JavaEditorPreferencePage.automaticallyAddImportInsteadOfQualifiedName"); //$NON-NLS-1$
addCheckBox(contentAssistComposite, label, ContentAssistPreference.ADD_IMPORT, 0);
label= JavaUIMessages.getString("JavaEditorPreferencePage.autoActivationDelay"); //$NON-NLS-1$
addTextField(contentAssistComposite, label, ContentAssistPreference.AUTOACTIVATION_DELAY, 4, 0, true);
label= JavaUIMessages.getString("JavaEditorPreferencePage.autoActivationTriggersForJava"); //$NON-NLS-1$
addTextField(contentAssistComposite, label, ContentAssistPreference.AUTOACTIVATION_TRIGGERS_JAVA, 25, 0, false);
label= JavaUIMessages.getString("JavaEditorPreferencePage.autoActivationTriggersForJavaDoc"); //$NON-NLS-1$
addTextField(contentAssistComposite, label, ContentAssistPreference.AUTOACTIVATION_TRIGGERS_JAVADOC, 25, 0, false);
label= JavaUIMessages.getString("JavaEditorPreferencePage.backgroundForCompletionProposals"); //$NON-NLS-1$
addColorButton(contentAssistComposite, label, ContentAssistPreference.PROPOSALS_BACKGROUND, 0);
label= JavaUIMessages.getString("JavaEditorPreferencePage.foregroundForCompletionProposals"); //$NON-NLS-1$
addColorButton(contentAssistComposite, label, ContentAssistPreference.PROPOSALS_FOREGROUND, 0);
label= JavaUIMessages.getString("JavaEditorPreferencePage.backgroundForMethodParameters"); //$NON-NLS-1$
addColorButton(contentAssistComposite, label, ContentAssistPreference.PARAMETERS_BACKGROUND, 0);
label= JavaUIMessages.getString("JavaEditorPreferencePage.foregroundForMethodParameters"); //$NON-NLS-1$
addColorButton(contentAssistComposite, label, ContentAssistPreference.PARAMETERS_FOREGROUND, 0);
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(JavaUIMessages.getString("JavaEditorPreferencePage.general")); //$NON-NLS-1$
item.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_CFILE));
item.setControl(createBehaviorPage(folder));
item= new TabItem(folder, SWT.NONE);
item.setText(JavaUIMessages.getString("JavaEditorPreferencePage.colors")); //$NON-NLS-1$
item.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_CFILE));
item.setControl(createColorPage(folder));
item= new TabItem(folder, SWT.NONE);
item.setText(JavaUIMessages.getString("JavaEditorPreferencePage.codeAssist")); //$NON-NLS-1$
item.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_CFILE));
item.setControl(createContentAssistPage(folder));
initialize();
return folder;
}
private void initialize() {
fFontEditor.setPreferenceStore(getPreferenceStore());
fFontEditor.setPreferencePage(this);
fFontEditor.load();
initializeFields();
for (int i= 0; i < fListModel.length; i++)
fList.add(fListModel[i][0]);
fList.getDisplay().asyncExec(new Runnable() {
public void run() {
fList.select(0);
handleListSelection();
}
});
}
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, AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND);
fBackgroundColorEditor.setColorValue(rgb);
boolean default_= fOverlayStore.getBoolean(AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT);
fBackgroundDefaultRadioButton.setSelection(default_);
fBackgroundCustomRadioButton.setSelection(!default_);
fBackgroundColorButton.setEnabled(!default_);
setEnabled(fBracketHighlightColor, fBracketHighlightButton.getSelection());
setEnabled(fLineHighlightColor, fLineHighlightButton.getSelection());
}
/*
* @see PreferencePage#performOk()
*/
public boolean performOk() {
fFontEditor.store();
fOverlayStore.propagate();
return true;
}
/*
* @see PreferencePage#performDefaults()
*/
protected void performDefaults() {
fFontEditor.loadDefault();
fOverlayStore.loadDefaults();
initializeFields();
handleListSelection();
super.performDefaults();
fPreviewViewer.invalidateTextPresentation();
}
/*
* @see DialogPage#dispose()
*/
public void dispose() {
if (fJavaTextTools != null) {
fJavaTextTools= null;
}
fFontEditor.setPreferencePage(null);
fFontEditor.setPreferenceStore(null);
if (fOverlayStore != null) {
fOverlayStore.stop();
fOverlayStore= null;
}
super.dispose();
}
private Control addColorButton(Composite parent, String label, String key, int indentation) {
Composite composite= new Composite(parent, SWT.NONE);
GridData gd= new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan= 2;
composite.setLayoutData(gd);
GridLayout layout= new GridLayout();
layout.numColumns= 2;
layout.marginWidth= 0;
layout.marginHeight= 0;
composite.setLayout(layout);
Label labelControl= new Label(composite, SWT.NONE);
labelControl.setText(label);
gd= new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalIndent= indentation;
labelControl.setLayoutData(gd);
ColorEditor editor= new ColorEditor(composite);
Button button= editor.getButton();
button.setData(editor);
gd= new GridData();
gd.horizontalAlignment= GridData.END;
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.FILL_HORIZONTAL);
gd.horizontalIndent= indentation;
gd.horizontalSpan= 2;
checkBox.setLayoutData(gd);
checkBox.addSelectionListener(fCheckBoxListener);
fCheckBoxes.put(checkBox, key);
return checkBox;
}
private Control addTextField(Composite parent, String label, String key, int textLimit, int indentation, boolean isNumber) {
Composite composite= new Composite(parent, SWT.NONE);
GridData gd= new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan= 2;
composite.setLayoutData(gd);
GridLayout layout= new GridLayout();
layout.numColumns= 2;
layout.marginWidth= 0;
layout.marginHeight= 0;
composite.setLayout(layout);
Label labelControl= new Label(composite, SWT.NONE);
labelControl.setText(label);
gd= new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalIndent= indentation;
labelControl.setLayoutData(gd);
Text textControl= new Text(composite, SWT.BORDER | SWT.SINGLE);
gd= new GridData(GridData.FILL_HORIZONTAL);
gd.widthHint= convertWidthInCharsToPixels(textLimit + 1);
gd.horizontalAlignment= GridData.END;
textControl.setLayoutData(gd);
textControl.setTextLimit(textLimit);
textControl.addModifyListener(fTextFieldListener);
fTextFields.put(textControl, key);
if (isNumber)
fNumberFields.add(textControl);
return composite;
}
private void addTextFontEditor(Composite parent, String label, String key) {
Composite editorComposite= new Composite(parent, SWT.NULL);
GridLayout layout= new GridLayout();
layout.numColumns= 3;
editorComposite.setLayout(layout);
fFontEditor= new WorkbenchChainedTextFontFieldEditor(key, label, editorComposite);
fFontEditor.setChangeButtonText(JavaUIMessages.getString("JavaEditorPreferencePage.change")); //$NON-NLS-1$
GridData gd= new GridData(GridData.FILL_HORIZONTAL);
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 textChanged(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(JavaUIMessages.getString("JavaEditorPreferencePage.empty_input")); //$NON-NLS-1$
} else {
try {
int value= Integer.parseInt(number);
if (value < 0)
status.setError(JavaUIMessages.getFormattedString("JavaEditorPreferencePage.invalid_input", number)); //$NON-NLS-1$
} catch (NumberFormatException e) {
status.setError(JavaUIMessages.getFormattedString("JavaEditorPreferencePage.invalid_input", number)); //$NON-NLS-1$
}
}
return status;
}
private 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);
}
}
setValid(!status.matches(IStatus.ERROR));
StatusUtil.applyToStatusLine(this, status);
}
}
|
14,777 |
Bug 14777 Self-encapsulate failure + undo scribbles in read-only file
|
Build: 20020426 (M5++) to reproduce the problem: 1. new class 2. keep editor open for the class 3. new default visibility field 4. make the class read-only 5. in the outliner select the field 6. from the pulldown select refactor->self-encapsulate 7. the operation attempts to run and then fails 8. click undo to undo the changes, your editor will be marked dirty, but you can't save because the file is read-only
|
resolved fixed
|
1ceeabf
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-03T16:12:00Z | 2002-04-26T19:40:00Z |
org.eclipse.jdt.ui/core
| |
14,777 |
Bug 14777 Self-encapsulate failure + undo scribbles in read-only file
|
Build: 20020426 (M5++) to reproduce the problem: 1. new class 2. keep editor open for the class 3. new default visibility field 4. make the class read-only 5. in the outliner select the field 6. from the pulldown select refactor->self-encapsulate 7. the operation attempts to run and then fails 8. click undo to undo the changes, your editor will be marked dirty, but you can't save because the file is read-only
|
resolved fixed
|
1ceeabf
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-03T16:12:00Z | 2002-04-26T19:40:00Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/sef/SelfEncapsulateFieldRefactoring.java
| |
3,926 |
Bug 3926 issue copying file with duplicate name (1GF60YK)
|
I tried to copy a package.html file from one package to another using the "copy" menu entry in the packages view. The destination package already had a file called package.html so I was presented with a "Duplicate names" dialog. The dialog has two radio buttons, one for "replace element" and one for "rename to". Issues: - The replace button is grayed out - "Rename to" is ambiguous. Am I renaming the thing being copied or the file already at the destination. Since I actually wanted to overwrite the file and the rename renames the file being copied, I could not accomplish the task. Note that the copy action from the navigator works as desired. NOTES: KH (6/12/2001 7:11:31 AM) Moving to JUI for comment.
|
resolved fixed
|
5577ddb
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-06T09:16:33Z | 2001-10-11T03:13:20Z |
org.eclipse.jdt.ui/core
| |
3,926 |
Bug 3926 issue copying file with duplicate name (1GF60YK)
|
I tried to copy a package.html file from one package to another using the "copy" menu entry in the packages view. The destination package already had a file called package.html so I was presented with a "Duplicate names" dialog. The dialog has two radio buttons, one for "replace element" and one for "rename to". Issues: - The replace button is grayed out - "Rename to" is ambiguous. Am I renaming the thing being copied or the file already at the destination. Since I actually wanted to overwrite the file and the rename renames the file being copied, I could not accomplish the task. Note that the copy action from the navigator works as desired. NOTES: KH (6/12/2001 7:11:31 AM) Moving to JUI for comment.
|
resolved fixed
|
5577ddb
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-06T09:16:33Z | 2001-10-11T03:13:20Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/reorg/CopyRefactoring.java
| |
3,926 |
Bug 3926 issue copying file with duplicate name (1GF60YK)
|
I tried to copy a package.html file from one package to another using the "copy" menu entry in the packages view. The destination package already had a file called package.html so I was presented with a "Duplicate names" dialog. The dialog has two radio buttons, one for "replace element" and one for "rename to". Issues: - The replace button is grayed out - "Rename to" is ambiguous. Am I renaming the thing being copied or the file already at the destination. Since I actually wanted to overwrite the file and the rename renames the file being copied, I could not accomplish the task. Note that the copy action from the navigator works as desired. NOTES: KH (6/12/2001 7:11:31 AM) Moving to JUI for comment.
|
resolved fixed
|
5577ddb
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-06T09:16:33Z | 2001-10-11T03:13:20Z |
org.eclipse.jdt.ui/core
| |
3,926 |
Bug 3926 issue copying file with duplicate name (1GF60YK)
|
I tried to copy a package.html file from one package to another using the "copy" menu entry in the packages view. The destination package already had a file called package.html so I was presented with a "Duplicate names" dialog. The dialog has two radio buttons, one for "replace element" and one for "rename to". Issues: - The replace button is grayed out - "Rename to" is ambiguous. Am I renaming the thing being copied or the file already at the destination. Since I actually wanted to overwrite the file and the rename renames the file being copied, I could not accomplish the task. Note that the copy action from the navigator works as desired. NOTES: KH (6/12/2001 7:11:31 AM) Moving to JUI for comment.
|
resolved fixed
|
5577ddb
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-06T09:16:33Z | 2001-10-11T03:13:20Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/reorg/ReorgRefactoring.java
| |
3,926 |
Bug 3926 issue copying file with duplicate name (1GF60YK)
|
I tried to copy a package.html file from one package to another using the "copy" menu entry in the packages view. The destination package already had a file called package.html so I was presented with a "Duplicate names" dialog. The dialog has two radio buttons, one for "replace element" and one for "rename to". Issues: - The replace button is grayed out - "Rename to" is ambiguous. Am I renaming the thing being copied or the file already at the destination. Since I actually wanted to overwrite the file and the rename renames the file being copied, I could not accomplish the task. Note that the copy action from the navigator works as desired. NOTES: KH (6/12/2001 7:11:31 AM) Moving to JUI for comment.
|
resolved fixed
|
5577ddb
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-06T09:16:33Z | 2001-10-11T03:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/reorg/JdtMoveAction.java
|
package org.eclipse.jdt.internal.ui.reorg;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.actions.MoveProjectAction;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.JavaElementContentProvider;
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.dialogs.ElementTreeSelectionDialog;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard;
import org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog;
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 (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, JavaElementContentProvider 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));
}
/*
* @see ReorgDestinationAction#getExcluded(ReorgRefactoring)
*/
Set getExcluded(ReorgRefactoring refactoring) throws JavaModelException{
Set elements= refactoring.getElementsThatExistInTarget();
Set result= new HashSet();
for (Iterator iter= elements.iterator(); iter.hasNext(); ){
Object o= iter.next();
int action= askIfOverwrite(ReorgUtils.getName(o));
if (action == IDialogConstants.CANCEL_ID)
return null;
if (action == IDialogConstants.YES_TO_ALL_ID)
return new HashSet(0); //nothing excluded
if (action == IDialogConstants.NO_ID)
result.add(o);
}
return result;
}
private static int askIfOverwrite(String elementName){
Shell shell= JavaPlugin.getActiveWorkbenchShell().getShell();
String title= ReorgMessages.getString("JdtMoveAction.move"); //$NON-NLS-1$
String question= ReorgMessages.getFormattedString("JdtMoveAction.overwrite", elementName);//$NON-NLS-1$
String[] labels= new String[] {IDialogConstants.YES_LABEL, IDialogConstants.YES_TO_ALL_LABEL,
IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL };
final MessageDialog dialog = new MessageDialog(shell, title, null, question, MessageDialog.QUESTION, labels, 0);
shell.getDisplay().syncExec(new Runnable() {
public void run() {
dialog.open();
}
});
int result = dialog.getReturnCode();
if (result == 0)
return IDialogConstants.YES_ID;
if (result == 1)
return IDialogConstants.YES_TO_ALL_ID;
if (result == 2)
return IDialogConstants.NO_ID;
return IDialogConstants.CANCEL_ID;
}
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){
//XXX - pm
RefactoringStatus status= refactoring.checkPreconditions(new NullProgressMonitor());
if (status.hasFatalError())
RefactoringErrorDialogUtil.open(ReorgMessages.getString("JdtMoveAction.move"), status);//$NON-NLS-1$
else
super.doReorg(refactoring);
return;
}
//XX incorrect help
RefactoringWizard wizard= new RefactoringWizard(refactoring, ReorgMessages.getString("JdtMoveAction.move"), IJavaHelpContextIds.MOVE_CU_ERROR_WIZARD_PAGE); //$NON-NLS-1$
new RefactoringWizardDialog(JavaPlugin.getActiveWorkbenchShell(), wizard).open();
}
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 fCheckbox;
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 Control createDialogArea(Composite parent) {
Composite result= (Composite)super.createDialogArea(parent);
fCheckbox= new Button(result, SWT.CHECK);
fCheckbox.setText(ReorgMessages.getString("JdtMoveAction.update_references")); //$NON-NLS-1$
fCheckbox.setEnabled(canUpdateReferences());
fCheckbox.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
updatePreviewButton();
fRefactoring.setUpdateReferences(fCheckbox.getEnabled() && fCheckbox.getSelection());
}
});
fCheckbox.setSelection(canUpdateReferences());
return result;
}
protected void createButtonsForButtonBar(Composite parent) {
super.createButtonsForButtonBar(parent);
fPreview= createButton(parent, PREVIEW_ID, ReorgMessages.getString("JdtMoveAction.preview"), false); //$NON-NLS-1$
}
protected void updateOKStatus() {
super.updateOKStatus();
try{
fRefactoring.setDestination(getFirstResult());
fCheckbox.setEnabled(getOkButton().getEnabled() && canUpdateReferences());
updatePreviewButton();
} 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();
}
private void updatePreviewButton(){
fPreview.setEnabled(fCheckbox.getEnabled() && fCheckbox.getSelection());
}
private boolean canUpdateReferences(){
try{
return fRefactoring.canUpdateReferences();
} catch (JavaModelException e){
return false;
}
}
}
}
|
3,926 |
Bug 3926 issue copying file with duplicate name (1GF60YK)
|
I tried to copy a package.html file from one package to another using the "copy" menu entry in the packages view. The destination package already had a file called package.html so I was presented with a "Duplicate names" dialog. The dialog has two radio buttons, one for "replace element" and one for "rename to". Issues: - The replace button is grayed out - "Rename to" is ambiguous. Am I renaming the thing being copied or the file already at the destination. Since I actually wanted to overwrite the file and the rename renames the file being copied, I could not accomplish the task. Note that the copy action from the navigator works as desired. NOTES: KH (6/12/2001 7:11:31 AM) Moving to JUI for comment.
|
resolved fixed
|
5577ddb
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-06T09:16:33Z | 2001-10-11T03:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/reorg/ReorgDestinationAction.java
|
package org.eclipse.jdt.internal.ui.reorg;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.dialogs.ListSelectionDialog;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.JavaElementContentProvider;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.ui.JavaElementSorter;
import org.eclipse.jdt.ui.actions.SelectionDispatchAction;
import org.eclipse.jdt.internal.corext.refactoring.Assert;
import org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgUtils;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.dialogs.ElementTreeSelectionDialog;
import org.eclipse.jdt.internal.ui.dialogs.ISelectionValidator;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.packageview.PackageFilter;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.viewsupport.ListContentProvider;
public abstract class ReorgDestinationAction extends SelectionDispatchAction {
protected ReorgDestinationAction(IWorkbenchSite site) {
super(site);
}
protected void selectionChanged(IStructuredSelection selection) {
setEnabled(canOperateOn(selection));
}
protected boolean canOperateOn(IStructuredSelection selection) {
return ClipboardActionUtil.canActivate(createRefactoring(selection.toList()));
}
protected void run(IStructuredSelection selection) {
List elements= selection.toList();
if (!ensureSaved(elements, getActionName()))
return;
ReorgRefactoring refactoring= createRefactoring(elements);
setUnsavedFileList(refactoring, elements);
Object destination= selectDestination(refactoring);
if (destination == null)
return;
try{
String duplicate= getDuplicatedElementName(elements);
if (duplicate != null){
String message= ReorgMessages.getFormattedString("ReorgDestinationAction.duplicate", duplicate);//$NON-NLS-1$
MessageDialog.openInformation(JavaPlugin.getActiveWorkbenchShell().getShell(), ReorgMessages.getString("ReorgDestinationAction.duplicate_name"), message); //$NON-NLS-1$
return;
}
refactoring.setDestination(destination);
Set excluded= getExcluded(refactoring);
if (excluded == null) //canceled
return;
if (excluded.size() == elements.size())
return;
refactoring.setExcludedElements(excluded);
if (! isOkToProceed(refactoring))
return;
doReorg(refactoring);
} catch (JavaModelException e){
ExceptionHandler.handle(e, ReorgMessages.getString("ReorgDestinationAction.exception_title"), ReorgMessages.getString("ReorgDestinationAction.exception")); //$NON-NLS-2$ //$NON-NLS-1$
}
}
/**
* returns null if no 2 elements have the same name
*/
private static String getDuplicatedElementName(List elements){
String[] names= getElementNames(elements);
if (names.length == 0)
return null;
Arrays.sort(names);
String last= names[0];
for (int i= 1; i < names.length; i++){ //non standard loop
if (last.equals(names[i]))
return last;
last= names[i];
}
return null;
}
abstract String getActionName();
abstract String getDestinationDialogMessage();
abstract ReorgRefactoring createRefactoring(List elements);
//hook to override
//returns null iff canceled
Set getExcluded(ReorgRefactoring refactoring) throws JavaModelException{
return new HashSet(0);
}
//hook to override
protected boolean isOkToProceed(ReorgRefactoring refactoring) throws JavaModelException{
return true;
}
void doReorg(ReorgRefactoring refactoring) throws JavaModelException{
MultiStatus status= ClipboardActionUtil.perform(refactoring);
if (status.isOK())
return;
JavaPlugin.log(status);
ErrorDialog.openError(JavaPlugin.getActiveWorkbenchShell(), getActionName(), ReorgMessages.getString("ReorgDestinationAction.error"), status); //$NON-NLS-1$
}
private static boolean ensureSaved(List elements, String actionName) {
List unsavedEditors= new ArrayList();
List unsavedElements= new ArrayList();
collectUnsavedEditors(elements, unsavedEditors, unsavedElements);
if (unsavedEditors.isEmpty())
return true;
ListSelectionDialog dialog = createUnsavedEditorDialog(unsavedElements);
if (dialog.open() != dialog.OK)
return false;
IEditorPart[] unsavedEditorArray= (IEditorPart[]) unsavedEditors.toArray(new IEditorPart[unsavedEditors.size()]);
IRunnableWithProgress r= createSaveEditorOperation(dialog.getResult(), unsavedEditorArray);
try {
new ProgressMonitorDialog(JavaPlugin.getActiveWorkbenchShell()).run(false, false, r);
} catch (InvocationTargetException e) {
ExceptionHandler.handle(e, actionName, ReorgMessages.getString("ReorgAction.exception.saving")); //$NON-NLS-1$
return false;
} catch (InterruptedException e) {
}
return true;
}
private static void setUnsavedFileList(ReorgRefactoring refactoring, List elements){
List unsavedEditors= new ArrayList(0);
collectUnsavedEditors(elements, unsavedEditors, new ArrayList(0));
refactoring.setUnsavedFiles(getFiles(unsavedEditors));
}
private static IFile[] getFiles(List editorParts){
List result= new ArrayList(editorParts.size());
for (Iterator iter= editorParts.iterator(); iter.hasNext(); ){
IEditorPart each= (IEditorPart)iter.next();
IEditorInput input= each.getEditorInput();
if (input instanceof IFileEditorInput)
result.add(((IFileEditorInput)input).getFile());
}
return (IFile[]) result.toArray(new IFile[result.size()]);
}
private static IRunnableWithProgress createSaveEditorOperation(final Object[] elementsToSave, final IEditorPart[] unsavedEditors) {
return new IRunnableWithProgress() {
public void run(IProgressMonitor pm) {
pm.beginTask(ReorgMessages.getString("ReorgAction.task.saving"), elementsToSave.length); //$NON-NLS-1$
for (int i= 0; i < elementsToSave.length; i++) {
IEditorPart editor= findEditor(elementsToSave[i], unsavedEditors);
if (editor != null)
editor.doSave(new SubProgressMonitor(pm, 1));
else
pm.worked(1);
}
pm.done();
}
};
}
private static IEditorPart findEditor(Object element, IEditorPart[] unsavedEditors){
for (int i= 0; i < unsavedEditors.length; i++) {
if (EditorUtility.isEditorInput(element, unsavedEditors[i]))
return unsavedEditors[i];
}
return null;
}
private static ListSelectionDialog createUnsavedEditorDialog(List unsavedElements) {
int labelFlags= JavaElementLabelProvider.SHOW_DEFAULT | JavaElementLabelProvider.SHOW_POST_QUALIFIED;
Shell parent= JavaPlugin.getActiveWorkbenchShell();
String msg= ReorgMessages.getString("ReorgAction.checkSaveTargets"); //$NON-NLS-1$
ListSelectionDialog dialog= new ListSelectionDialog(parent, unsavedElements, new ListContentProvider(),
new JavaElementLabelProvider(labelFlags), msg);
dialog.setInitialSelections(unsavedElements.toArray());
return dialog;
}
private static void collectUnsavedEditors(List elements, List unsavedEditors, List unsavedElements) {
IEditorPart[] editors= JavaPlugin.getDirtyEditors();
for (int i= 0; i < editors.length; i++) {
for (Iterator iter= elements.iterator(); iter.hasNext(); ){
Object element= iter.next();
if (EditorUtility.isEditorInput(element, editors[i])) {
unsavedEditors.add(editors[i]);
unsavedElements.add(element);
}
}
}
}
private static String[] getElementNames(List elements){
String[] result= new String[elements.size()];
int i= 0;
for (Iterator iter= elements.iterator(); iter.hasNext(); ){
result[i]= ReorgUtils.getName(iter.next());
i++;
}
return result;
}
//overriden by d'n'd - must be protected
protected Object selectDestination(ReorgRefactoring refactoring) {
JavaElementContentProvider cp= new JavaElementContentProvider() {
public boolean hasChildren(Object element) {
// prevent the + from being shown in front of packages
return !(element instanceof IPackageFragment) && super.hasChildren(element);
}
};
ElementTreeSelectionDialog dialog= createDestinationSelectionDialog(JavaPlugin.getActiveWorkbenchShell(),
new DestinationRenderer(JavaElementLabelProvider.SHOW_SMALL_ICONS ),
cp,
refactoring);
dialog.setTitle(getActionName());
dialog.setValidator(new ReorgSelectionValidator(refactoring));
dialog.addFilter(new ContainerFilter(refactoring));
dialog.setSorter(new JavaElementSorter());
dialog.setMessage(getDestinationDialogMessage());
dialog.setSize(60, 18);
dialog.setInput(JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()));
dialog.setInitialSelection(computeCommonParent(refactoring.getElementsToReorg()));
if (dialog.open() != dialog.CANCEL)
return dialog.getFirstResult();
return null;
}
ElementTreeSelectionDialog createDestinationSelectionDialog(Shell parent, ILabelProvider labelProvider, JavaElementContentProvider cp, ReorgRefactoring refactoring){
return new ElementTreeSelectionDialog(parent, labelProvider, cp);
}
private static Object computeCommonParent(List elements){
if (elements.isEmpty())
return null;
Object parent= elements.get(0);
for (Iterator iter= elements.iterator(); iter.hasNext(); ){
parent= computeCommonParent(parent, iter.next());
}
IResource parentRes= getResource(parent);
IJavaElement parentElement= JavaCore.create(parentRes);
if (parentElement != null)
return parentElement;
return getResource(parent);
}
private static Object computeCommonParent(Object e1, Object e2){
IResource r1= getResource(e1);
IResource r2= getResource(e2);
if (r1 == null && r2 == null)
return null;
if (r1 == null)
return r2.getParent();
if (r2 == null)
return r1.getParent();
if (r1.equals(r2))
return r1.getParent();
if (r1.getFullPath().isPrefixOf(r2.getFullPath()))
return r1;
if (r2.getFullPath().isPrefixOf(r1.getFullPath()))
return r2;
IPath p1= r1.getParent().getFullPath();
IPath p2= r2.getParent().getFullPath();
IPath commonPath= new Path(""); //$NON-NLS-1$
int segCount= Math.min(p1.segmentCount(), p2.segmentCount());
for (int i= 0; i < segCount; i++){
if (p1.segment(i).equals(p2.segment(i)))
commonPath= commonPath.append(p1.segment(i));
else
break;
}
return ResourcesPlugin.getWorkspace().getRoot().findMember(commonPath);
}
private static IResource getResource(Object o) {
try{
if (o instanceof IResource)
return (IResource)o;
else if (o instanceof IJavaElement)
return ((IJavaElement)o).getCorrespondingResource();
else
return null;
} catch (JavaModelException e){
JavaPlugin.log(e);
return null;
}
}
//-----
private static class ContainerFilter extends PackageFilter {
private ReorgRefactoring fRefactoring;
ContainerFilter(ReorgRefactoring refactoring) {
Assert.isNotNull(refactoring);
fRefactoring= refactoring;
}
public boolean select(Viewer viewer, Object parent, Object o) {
if (fRefactoring.getElementsToReorg().contains(o))
return false;
return fRefactoring.canBeAncestor(o);
}
}
//-----
private static class DestinationRenderer extends JavaElementLabelProvider {
public DestinationRenderer(int flags) {
super(flags);
}
public String getText(Object element) {
try {
if (element instanceof IPackageFragmentRoot) {
IPackageFragmentRoot root= (IPackageFragmentRoot)element;
if (root.getUnderlyingResource() instanceof IProject)
return ReorgMessages.getString("DestinationRenderer.packages"); //$NON-NLS-1$
}
} catch (JavaModelException e) {
ExceptionHandler.handle(e, ReorgMessages.getString("ReorgDestinationAction.exception_title"), ReorgMessages.getString("ReorgDestinationAction.exception")); //$NON-NLS-2$ //$NON-NLS-1$
}
return super.getText(element);
}
}
//------
private static class ReorgSelectionValidator implements ISelectionValidator {
private ReorgRefactoring fRefactoring;
public ReorgSelectionValidator(ReorgRefactoring refactoring) {
Assert.isNotNull(refactoring);
fRefactoring= refactoring;
}
public IStatus validate(Object[] selection) {
if (selection.length != 1)
return new StatusInfo(IStatus.ERROR, ""); //$NON-NLS-1$
try{
if (fRefactoring.isValidDestination(selection[0]))
return new StatusInfo();
return new StatusInfo(IStatus.ERROR, ""); //$NON-NLS-1$
} catch (JavaModelException e){
ExceptionHandler.handle(e, ReorgMessages.getString("ReorgDestinationAction.exception_title"), ReorgMessages.getString("ReorgDestinationAction.exception")); //$NON-NLS-2$ //$NON-NLS-1$
return new StatusInfo(IStatus.ERROR, ""); //$NON-NLS-1$
}
}
}
}
|
15,305 |
Bug 15305 incorrect deletion of fields (multi-declaration case)
|
20020502+latest public class A { int i, j; } delete field i by calling (delete action i the outliner does it too) IField::delete(false, new NullProgressMonitor()); you end up with: public class A { j; }
|
resolved wontfix
|
f3586a8
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-06T10:18:44Z | 2002-05-06T10:13:20Z |
org.eclipse.jdt.ui.tests.refactoring/test
| |
15,305 |
Bug 15305 incorrect deletion of fields (multi-declaration case)
|
20020502+latest public class A { int i, j; } delete field i by calling (delete action i the outliner does it too) IField::delete(false, new NullProgressMonitor()); you end up with: public class A { j; }
|
resolved wontfix
|
f3586a8
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-06T10:18:44Z | 2002-05-06T10:13:20Z |
cases/org/eclipse/jdt/ui/tests/actions/DeleteSourceReferenceActionTests.java
| |
15,188 |
Bug 15188 Persist "update references" refactoring preference
|
The "Move" refactoring dialog should persist the "Update references to the moved element(s)" preference. In addition, the default setting for the button should be ON. The common case for a refactoring is that the user wants us to update references.
|
resolved fixed
|
afba086
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-06T10:52:08Z | 2002-05-03T15:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/reorg/JdtMoveAction.java
|
package org.eclipse.jdt.internal.ui.reorg;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.actions.MoveProjectAction;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.JavaElementContentProvider;
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.dialogs.ElementTreeSelectionDialog;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard;
import org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog;
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 (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, JavaElementContentProvider 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){
//XXX - pm
RefactoringStatus status= refactoring.checkPreconditions(new NullProgressMonitor());
if (status.hasFatalError())
RefactoringErrorDialogUtil.open(ReorgMessages.getString("JdtMoveAction.move"), status);//$NON-NLS-1$
else
super.doReorg(refactoring);
return;
}
//XX incorrect help
RefactoringWizard wizard= new RefactoringWizard(refactoring, ReorgMessages.getString("JdtMoveAction.move"), IJavaHelpContextIds.MOVE_CU_ERROR_WIZARD_PAGE); //$NON-NLS-1$
new RefactoringWizardDialog(JavaPlugin.getActiveWorkbenchShell(), wizard).open();
}
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 fCheckbox;
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 Control createDialogArea(Composite parent) {
Composite result= (Composite)super.createDialogArea(parent);
fCheckbox= new Button(result, SWT.CHECK);
fCheckbox.setText(ReorgMessages.getString("JdtMoveAction.update_references")); //$NON-NLS-1$
fCheckbox.setEnabled(canUpdateReferences());
fCheckbox.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
updatePreviewButton();
fRefactoring.setUpdateReferences(fCheckbox.getEnabled() && fCheckbox.getSelection());
}
});
fCheckbox.setSelection(canUpdateReferences());
return result;
}
protected void createButtonsForButtonBar(Composite parent) {
super.createButtonsForButtonBar(parent);
fPreview= createButton(parent, PREVIEW_ID, ReorgMessages.getString("JdtMoveAction.preview"), false); //$NON-NLS-1$
}
protected void updateOKStatus() {
super.updateOKStatus();
try{
fRefactoring.setDestination(getFirstResult());
fCheckbox.setEnabled(getOkButton().getEnabled() && canUpdateReferences());
updatePreviewButton();
} 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();
}
private void updatePreviewButton(){
fPreview.setEnabled(fCheckbox.getEnabled() && fCheckbox.getSelection());
}
private boolean canUpdateReferences(){
try{
return fRefactoring.canUpdateReferences();
} catch (JavaModelException e){
return false;
}
}
}
}
|
9,228 |
Bug 9228 Surround with try-catch works only if the selected code throws a exception
|
As there are runtime exceptions, wich can be interesting to catch by clients, it would be nice to allow the surround feature on any code snippet. Standard exception could be Throwable.
|
resolved fixed
|
5eda0a9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-06T14:10:53Z | 2002-02-07T13:53:20Z |
org.eclipse.jdt.ui.tests.refactoring/test
| |
9,228 |
Bug 9228 Surround with try-catch works only if the selected code throws a exception
|
As there are runtime exceptions, wich can be interesting to catch by clients, it would be nice to allow the surround feature on any code snippet. Standard exception could be Throwable.
|
resolved fixed
|
5eda0a9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-06T14:10:53Z | 2002-02-07T13:53:20Z |
cases/org/eclipse/jdt/ui/tests/refactoring/SurroundWithTests.java
| |
9,228 |
Bug 9228 Surround with try-catch works only if the selected code throws a exception
|
As there are runtime exceptions, wich can be interesting to catch by clients, it would be nice to allow the surround feature on any code snippet. Standard exception could be Throwable.
|
resolved fixed
|
5eda0a9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-06T14:10:53Z | 2002-02-07T13:53:20Z |
org.eclipse.jdt.ui/core
| |
9,228 |
Bug 9228 Surround with try-catch works only if the selected code throws a exception
|
As there are runtime exceptions, wich can be interesting to catch by clients, it would be nice to allow the surround feature on any code snippet. Standard exception could be Throwable.
|
resolved fixed
|
5eda0a9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-06T14:10:53Z | 2002-02-07T13:53:20Z |
extension/org/eclipse/jdt/internal/corext/codemanipulation/DeleteNodeEdit.java
| |
9,228 |
Bug 9228 Surround with try-catch works only if the selected code throws a exception
|
As there are runtime exceptions, wich can be interesting to catch by clients, it would be nice to allow the surround feature on any code snippet. Standard exception could be Throwable.
|
resolved fixed
|
5eda0a9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-06T14:10:53Z | 2002-02-07T13:53:20Z |
org.eclipse.jdt.ui/core
| |
9,228 |
Bug 9228 Surround with try-catch works only if the selected code throws a exception
|
As there are runtime exceptions, wich can be interesting to catch by clients, it would be nice to allow the surround feature on any code snippet. Standard exception could be Throwable.
|
resolved fixed
|
5eda0a9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-06T14:10:53Z | 2002-02-07T13:53:20Z |
extension/org/eclipse/jdt/internal/corext/codemanipulation/MemberEdit.java
| |
9,228 |
Bug 9228 Surround with try-catch works only if the selected code throws a exception
|
As there are runtime exceptions, wich can be interesting to catch by clients, it would be nice to allow the surround feature on any code snippet. Standard exception could be Throwable.
|
resolved fixed
|
5eda0a9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-06T14:10:53Z | 2002-02-07T13:53:20Z |
org.eclipse.jdt.ui/core
| |
9,228 |
Bug 9228 Surround with try-catch works only if the selected code throws a exception
|
As there are runtime exceptions, wich can be interesting to catch by clients, it would be nice to allow the surround feature on any code snippet. Standard exception could be Throwable.
|
resolved fixed
|
5eda0a9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-06T14:10:53Z | 2002-02-07T13:53:20Z |
extension/org/eclipse/jdt/internal/corext/dom/CompilationUnitBuffer.java
| |
9,228 |
Bug 9228 Surround with try-catch works only if the selected code throws a exception
|
As there are runtime exceptions, wich can be interesting to catch by clients, it would be nice to allow the surround feature on any code snippet. Standard exception could be Throwable.
|
resolved fixed
|
5eda0a9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-06T14:10:53Z | 2002-02-07T13:53:20Z |
org.eclipse.jdt.ui/core
| |
9,228 |
Bug 9228 Surround with try-catch works only if the selected code throws a exception
|
As there are runtime exceptions, wich can be interesting to catch by clients, it would be nice to allow the surround feature on any code snippet. Standard exception could be Throwable.
|
resolved fixed
|
5eda0a9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-06T14:10:53Z | 2002-02-07T13:53:20Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/LineEndDeleteTextEdit.java
| |
9,228 |
Bug 9228 Surround with try-catch works only if the selected code throws a exception
|
As there are runtime exceptions, wich can be interesting to catch by clients, it would be nice to allow the surround feature on any code snippet. Standard exception could be Throwable.
|
resolved fixed
|
5eda0a9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-06T14:10:53Z | 2002-02-07T13:53:20Z |
org.eclipse.jdt.ui/core
| |
9,228 |
Bug 9228 Surround with try-catch works only if the selected code throws a exception
|
As there are runtime exceptions, wich can be interesting to catch by clients, it would be nice to allow the surround feature on any code snippet. Standard exception could be Throwable.
|
resolved fixed
|
5eda0a9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-06T14:10:53Z | 2002-02-07T13:53:20Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/surround/ISurroundWithTryCatchQuery.java
| |
9,228 |
Bug 9228 Surround with try-catch works only if the selected code throws a exception
|
As there are runtime exceptions, wich can be interesting to catch by clients, it would be nice to allow the surround feature on any code snippet. Standard exception could be Throwable.
|
resolved fixed
|
5eda0a9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-06T14:10:53Z | 2002-02-07T13:53:20Z |
org.eclipse.jdt.ui/core
| |
9,228 |
Bug 9228 Surround with try-catch works only if the selected code throws a exception
|
As there are runtime exceptions, wich can be interesting to catch by clients, it would be nice to allow the surround feature on any code snippet. Standard exception could be Throwable.
|
resolved fixed
|
5eda0a9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-06T14:10:53Z | 2002-02-07T13:53:20Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/surround/SurroundWithTryCatchAnalyzer.java
| |
9,228 |
Bug 9228 Surround with try-catch works only if the selected code throws a exception
|
As there are runtime exceptions, wich can be interesting to catch by clients, it would be nice to allow the surround feature on any code snippet. Standard exception could be Throwable.
|
resolved fixed
|
5eda0a9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-06T14:10:53Z | 2002-02-07T13:53:20Z |
org.eclipse.jdt.ui/core
| |
9,228 |
Bug 9228 Surround with try-catch works only if the selected code throws a exception
|
As there are runtime exceptions, wich can be interesting to catch by clients, it would be nice to allow the surround feature on any code snippet. Standard exception could be Throwable.
|
resolved fixed
|
5eda0a9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-06T14:10:53Z | 2002-02-07T13:53:20Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/surround/SurroundWithTryCatchRefactoring.java
| |
9,228 |
Bug 9228 Surround with try-catch works only if the selected code throws a exception
|
As there are runtime exceptions, wich can be interesting to catch by clients, it would be nice to allow the surround feature on any code snippet. Standard exception could be Throwable.
|
resolved fixed
|
5eda0a9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-06T14:10:53Z | 2002-02-07T13:53:20Z |
org.eclipse.jdt.ui/core
| |
9,228 |
Bug 9228 Surround with try-catch works only if the selected code throws a exception
|
As there are runtime exceptions, wich can be interesting to catch by clients, it would be nice to allow the surround feature on any code snippet. Standard exception could be Throwable.
|
resolved fixed
|
5eda0a9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-06T14:10:53Z | 2002-02-07T13:53:20Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/util/CommentAnalyzer.java
| |
9,228 |
Bug 9228 Surround with try-catch works only if the selected code throws a exception
|
As there are runtime exceptions, wich can be interesting to catch by clients, it would be nice to allow the surround feature on any code snippet. Standard exception could be Throwable.
|
resolved fixed
|
5eda0a9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-06T14:10:53Z | 2002-02-07T13:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/LocalCorrectionsSubProcessor.java
|
package org.eclipse.jdt.internal.ui.text.correction;
import java.util.ArrayList;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jdt.core.IBuffer;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.Assignment;
import org.eclipse.jdt.core.dom.BodyDeclaration;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.ReturnStatement;
import org.eclipse.jdt.core.dom.SimpleName;
import org.eclipse.jdt.core.dom.Statement;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.codemanipulation.ImportEdit;
import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility;
import org.eclipse.jdt.internal.corext.dom.GenericVisitor;
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.surround.SurroundWithTryCatchRefactoring;
import org.eclipse.jdt.internal.ui.JavaPlugin;
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(ProblemPosition problemPos, ArrayList proposals) throws CoreException {
String[] args= problemPos.getArguments();
if (args.length == 2) {
ICompilationUnit cu= problemPos.getCompilationUnit();
String castDestType= args[1];
CompilationUnit astRoot= AST.parseCompilationUnit(cu, false);
ASTNode selectedNode= ASTResolving.findSelectedNode(astRoot, problemPos.getOffset(), problemPos.getLength());
int pos= problemPos.getOffset();
if (selectedNode != null) {
int parentNodeType= selectedNode.getParent().getNodeType();
if (parentNodeType == ASTNode.ASSIGNMENT) {
Assignment assign= (Assignment) selectedNode.getParent();
if (selectedNode.equals(assign.getLeftHandSide())) {
pos= assign.getRightHandSide().getStartPosition();
}
} else if (parentNodeType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
VariableDeclarationFragment frag= (VariableDeclarationFragment) selectedNode.getParent();
if (selectedNode.equals(frag.getName())) {
pos= frag.getInitializer().getStartPosition();
}
}
}
String cast= '(' + Signature.getSimpleName(castDestType) + ')';
String formatted= StubUtility.codeFormat(cast + 'x', 0, ""); //$NON-NLS-1$
if (formatted.charAt(formatted.length() - 1) == 'x') {
cast= formatted.substring(0, formatted.length() - 1);
}
String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.addcast.description", args[1]); //$NON-NLS-1$
InsertCorrectionProposal proposal= new InsertCorrectionProposal(label, cu, pos, cast, 1);
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
ImportEdit edit= new ImportEdit(problemPos.getCompilationUnit(), settings);
edit.addImport(castDestType);
proposal.getCompilationUnitChange().addTextEdit("import", edit); //$NON-NLS-1$
proposals.add(proposal);
}
}
public static void addUncaughtExceptionProposals(ProblemPosition problemPos, ArrayList proposals) throws CoreException {
ICompilationUnit cu= problemPos.getCompilationUnit();
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ASTNode selectedNode= ASTResolving.findSelectedNode(astRoot, problemPos.getOffset(), problemPos.getLength());
if (selectedNode == null) {
return;
}
while (selectedNode != null && !(selectedNode instanceof Statement)) {
selectedNode= selectedNode.getParent();
}
if (selectedNode != null) {
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
SurroundWithTryCatchRefactoring refactoring= new SurroundWithTryCatchRefactoring(cu, selectedNode.getStartPosition(), selectedNode.getLength(), settings);
refactoring.setSaveChanges(false);
if (refactoring.checkActivationBasics(astRoot, null).isOK()) {
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.surroundwith.description"); //$NON-NLS-1$
CUCorrectionProposal proposal= new CUCorrectionProposal(label, (CompilationUnitChange) refactoring.createChange(null), 0);
proposals.add(proposal);
}
}
BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode);
if (decl instanceof MethodDeclaration) {
String uncaughtName= problemPos.getArguments()[0];
MethodDeclaration methodDecl= (MethodDeclaration) decl;
SimpleName name= methodDecl.getName();
int pos= name.getStartPosition() + name.getLength();
StringBuffer insertString= new StringBuffer();
if (methodDecl.thrownExceptions().isEmpty()) {
insertString.append(" throws "); //$NON-NLS-1$
} else {
insertString.append(", "); //$NON-NLS-1$
}
insertString.append(Signature.getSimpleName(uncaughtName));
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.addthrows.description"); //$NON-NLS-1$
InsertCorrectionProposal proposal= new InsertCorrectionProposal(label, cu, pos, insertString.toString(), 0);
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
ImportEdit edit= new ImportEdit(cu, settings);
edit.addImport(uncaughtName);
proposal.getCompilationUnitChange().addTextEdit("import", edit); //$NON-NLS-1$
proposals.add(proposal);
}
}
public static void addMethodWithConstrNameProposals(ProblemPosition problemPos, ArrayList proposals) throws CoreException {
ICompilationUnit cu= problemPos.getCompilationUnit();
CompilationUnit astRoot= AST.parseCompilationUnit(cu, false);
ASTNode selectedNode= ASTResolving.findSelectedNode(astRoot, problemPos.getOffset(), problemPos.getLength());
if (selectedNode instanceof SimpleName && selectedNode.getParent() instanceof MethodDeclaration) {
MethodDeclaration declaration= (MethodDeclaration) selectedNode.getParent();
int start= declaration.getReturnType().getStartPosition();
int end= declaration.getName().getStartPosition();
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.constrnamemethod.description"); //$NON-NLS-1$
ReplaceCorrectionProposal proposal= new ReplaceCorrectionProposal(label, cu, start, end - start, "", 0); //$NON-NLS-1$
proposals.add(proposal);
}
}
public static void addUnusedVariableProposals(ProblemPosition problemPos, ArrayList proposals) throws CoreException {
ICompilationUnit cu= problemPos.getCompilationUnit();
CompilationUnit astRoot= AST.parseCompilationUnit(cu, false);
ASTNode selectedNode= ASTResolving.findSelectedNode(astRoot, problemPos.getOffset(), problemPos.getLength());
if (selectedNode instanceof SimpleName) {
selectedNode= selectedNode.getParent();
}
if (selectedNode instanceof VariableDeclarationFragment) {
ASTNode parent= selectedNode.getParent();
int start= parent.getStartPosition();
int end= start + parent.getLength();
IBuffer buf= cu.getBuffer();
while (end < buf.getLength() && Character.isWhitespace(buf.getChar(end))) {
end++;
}
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.removelocalvar.description"); //$NON-NLS-1$
ReplaceCorrectionProposal proposal= new ReplaceCorrectionProposal(label, cu, start, end - start, "", 0); //$NON-NLS-1$
proposals.add(proposal);
}
}
public static void addVoidMethodReturnsProposals(ProblemPosition problemPos, ArrayList proposals) throws CoreException {
ICompilationUnit cu= problemPos.getCompilationUnit();
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ASTNode selectedNode= ASTResolving.findSelectedNode(astRoot, problemPos.getOffset(), problemPos.getLength());
if (selectedNode != null) {
if (selectedNode.getParent() instanceof ReturnStatement) {
ReturnStatement returnStatement= (ReturnStatement) selectedNode.getParent();
Expression expr= returnStatement.getExpression();
if (expr != null) {
ITypeBinding binding= expr.resolveTypeBinding();
if (binding != null) {
if ("null".equals(binding.getName())) { //$NON-NLS-1$
binding= selectedNode.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
}
BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(returnStatement);
if (decl instanceof MethodDeclaration) {
ASTNode returnType= ((MethodDeclaration) decl).getReturnType();
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.voidmethodreturns.description") + binding.getName(); //$NON-NLS-1$
ReplaceCorrectionProposal proposal= new ReplaceCorrectionProposal(label, cu, returnType.getStartPosition(), returnType.getLength(), binding.getName(), 0);
proposals.add(proposal);
}
}
}
}
}
}
public static void addMissingReturnTypeProposals(ProblemPosition problemPos, ArrayList proposals) throws CoreException {
ICompilationUnit cu= problemPos.getCompilationUnit();
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ASTNode selectedNode= ASTResolving.findSelectedNode(astRoot, problemPos.getOffset(), problemPos.getLength());
if (selectedNode != null) {
BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode);
if (decl instanceof MethodDeclaration) {
final ITypeBinding[] res= new ITypeBinding[1];
res[0]= null;
decl.accept(new GenericVisitor() {
public boolean visit(ReturnStatement node) {
if (res[0] == null) {
Expression expr= node.getExpression();
if (expr != null) {
ITypeBinding binding= expr.resolveTypeBinding();
if (binding != null) {
res[0]= binding;
} else {
res[0]= node.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
}
} else {
res[0]= node.getAST().resolveWellKnownType("void"); //$NON-NLS-1$
}
}
return false;
}
});
ITypeBinding type= res[0];
if (type == null) {
type= decl.getAST().resolveWellKnownType("void"); //$NON-NLS-1$
}
String str= type.getName() + " "; //$NON-NLS-1$
int pos= ((MethodDeclaration) decl).getName().getStartPosition();
String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.missingreturntype.description", type.getName()); //$NON-NLS-1$
InsertCorrectionProposal proposal= new InsertCorrectionProposal(label, cu, pos, str, 1);
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
ImportEdit edit= new ImportEdit(problemPos.getCompilationUnit(), settings);
edit.addImport(type.getName());
proposal.getCompilationUnitChange().addTextEdit("import", edit); //$NON-NLS-1$
proposals.add(proposal);
}
}
}
public static void addNLSProposals(ProblemPosition problemPos, ArrayList proposals) throws CoreException {
final ICompilationUnit cu= problemPos.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, dialogTitle, true);
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
};
proposals.add(proposal);
}
}
|
9,228 |
Bug 9228 Surround with try-catch works only if the selected code throws a exception
|
As there are runtime exceptions, wich can be interesting to catch by clients, it would be nice to allow the surround feature on any code snippet. Standard exception could be Throwable.
|
resolved fixed
|
5eda0a9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-06T14:10:53Z | 2002-02-07T13:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/SurroundWithTryCatchAction.java
|
package org.eclipse.jdt.ui.actions;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.ui.texteditor.AbstractTextEditor;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.internal.corext.refactoring.base.ChangeContext;
import org.eclipse.jdt.internal.corext.refactoring.base.JavaSourceContext;
import org.eclipse.jdt.internal.corext.refactoring.base.RefactoringStatus;
import org.eclipse.jdt.internal.corext.refactoring.base.RefactoringStatusEntry;
import org.eclipse.jdt.internal.corext.refactoring.surround.SurroundWithTryCatchRefactoring;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor;
import org.eclipse.jdt.internal.ui.preferences.CodeFormatterPreferencePage;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation;
import org.eclipse.jdt.internal.ui.refactoring.RefactoringMessages;
import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringErrorDialogUtil;
import org.eclipse.jdt.internal.ui.refactoring.changes.AbortChangeExceptionHandler;
import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
public class SurroundWithTryCatchAction extends SelectionDispatchAction {
private CompilationUnitEditor fEditor;
private static final String TITLE= RefactoringMessages.getString("SurroundWithTryCatchAction.title"); //$NON-NLS-1$
public SurroundWithTryCatchAction(CompilationUnitEditor editor) {
super(editor.getEditorSite());
setText(TITLE);
fEditor= editor;
}
protected void run(ITextSelection selection) {
SurroundWithTryCatchRefactoring refactoring=
new SurroundWithTryCatchRefactoring(getCompilationUnit(), selection, JavaPreferencesSettings.getCodeGenerationSettings());
try {
RefactoringStatus status= refactoring.checkActivation(new NullProgressMonitor());
if (status.hasFatalError()) {
RefactoringErrorDialogUtil.open(TITLE, status);
RefactoringStatusEntry entry= status.getFirstEntry(RefactoringStatus.FATAL);
if (entry.getContext() instanceof JavaSourceContext && fEditor != null) {
JavaSourceContext context= (JavaSourceContext)entry.getContext();
ISourceRange range= context.getSourceRange();
fEditor.setHighlightRange(range.getOffset(), range.getLength(), true);
}
return;
}
PerformChangeOperation op= new PerformChangeOperation(refactoring.createChange(new NullProgressMonitor()));
op.setChangeContext(new ChangeContext(new AbortChangeExceptionHandler()));
new BusyIndicatorRunnableContext().run(false, false, op);
} catch (CoreException e) {
ExceptionHandler.handle(e, TITLE, RefactoringMessages.getString("SurroundWithTryCatchAction.exception")); //$NON-NLS-1$
} catch (InvocationTargetException e) {
ExceptionHandler.handle(e, TITLE, RefactoringMessages.getString("SurroundWithTryCatchAction.exception")); //$NON-NLS-1$
} catch (InterruptedException e) {
// not cancelable
}
}
protected void selectionChanged(ITextSelection selection) {
setEnabled(selection.getLength() > 0);
}
private final ICompilationUnit getCompilationUnit() {
Object editorInput= SelectionConverter.getInput(fEditor);
if (editorInput instanceof ICompilationUnit)
return (ICompilationUnit)editorInput;
else
return null;
}
}
|
9,374 |
Bug 9374 Surround with try/catch: doesn't work with static initializers
|
package tests; import java.io.*; public class D { private static InputStream input; static { input = new FileInputStream("myfile"); } } Can't surround input= .....
|
resolved fixed
|
b8025d2
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-06T14:51:10Z | 2002-02-11T09:33:20Z |
org.eclipse.jdt.ui.tests.refactoring/resources/SurroundWithWorkSpace/SurroundWithTests/D.java
| |
9,374 |
Bug 9374 Surround with try/catch: doesn't work with static initializers
|
package tests; import java.io.*; public class D { private static InputStream input; static { input = new FileInputStream("myfile"); } } Can't surround input= .....
|
resolved fixed
|
b8025d2
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-06T14:51:10Z | 2002-02-11T09:33:20Z |
org.eclipse.jdt.ui.tests.refactoring/resources/SurroundWithWorkSpace/SurroundWithTests/trycatch_in/TestInitializer.java
| |
9,374 |
Bug 9374 Surround with try/catch: doesn't work with static initializers
|
package tests; import java.io.*; public class D { private static InputStream input; static { input = new FileInputStream("myfile"); } } Can't surround input= .....
|
resolved fixed
|
b8025d2
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-06T14:51:10Z | 2002-02-11T09:33:20Z |
org.eclipse.jdt.ui.tests.refactoring/resources/SurroundWithWorkSpace/SurroundWithTests/trycatch_in/TestStaticField.java
| |
9,374 |
Bug 9374 Surround with try/catch: doesn't work with static initializers
|
package tests; import java.io.*; public class D { private static InputStream input; static { input = new FileInputStream("myfile"); } } Can't surround input= .....
|
resolved fixed
|
b8025d2
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-06T14:51:10Z | 2002-02-11T09:33:20Z |
org.eclipse.jdt.ui.tests.refactoring/resources/SurroundWithWorkSpace/SurroundWithTests/trycatch_out/TestInitializer.java
| |
9,374 |
Bug 9374 Surround with try/catch: doesn't work with static initializers
|
package tests; import java.io.*; public class D { private static InputStream input; static { input = new FileInputStream("myfile"); } } Can't surround input= .....
|
resolved fixed
|
b8025d2
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-06T14:51:10Z | 2002-02-11T09:33:20Z |
org.eclipse.jdt.ui.tests.refactoring/test
| |
9,374 |
Bug 9374 Surround with try/catch: doesn't work with static initializers
|
package tests; import java.io.*; public class D { private static InputStream input; static { input = new FileInputStream("myfile"); } } Can't surround input= .....
|
resolved fixed
|
b8025d2
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-06T14:51:10Z | 2002-02-11T09:33:20Z |
cases/org/eclipse/jdt/ui/tests/refactoring/SurroundWithTests.java
| |
9,374 |
Bug 9374 Surround with try/catch: doesn't work with static initializers
|
package tests; import java.io.*; public class D { private static InputStream input; static { input = new FileInputStream("myfile"); } } Can't surround input= .....
|
resolved fixed
|
b8025d2
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-05-06T14:51:10Z | 2002-02-11T09:33:20Z |
org.eclipse.jdt.ui/core
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.